You could do something like
<script>
php_variable = <?= json_encode($php_variable) ?>;
</script>
which should even let you do arrays and possibly objects. It requires PHP 5.2 or later, though. If you're stuck without json_encode
, you could wrap quotes around a call to addslashes
, but that won't let you do arrays and such.
If your intent is to set the value within some form, you can do like
<input type="text" name="stuff" value="<?= htmlentities($stuff) ?>">
and of course, you could access that element's value within your script if necessary.
Two key points to take away here:
Since PHP is generating the page, it can output stuff as it pleases -- even right in the middle of a <script>
element. You can use this to transfer variables from server to client, but not vice versa. (Transferring client variables...well...that's effectively going to require XHR or a form submit.)
But always* escape stuff going from PHP to anywhere -- particularly if it's going into HTML, JS, or directly into SQL. Unless you have your server set all retarded (enabling magic quotes, for example), PHP will get the data raw, and it could have special chars that will cause one or all of those to break.
* Ok, not quite always. If you have a PHP variable that contains some HTML or JS you want to output as HTML/JS, then don't escape it. But you should be aware of what "XSS" means, and don't blindly output data supplied by a user.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…