file_get_contents Not Work If Value is Gained from Javascript - javascript

I want to read other sites on my web with file_get_contents(). My value can be with javascript merging.
My site page is : http://example.com/page.html#2010/09/awesome.html
JAVASCRIPT
var hash = window.location.hash.substr(1);
// results: 2010/09/awesome.html
PHP
$hash = "<script>document.write(hash);</script>";
$resultLink = "http://www.external-site.com/" .$hash;
$content = file_get_contents($resultLink);
$first_step = explode("<div class='post-entry'>" , $content );
$second_step = explode("</div>" , $first_step[1] );
echo $second_step[0];
Here $resultLink is : http://www.external-site.com/2010/09/awesome.html
But file_get_contents($resultLink) can not open the page.
How can I fix this code?

The problem here is JS is executed client side, which is AFTER the PHP is executed and produces content to send to the browser.
For example, by doing what you're doing $resultLink contains http://www.external-site.com/<script>document.write(hash);</script>

Related

DNI show div based on landing page, continue showing div entire session

I have about 60 landing pages that use different phone numbers on them. I am using a combination of WordPress and Advanced Custom Fields to place the phone numbers on their respective pages.
I am being asked to show a <div> based on the landing page URL that will not only show the phone number assigned to that page, but, keep showing the <div> (and phone number) regardless of what page the user navigates to on the website.
I have found little to no support on how to make the <div> remain visible throughout the entire session until the user closes the window.
I am thinking that this will somehow revolve around a cookie and Dynamic Number Insertion but I have no real progress to speak of. Should this be done using PHP or JS? Does a plugin exist that would allow for this on WordPress? I'm open to all suggestions.
Please try this code. Like #John C mentioned, WP Engine doesn't recommend Cookie nor PHP Session for the sake of performance and security. This is pure JavaScript code, and I think this will solve your problem.
Code in your Post/Page template file:
<div id="phone-number"></div>
<?php if( get_field('phone_number') ): ?>
<script type="text/javascript">
let phone_number = "<?php the_field('phone_number'); ?>";
</script>
<?php endif; ?>
Code in your theme JavaScript file:
<script type="text/javascript">
// in the case of the div data is persistent on the same site
// let storage = localStorage;
// in the case of the div data is persistent in the same tab, but not in new tab
let storage = sessionStorage;
let key = "phone_number"; // storage key
var global_phone_number = storage.getItem(key);
// check if storage data is set before
if (null === global_phone_number) {
// if not set the data on page into storage
global_phone_number = phone_number ? phone_number : '';
storage.setItem(key, global_phone_number);
}
document.getElementById('phone-number').innerHTML = global_phone_number;
</script>
You should use PHP and capture the session.
(untested code warning)
add_action('wp_footer', 'dynamic_phone_div');
function dynamic_phone_div() {
session_start;
if(isset($_SESSION['phone_div']) ? $phone_div = $_SESSION['phone_div'] :
$phone_div = '';
if($phone_div != '') {
echo '<div class="that_div_thing">';
echo $phone_div;
echo '</div>';
} else {
$_SESSION['phone_div'] = 123456789;
echo '<div class="that_div_thing">';
echo '123456789';
echo '</div>';
}
}
This is only raw logic. I am not sure where your div is (header/footer/page) - depending on where it is you should either use a hook (header/footer) or code it into a template (page/post).
The session will be destroyed after the user closes the tab/window.
I would probably do this with client side session storage. Providing all pages open in the same tab, the value will remain for the session, then be removed.
PHP code (in your functions.php file?) would be something like this:
function phone_script() {
$params = array(
'phone_number' => null, // Insert logic for current number. Can stay null if this is running on a non-landing page
'is_landing_page' => false // Change to true/false based on is current page a landing one or not
);
$params = json_encode( $params );
echo <<< EOT
<script>
let settings = $params;
document.addEventListener("DOMContentLoaded", function() {
if( settings.is_landing_page ) {
window.sessionStorage.setItem( 'phone-number', settings.phone_number );
} else {
settings.phone_number = window.sessionStorage.getItem( 'phone-number' );
}
if( settings.phone_number ) {
let div = document.createElement('div');
div.classList.add('phone-div');
// or add inline style
// div.style.cssText = 'position:fixed'; //etc
// Some logic here to actually add the number and any other content to the div
div.innerHTML = `The Phone number is: ${settings.phone_number}`;
document.body.appendChild(div);
}
});
</script>
EOT;
}
add_action( 'wp_footer', 'phone_script');
Note that the EOT; line MUST have no leading or trailing spaces.
The above is untested.

JS don't passes data in POST request to the php file, or php can't recieve it

I have a JS function that has to pass two variables to the php file by POST, however variables in php are "Null"
JS script
function a(){
var name = document.getElementById("fio");
var tel = document.getElementById("tel");
if(name!=""&&tel!="")
{
dannie = {'polz_name':name, 'polz_tel':tel};
$.post('senda.php', dannie, function(otvet_serv){
rezultat = '<div style="color:#D80018;">'+otvet_serv.text+'</div>';
$("#form_result").hide().html(rezultat).slideDown();
}, 'json');
}
}
PHP file
$user_Name = filter_var($_POST["polz_name"], FILTER_SANITIZE_STRING);
$user_Phone = filter_var($_POST["polz_tel"], FILTER_SANITIZE_STRING);
In html part of the document "fio" and "tel" was names, not ids. I added id parameter to them, and it worked

adding Advanced Custom Field to javascript

I have created an ACF option in the admin so a user can add cookie notice text via the admin...The javascript script I'm using creates the message within the javascript so I'm wanting to echo the ACF field within the javascript.
At the top of my cookie.js file I have: "<?php $cooke_msg = the_field('cookie_notice', 'option'); ?>"; and I'm echoing it within a var like so: var msg = "<?php echo $cookie_msg; ?>"; so the top of my file looks like this:
"<?php $cooke_msg = the_field('cookie_notice', 'option'); ?>";
(function(){
//Change these values
var msg = "<?php echo $cookie_msg; ?>";
var closeBtnMsg = "OK";
var privacyBtnMsg = "Privacy Policy";
var privacyLink = "https://www.google.com";
//check cookies
if(document.cookie){
var cookieString = document.cookie;
var cookieList = cookieString.split(";");
// if cookie named OKCookie is found, return
for(x = 0; x < cookieList.length; x++){
if (cookieList[x].indexOf("OKCookie") != -1){return};
}
}
What I'm getting when I view the site is: <?php echo $cookie_msg; ?> and not the actual message from ACF...is there a way of actually doing this?
Wordpress giving nice function to pass PHP variable data to js file.
Put this code in your theme functions.php page.
function mytheme_load_scripts() {
wp_enqueue_script('mytheme-script', get_template_directory_uri() . '/js/mytheme-script.js');
wp_localize_script('mytheme-script', 'mytheme_script_vars', array(
'alert' => get_field("cookie_notice",$post_id)
)
);
}
add_action('wp_enqueue_scripts', 'mytheme_load_scripts');
And Create one js folder in your theme root directory. Inside that directory create the js file named mytheme-script.js file, & put the below code over there.
jQuery(document).ready(function($) {
alert( mytheme_script_vars.alert );
});
Now visit any page of your site. Surely you will get an alert with the your desire field value. Make sure you will assign proper value to $post_id. I think this will help you. Codex reference link for more details: WP Localize Script Function

Set the value/text of a div using javascript/jquery - inside a php LOOP

I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys.
Objectives:
Retrieve data from database.
Set the value of an element using javascript/jquery (inside a loop) from the database.
Make the value a link
I have this a_link column from links table with the ff. values:
- www.google.com
- https://www.google.com
- www.stackoverflow.com
And here is my code:
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id = "linkhere"></span>
</div>
<script>
var link = "<?php echo $thelink; ?>";
$("#linkhere").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
<?php
}
?>
Any help would be highly appreciated. Thanks.
#aimme is technically not wrong about using a different database library. Please read "Why shouldn't I use mysql_* functions in PHP?" for reasons why not to use mysql_ and for some neat alternatives, some tutorials, and some good reads. (yes, all in the same page! just scroll down)
I think you're trying to:
display a <div> of class 'row'
with an <a> tag inside that uses the 'a_link' column of the 'links' table as the href and the label.
The href for the tag must always have a scheme (http://).
Just PHP and HTML
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$regexMatches = array();
// removed (what seemed to be) needless groups in regex
$urlFound = preg_match("#((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);
if($urlFound === 1) {
// only add http:// if http:// was not detected
$href = ($regexMatches[2] === "www." ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php }
}
?>
This code won't echo a row if a_link doesn't contain either 'http://' or 'www.' in it. so google.com will not be displayed.
Of note, as written, the regex will work on "urls" like 'applewww.google.com'. Don't know if that matters. Adding a '^' to the beginning of the regex may solve the problem (like so:preg_match("#^((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);)
A (better|different) solution could use parse_url($url)
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$href = (parse_url($theLink,PHP_URL_SCHEME) === NULL ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php
}
?>
However, using parse_url() would mean any old string would be displayed (while the first solution would not display any links that didn't have either http:// or www.) but since your pulling from a table called 'links' it's probably safe to assume everything is a valid path.
That's not how it works, that's not how any of this works
Now let's assume that you really need to use Javascript to process your generated links (which is not).
You first need to separate your Javascript code from your PHP code. You will only use Javascript once you have fetched your data and generated some output.
I guess you just want some kind of working code
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink)) :
$link = $rowlink['a_link'];
?>
<div class="row">
</div>
<?php
endwhile;
?>
<script type="text/javascript">
$(function() {
$('.row a').each(function() {
var urlified = urlify($(this).data('url'));
$(this).attr('href', urlified.url)
.text(urlified.label);
});
});
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var label = (c == 'www.') ? 'http://' +url : url;
return {url: url, label: label};
});
}
</script>
First i want to advice that use PDO or mysqli instead of mysql. as it
is vulnerable to sql injection and its depreciated.
"I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys."
for that i would say Php is a server side language whereas javascript is a client side language. and Ajax is the way to manipulate client side from server vice versa, without refreshing the whole page.
below is just a demonstration that i edited little bit from your code to show the separation of server side and client side code and to just give an idea how it works.I don't know whether the code will work or not. haven't tested. php code (server side) will be executed first but could control the display of it using javascript(client side) functions inside document.ready() or window.load() to apply the affects as soon as possible.Through this we could bring changes to the links that we want before its being shown to the client . For each of the link retrieved and displayed you could use a specific class and jquery .each() function to apply certain fix to the selected link as Lyes BEN mentioned above or all the elements with a specific class could be manipulated as a whole without using .each.
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
echo '<div class = "row">
<span id = "linkhere">
</span>
</div>';
}
?>
<script>
$("#linkhere a").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
You can implement this using php with parse_url function (http://php.net/manual/en/function.parse-url.php) to get different components.
In parse_url, there is 'scheme' key for http or https.
Then to do this with php, just call formatUrl function to make the url
<?php
function formatUrl($url)
{
$urlData = parse_url($url);
if(!isset($urlData['scheme'])) {
$url = 'http://' . $url;
}
return '' . $url . '';
}
?>
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id="linkhere"><?php echo formatUrl($thelink)?></span>
</div>
<?php
}
?>

