Is there any scenario where a client/user/hacker can set $_SESSION variables themselves (excluding malicious software running on a server computer. I mostly mean via the browser)?
The reason I ask is because of this question that I asked a few days ago. Since then I have become pretty confused on the subject, but I've got a better idea of session fixation and hijacking.
To put it as simply as possible, if I validate every page with something like isset($_SESSION['validated']), is it secure?
Yes if you were assigning $_SESSION variables directly to unfiltered user input.
Which brings me to my point: NEVER TRUST INPUT FROM THE USER. EVER
If indeed you are filtering the input, then I don't see how it could be done.
Yes, it's possible. Read about Session poisoning and another quite common security issue Session fixation on Wikipedia or Google it - the web is full of articles about that.
I don't think $_SESSION variables can be changed unless the user has server access otherwise no they can't change it but filtering the variables or sanitizing it is recommended if it is something the user enters.
I do not quite understand the question, but this question explains my way of what I think that you want to do.
Make sure that you include jQuery.
Code:
<html>
<head>
<title>Tab name</title>
<meta charset = "UTF-8" />
<script type = "text/javascript" src = "http://code.jquery.com/jquery-1.1.13.min.js"></script>
<script type = "text/javascript" src = "script.js"></script>
</head>
<body>
</body>
</html>
Then make a file called addsession.php.
Code for addsession.php:
<?php session_start(); ?>
<?php
if(isset($_POST["name"])){
$name = $_POST["name"];
} else {
print '<p style = "color: red; font-weight: bold;">Name not defined!</p>' . "\n";
$name = "unknownsessionvariable";
}
if(isset($_POST["value"])){
$value = $_POST["value"];
} else {
$value = "";
}
$_SESSION[name] = value;
?>
Code for script.js:
function session(name, value){
$.post(addsession.php, {"name" : name, "value" : value});
window.location.reload(); // This line maybe should be here depending on what you are doing.
}
$(document).ready(function(){
session("sessvar", "supervalue");
});
Example code snippet:
function session(name, value){
$.post("http://www.eastonwerling.com/addsession.php", {"name" : name, "value" : value});
//window.location.reload();
$(document).ready(function(){
session("sessvar", "supervalue");
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<p>This example depends on www.eastonwerling.com (my website).</p>
Related
I have a PHP file that contains both the PHP Code and the JQuery Code. My motive is to set cookies as and when the PHP code is executing and read the cookies set by PHP in the JQuery part of the code and make some decision. But I'm not able to do that. What would be the best way for me to achieve this.
I'm new to PHP any help would be great.
<?php>
if(isset($_POST['StartProcess'])){
$Process_step = 1;
setcookie("MyCookie", $Process_step); sleep(30);
$Process_step = 2;
setcookie("MyCookie", $Process_step); sleep(30);}
<?>
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
window.setInterval(function(){
var abc = document.cookie.split(";").map(function(el){ return el.split("="); }).reduce(function(prev,cur){ prev[cur[0]] = cur[1];return prev },{});
console.log(abc["MyCookie"]);
if(Step == 1){ do something;}else if(Step == 1){ do something else;}
})
})</script>
<head>
<body></body>
</html>
If I understand your question correctly, you would like to use PHP session value on the JQuery.
You can print the variable of PHP in the JQuery line. You can do it like this
var myvalue = "<?PHP $phpvarname ?>"
or you can use PHP session and assign it on the var.
I am trying to write code to bring session variables from one php to another without refreshing. I tried to follow the example I found on web as below. It seems to bring the value successfully when loading the ajax page. However, the session variable created seems unable to be preserved even I use the session_start() command. Instead of loading the data, it shows the following error message:
Notice: Undefined index: numSum in C:\xampp\htdocs\test\update.php on line 5
I'd appreciate it if anyone can advise what to do with the code in order to get it right.
index.php
<html>
<?php
session_start();
?>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
j_TOC = [1,2,3,4,5];
$.ajax({
method: "POST",
url: "update.php",
data: { numSum: j_TOC}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
</script>
</html>
update.php
<html>
<?php
session_start();
session_save_path('/session_data/');
$_SESSION['numSum1'] = $_POST['numSum'];
?>
<script type="text/javascript">
function atest() {
var id_toc = <?php echo json_encode($_SESSION['numSum1']); ?>;
window.alert(id_toc);
{
</script>
<input type="button" id="clickme" onclick="atest()" value="update session"></>
</html>
There are few issues with your code, such as:
Normal code flow: When you first visit index.php, it will trigger the AJAX request, and will subsequently set the session variable; so that when you visit update.php page, you'll get the desired result.
Your code flow: Having said the above point, if you directly visit the update.php page without visiting index.php in the first place, you'll get this error,
Notice: Undefined index: numSum in ...
And that's because $_POST['numSum'] is not set, in fact, the entire superglobal $_POST array is empty.
So the solution is this,
Wrap this statement $_SESSION['numSum1'] = $_POST['numSum']; inside an if block, like this:
if(!isset($_SESSION['numSum1']) || empty($_SESSION['numSum1'])){
$_SESSION['numSum1'] = isset($_POST['numSum']) ? $_POST['numSum'] : array();
}
There's also a small syntax error in your code,
function atest() {
var id_toc = <?php echo json_encode($_SESSION['numSum1']); ?>;
window.alert(id_toc);
{ <============ See here, it should be }
You forgot to add a closing parentheses }
Finally, from the documentation,
... Session data path. If specified, the path to which data is saved will be changed. session_save_path() needs to be called before session_start() for that purpose.
Edited:
Change your if block in the following way,
if(!isset($_SESSION['numSum1']) || empty($_SESSION['numSum1']) || (isset($_POST['numSum']) && $_POST['numSum'] != $_SESSION['numSum1'])){
$_SESSION['numSum1'] = isset($_POST['numSum']) ? $_POST['numSum'] : array();
}
Also, learn about comparison operators in PHP, especially about ternary operator. The question mark(?:) you're talking about is related to ternary operator. Here are the necessary references,
http://php.net/manual/en/language.operators.comparison.php (Comparison operators)
http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary (Ternary operator)
session_save_path() should be called prior to session_start(), and if you're going to use it, use it both scripts where you use session_start()
update.php should just return a string for alert(). When you load that page directly, $_POST is empty, so that is the error you're seeing.
I want to pass JavaScript variables to PHP using a hidden input in a form.
But I can't get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?
Here is the code:
<script type="text/javascript">
// View what the user has chosen
function func_load3(name) {
var oForm = document.forms["myform"];
var oSelectBox = oForm.select3;
var iChoice = oSelectBox.selectedIndex;
//alert("You have chosen: " + oSelectBox.options[iChoice].text);
//document.write(oSelectBox.options[iChoice].text);
var sa = oSelectBox.options[iChoice].text;
document.getElementById("hidden1").value = sa;
}
</script>
<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<?php
$salarieid = $_POST['hidden1'];
$query = "select * from salarie where salarieid = ".$salarieid;
echo $query;
$result = mysql_query($query);
?>
<table>
Code for displaying the query result.
</table>
You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.
<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>
<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>
<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>
Just save it in a cookie:
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
It's not a pretty solution, but it works.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
Send the information in a form as stated here (will result in a page refresh)
Pass it in Ajax (several posts are on here about that) (without a page refresh)
Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
Here is the Working example: Get javascript variable value on the same page in php.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's how I did it (I needed to insert a local timezone into PHP:
<?php
ob_start();
?>
<script type="text/javascript">
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
<?php
$offset = ob_get_clean();
print_r($offset);
When your page first loads the PHP code first runs and sets the complete layout of your webpage. After the page layout, it sets the JavaScript load up.
Now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't - it needs to refresh the page. The only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP.
So, we use AJAX to get Javascript to interact with PHP without a page reload. AJAX can also be used as an API. One more thing if you have already declared the variable in PHP before the page loads then you can use it with your Javascript example.
<?php $myname= "syed ali";?>
<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>
The above code is correct and it will work, but the code below is totally wrong and it will never work.
<script>
var username = "syed ali";
var <?php $myname;?> = username;
alert(myname);
</script>
Pass value from JavaScript to PHP via AJAX
This is the most secure way to do it, because HTML content can be edited via developer tools and the user can manipulate the data. So, it is better to use AJAX if you want security over that variable. If you are a newbie to AJAX, please learn AJAX it is very simple.
The best and most secure way to pass JavaScript variable into PHP is via AJAX
Simple AJAX example
var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
$.ajax({
type: "POST",
url: "YOUR PHP URL HERE",
data:userdata,
success: function(data){
console.log(data);
}
});
PASS value from JavaScript to PHP via hidden fields
Otherwise, you can create a hidden HTML input inside your form. like
<input type="hidden" id="mydata">
then via jQuery or javaScript pass the value to the hidden field. like
<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>
Now when you submit the form you can get the value in PHP.
I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.
It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.
One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:
<img src="pic.php">
The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.
PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.
If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.
Here's a previous question that you can follow for more information: Ajax Tutorial
Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.
<?php
if(isset($_POST))
{
print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="data" value="1" />
<input type="submit" value="Submit" />
</form>
Clicking submit will submit the page, and print out the submitted data.
We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -
function statusChangeCallback(response) {
console.log('statusChangeCallback');
if (response.status === 'connected') {
// Logged into your app and Facebook.
FB.api('/me?fields=id,first_name,last_name,email', function (result) {
document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
console.log(document.cookie);
});
}
}
And I've accessed it (in any file) using -
<?php
if(isset($_COOKIE['fbdata'])) {
echo "welcome ".$_COOKIE['fbdata'];
}
?>
Your code has a few things wrong with it.
You define a JavaScript function, func_load3(), but do not call it.
Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
Your form has no means to submit it. It needs a submit button.
You do not check whether your form has been submitted.
It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:
<?php
if (isset($_POST['hidden1'])) {
echo "You submitted {$_POST['hidden1']}";
die;
}
echo <<<HTML
<form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
<input type="submit" name="submit" value="Test this mess!" />
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<script type="text/javascript">
document.getElementById("hidden1").value = "This is an example";
</script>
HTML;
?>
You can use JQuery Ajax and POST method:
var obj;
$(document).ready(function(){
$("#button1").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: "addperson.php",
type: "POST",
async: false,
data: {
username: username,
password: password
}
})
.done (function(data, textStatus, jqXHR) {
obj = JSON.parse(data);
})
.fail (function(jqXHR, textStatus, errorThrown) {
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
});
});
});
To take a response back from the php script JSON parse the the respone in .done() method.
Here is the php script you can modify to your needs:
<?php
$username1 = isset($_POST["username"]) ? $_POST["username"] : '';
$password1 = isset($_POST["password"]) ? $_POST["password"] : '';
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";
;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('success' => 1));
} else{
echo json_encode(array('success' => 0));
}
$conn->close();
?>
Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.
May be you could use jquery serialize() method so that everything will be at one go.
var data=$('#myForm').serialize();
//this way you could get the hidden value as well in the server side.
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
Use the + sign to concatenate your javascript variable into your php function call.
<script>
var JSvar = "success";
var JSnewVar = "<?=myphpFunction('" + JSvar + "');?>";
</script>`
Notice the = sign is there twice.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I know its REALLY simple, but I'm a newbie. I want to pass a variable from a PHP query via JS (for open-flash-chart) to the data file which is PHP.
This is my JS inside my PHP file. I'm pretty certian my issue is with the JS part since I've never used it before.
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript">
var player = "<? echo $player1 ?>";
swfobject.embedSWF(
"open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf", {"data-file":"data2.php"} );
</script>
I am trying to pass the $player variable to the graph data file which is this ( data2.php)
<?php
include("include/session.php");
include 'open-flash-chart/php-ofc-library/open-flash-chart.php';
if (isset($_GET['player'])) {
$player = $_GET['player']; }
$sql = "SELECT pos FROM nflscore where username = '$player'";
Assuming you want to use the var player change this in your swfobject.embedSWF call
{"data-file":"data2.php?player=" + player }
data2.php?variable="whatever variable"
on the php side do
$variable=$_GET["variable"];
now variable is the variable that you passed and you can do what you want with it
Well it pretty much depends on your needs!
Will javascript alter that variable? if not, the best way to transfer data between php pages are sessions! there are other options such as cookies, get vars, post vars etc. but users may change them putting your script in an uncomfortable position of dealing with wrong information if users do!
Using sessions your first page would simply look like this:
<?php session_start(); $_SESSION['player'] = $player; ?>
<!-- [...] -->
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf", {"data-file":"data.php"} );
</script>
<!-- [...] -->
session_start has to be put at the very beginning of your php file, no headers should be sent before that function!
Well, your data file would then just become something like this:
<?php session_start();
/* ...your includes and the rest... */
$sql = "SELECT pos FROM nflscore where username = '{$_SESSION['player']}'";
Using cookies instead is quite the same, you just don't have to start the session at the beginning of your script (but if its a game you should rely on them already)! whats best though, you can access the cookie afterwards in your javascript as well!
so that's what your first page should look like :
<?php setcookie('player', $player) // somewhere in the script ?>
<!-- [...] -->
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf", {"data-file":"data.php"} );
</script>
<!-- [...] -->
an your data page also becomes :
$sql = "SELECT pos FROM nflscore where username = '{$_COOKIE['player']}'";
The third easy option is to just drop the information where it should be right from the beginning ;) so no sessions, no cookies but just plain get variables!
first file :
<!-- [...] -->
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf",
{"data-file":"data.php?player=<?php echo $player ?>"} );
</script>
<!-- [...] -->
second file :
$sql = "SELECT pos FROM nflscore where username = '{$_GET['player']}'";
Things become different though if your javascript needs to change the variable's content
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
How do I access PHP variables in JavaScript or jQuery? Do I have to write
<?php echo $variable1 ?>
<?php echo $variable2 ?>
<?php echo $variable3 ?>
...
<?php echo $variablen ?>
I know I can store some variables in cookies, and access these values via cookies, but values in cookies are relatively stable values. Moreover, there is a limit, you can not store many values in cookies, and the method is not that convenient. Is there a better way to do it?
Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:
<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>
Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.
Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction.
jQuery.ajax is a good start IMHO.
If AJAX isn't an option you can use nested data structures to simplify.
<?php
$var = array(
'qwe' => 'asd',
'asd' => array(
1 => 2,
3 => 4,
),
'zxc' => 0,
);
?>
<script>var data = <?php echo json_encode($var); ?>;</script>
You're asking kind of a two-part question. As far as syntax (I think since PHP4?) you can use:
<?=$var?>
... if PHP is configured to allow it. And it is on most servers.
As far as storing user data, you also have the option of storing it in the session:
$_SESSION['bla'] = "so-and-so";
for persistence from page to page. You could also of course use a database. You can even have PHP store the session variables in the db. It just depends on what you need.
Basically, yes. You write alert('<?php echo($phpvariable); ?>');
There are sure other ways to interoperate, but none of which i can think of being as simple (or better) as the above.
I ran into a similar issue when building a custom pagination for a site I am working on.
The global variable I created in functions.php was defined and set to 0. I could output this value in my javascript no problem using the method #Karsten outlined above. The issue was with updating the global variable that I initially set to 0 inside the PHP file.
Here is my workaround (hacky? I know!) but after struggling for an hour on a tight deadline the following works:
Inside archive-episodes.php:
<script>
// We define the variable and update it in a php
// function defined in functions.php
var totalPageCount;
</script>
Inside functions.php
<?php
$totalPageCount = WP_Query->max_num_pages; // In my testing scenario this number is 8.
echo '<script>totalPageCount = $totalPageCount;</script>';
?>
To keep it simple, I was outputting the totalPageCount variable in an $ajax.success callback via alert.
$.ajax({
url: ajaxurl,
type: 'POST',
data: {"action": "infinite_scroll", "page_no": pageNumber, "posts_per_page": numResults},
beforeSend: function() {
$(".ajaxLoading").show();
},
success: function(data) {
//alert("DONE LOADING EPISODES");
$(".ajaxLoading").hide();
var $container = $("#episode-container");
if(firstRun) {
$container.prepend(data);
initMasonry($container);
ieMasonryFix();
initSearch();
} else {
var $newItems = $(data);
$container.append( $newItems ).isotope( 'appended', $newItems );
}
firstRun = false;
addHoverState();
smartResize();
alert(totalEpiPageCount); // THIS OUTPUTS THE CORRECT PAGE TOTAL
}
Be it as it may, I hope this helps others! If anyone has a "less-hacky" version or best-practise example I'm all ears.
I would say echo() ing them directly into the Javascript source code is the most reliable and downward compatible way. Stay with that unless you have a good reason not to.