Update my php array in javascript function

I want to update or add new key=>value to my php array in javascript function.
The paging is in ajax, page is not reloaded again.
Actually I am receiving the data in a text file which is uploaded on my server. I parse that file and get a limited number of records, when I click on NEXT then one more file is uploaded on server and I parse it once again and show the data. So, I want that all data to be stored in php array on that page so when next time I go to PREVIOUS record, it doesn't parse the file once again, just show the data from the array.
//php array name is $call_data
var file_data = <?php $content = #file_get_contents("text file name");
$content = rawurldecode($content);
$new_call_data = json_decode( $content );
foreach ($new_call_data->CALLS as $key => $val) {
$call_data['CALLS'][] = $val; $file_rec_start++;
}
echo json_encode( $call_data ); ?>;
i don't see the part, where you split your "content" part into peaces so you have to reload the page, is it missing or is this part in JavaScript?
also you could minify you source:
<?php
$my_contents = file_get_contents('myfile.json');
$my_contents = rawurldecode($my_contents);
$my_array = json_decode($content);
$my_json = json_encode(array_values($my_array->CALLS));
?>
var file_data = <?=$my_json?>;
than you can itterate trough the array in javascript without the need of refreshing the page.
you could use
var results_per_page = 25
var page_available = Math.ceil(file_data.length / results_per_page);
var page = 0;
var page_array = file_data.slice((page * results_per_page), ((page+1)*results_per_page));

Categories

Resources