setting and getting session variables - php

I am trying to set a session variable in a php script and get the variable in
a javaScript.
In the php program I put an echo command to see if the variable
is generated. Nothing happens.
In the javascript I try to write the variable to the screen and I see nothing. If I put single quotes around the get command I just get a display of that command.
php:
$full_name = $_POST['Full_Name']; // required
$names = explode(" ", $full_name);
$_SESSION['myvar'] = $names[0];
echo ($names[0]);
javascript:
<script type="text/javascript">
var name = #Session["myvar"];
document.write(name);
</script>

Direct use of PHP in a JS-script is really not useful if you want to make it scalable.
Use it like this
myprintoutscript.js
function writeOnDocument(name){
document.write(name);
}
In most cases it is better to call a js-function from the outside with a variable (in your case the session)
index.php
<script>
//referencing to function in myPrintOutScript.js
writeOnDocument("<?= $_SESSION['myvar'] ?>");
</script>
Or readout a html data-attribute, for example a body
index.php
<body data-session-name="<?= $_SESSION['myvar'] ?>">
and call it from a script:
windowIsLoadedScript.js
var body = document.getElementsByTagName("BODY")[0],
name = body.getAttribute("data-session-name");
//referencing to function in myPrintOutScript.js
writeOnDocument(name);
The more you keep things separated, the easier it is to make your building blocks stack on to each other.

Writing JavaScript with PHP...hmmm...as a programmer that has inherited code where other programmers did this...Please don't. It's hard to see what's going on when you start mixing languages together.
As to your actual problem...generally, you put stuff into the Session that you want to keep "secret", or stuff that you have already properly secured, like the User's ID value of who is logged in so that when they go to the next page, you see the User ID in a session and you trust that data because it came from your server rather than the user. POST, GET, and COOKIE data is insecure, so you don't trust what the user is sending you.
In any case, for stuff that you want to be accessible to both PHP AND Javascript, if you're not using web services, I would suggest using cookies might be the better practice.
setcookie('FirstName',$_SESSION['myvar']);
http://php.net/manual/en/function.setcookie.php
Admittedly, getting cookie values with JavaScript is a pain in itself, but people have already written the code for you, so it shouldn't be as painful:
Get cookie by name
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
var name = getCookie('FirstName');
[EDIT] I would also say that the other poster's answer, putting it into a data-attribute within the HTML, is also a good practice and more clear than writing to JS directly.
<body data-first-name="<?php echo htmlspecialchars($firstName) ?>">

write session_start(); at the starting of the php file.
then catch the variable into js like this.
<script type="text/javascript">
var name ="<?php echo $_SESSION['myvar'];?>";
document.write(name);
</script>

Related

Calling javascript from php script issue

I have a php script which is editing records in mysql table. I have an issue in refreshing the page using javascript by passing the record number.
Pl check below are the few lines of my php script:
if ($mode == "edit")
{
$ids=$_POST[prs_rid];
$edt1=mysql_query("SELECT * FROM ECRDTL_edit WHERE id='$ids'");
$edt2=mysql_fetch_assoc($edt1);
echo "<script>var x=document.getElementById('prs_rid').value</script>";
echo "<script> alert (x);</script>";
echo "<script>document.location.href='ecr-detail-edit.php?prs_mode=edit&prs_id='+x;</script>";
}
I have used alert to see if variable "x" is getting the record value or not, this works fine. But when i use the same in the next line, it is not showing the same record in the edit mode of my php.
But if I put the same line in address bar of a browser like this, it works fine:
http://www.mydomain.com/ecr-detail-edit.php?prs_mode=edit&prs_id=27
Kindly check what could be the issue or is there any other way of refreshing the page passing the record number.
Just use the location.href object which (as specified in MDN window.location) belongs to the window object, not document.
So your last line of code should read like:
echo "<script>location.href='ecr-detail-edit.php?prs_mode=edit&prs_id='+x;</script>";
On another note, you will get better browser support using the script tags as <script type="text/javascript">
Relative URL's don't work when assigned to location.href, it should be absolute or fully qualified.
In your case, absolute will do:
location.href = location.pathname + '?prs_mode=edit&prs_id=' +
encodeURIComponent(x)
The location.pathname gives the path (starting with /) up to the query separator (question mark).
I've also added encodeURIComponent(x) to make sure the value of x is properly escaped if necessary.
Implementation
echo "<script>location.href = location.pathname + '?prs_mode=edit&prs_id=' + encodeURIComponent(x);</script>";
The problem is that window.location needs an absolute, http:// URL. Use the following code:
window.location=window.location=location.protocol+'//'+location.host+location.pathname+"?get_variables_here";
document.location.href='ecr-detail-edit.php?prs_mode=edit&prs_id='+x;
should be
location.href='ecr-detail-edit.php?prs_mode=edit&prs_id='+x;
and also you should use mysql_real_escape_string() to escape malicious data user may pass on to your script.
hence change
$ids = $_POST['prs_rid'];
to
$ids = mysql_real_escape_string($_POST[prs_rid]);
you are missing script type, when you want to use javascript you need to tell to browser that the code being declared is of javascript, you need to change
<script>
to
<script type="text/javascript">
you are missing single quotes in your POST data. add single quotes to the following.
$ids = $_POST['prs_rid'];
one last thing is i would never output javascript with PHP. it is better you keep javascript and PHP different. for example your above code can be changed to.
<?php
if ($mode == "edit"):
$ids = mysql_real_escape_string($_POST['prs_rid']);
$result = mysql_query("SELECT * FROM ECRDTL_edit WHERE id='$ids'") or die(mysql_error());
$row = mysql_fetch_assoc($result);
?>
<script type="text/javascript">
var x = document.getElementById('prs_rid').value
alert(x);
location.href = 'ecr-detail-edit.php?prs_mode=edit&prs_id='+x;
</script>
<?php endif; ?>
Try this..
echo "<script type='text/javascript'>window.location.href='ecr-detail-edit.php?prs_mode=edit&prs_id='+x;</script>";
For this line to execute successfully, var x=document.getElementById('prs_rid').value in PHP, the html dom should be loaded first else it will give an error, which might be the issue here.

get #var from url in php code error

i want to get #var value from url like my url is mydomain.com/index.php#1 so i want to get has(#) value from url which is 1 after some research i got this article http://www.stoimen.com/blog/2009/04/15/read-the-anchor-part-of-the-url-with-php/
i use this code for get has(#) value, this is work fine in JavaScript but this is not work in php my code is :
<script language="javascript">
var query = location.href.split('#');
document.cookies = 'anchor=' + query[1];
alert(query[1]);
</script>
<?php
echo $_COOKIE['anchor'];
?>
this code give me alert value in JavaScript but not echo value. any solution for that ?
Additionally, you seem to set wrong property in JS (it's .cookie, not .cookies):
document.cookie = 'anchor' + query[1];
The cookie you are setting will not be visible to PHP until the next page request. The article you link to states this explicitly:
Of course, yes. This is not working correctly. In fact it’s working
correctly from the second load on, but on the initial load of the page
the $_COOKIE array does not has any anchor key inside. That’s because
this part of the code is executed before the browser setup the cookie
on the client.
There is a "workaround" presented in that article, but frankly: this sort of thing is rubbish and you should simply not put this information (only) in the query fragment if you want PHP to read it.
By article which you sent, you must do a redirect like:
<?php if (!$_COOKIE['anchor']){ ?>
<script language="javascript">
var query = location.href.split('#');
document.cookie = 'anchor=' + query[1];
window.location.reload();
</script>
<?php } ?>
<?php
echo $_COOKIE['anchor'];
?>
You are setting a cookie that wont be passed to php until next reload. Am I wrong?
Client dynamics is the end of the chain.
Use this method to prevent errors:
<script>
query=location.hash;
document.cookie= 'anchor'+query;
</script>
And of course in PHP, explode that puppy and get one of the values
$split = explode('/', $_COOKIE['anchor']);
print_r($split[1]); //to test it, use print_r. this line will print the value after the anchortag

PHP & Javascript: Unsecure?

Is it unsecure to embed PHP code in a javascript function?
My friend told me not to do it.
My script just inserts a number in the database if the message has been clicked (read).
<!--Insert into database when click-->
<script>
function insert()
{
<?php
include 'db_connect.php';
$usermsg = $_SESSION['username'];
$message_id = $_GET['messageid'];
mysql_query("UPDATE messages SET message_read='1' WHERE id='$message_id' AND to_user='$usermsg'");
?>
}
</script>
Should i do this any otherway? Or drop including php & mysql in my script and start over?
Your friend probably told you not to do it because it makes no sense whatsoever.
PHP is a preprocessing language whose parser runs on the webserver. The result of running PHP is the HTML/Javascript that your browser sees. Your PHP does not output anything (merely silently performing the SQL query whilst your HTML/Javascript page is being generated), so the Javascript that your browser sees is:
<script>
function insert()
{
}
</script>
PHP cannot be "inside" a Javascript function at all. There is no such concept.
Instead, consider an HTML form, or read up about "AJAX" when you're slightly more familiar with the web technologies heirarchy.
If you try that code, it won't even work that way. You cannot embed server side code in javascript function.
What you want is to make a sepearate request that will handle the request. This method is called AJAX. With jQuery library you can make AJAX POST request like this:
<script>
function insert()
{
//Example: Request the test.php page and send some additional data along (while still ignoring the return results).
$.post("test.php", { messageid: "1" } );
}
</script>
In test.php:
<?php
//Get Post Variables. The name is the same as
//what was in the object that was sent in the jQuery
if (isset($_POST['messageid'])) {
include 'db_connect.php';
$usermsg = $_SESSION['username'];
$message_id = $_POST['messageid'];
mysql_query("UPDATE messages SET message_read='1' WHERE id='$message_id' AND to_user='$usermsg'");
}
?>
Read the Beginners Guide to Using AJAX with jQuery
And don't forget to use parametrized sql to prevent sql injection attacks as this code in its current state is vulnurable.
It's insecure in that it's entirely possible for PHP to insert some text into the page that breaks the javascript. e.g.
<?php
$name = "O'Brien";
?>
<script type="text/javascript">
var name = <?php echo $name ?>;
</script>
This would produce:
var name = O'Brien;
which is illegal JS syntax. You're assigning an undefined variable O, which is immediately followed by an unterminated string literal 'Brien. Surrounding this with quotes in the PHP page accomplishes nothing either:
var name = '<?php echo $name ?>';
^ ^-- added quotes
which now gives
var name = 'O'Brien';
Now you've got a slightly different problem: Assigning a perfectly valid string literal 'O', followed immediately by an undefined variable Brien, followed by an unterminated string literal ';.
The proper way to have PHP output text into a JS code block safely is to use json_encode:
var name = <?php echo json_encode($name) ?>;
which produces:
var name = "O'Brien";
and off you go.
PHP/MySql runs on the web server. Javascript runs on the browser.
You should also think that anything that comes from the browser may be faked - therefore should validate/verify it. Javascript just makes the users experience more interactive as it does not require communication across the network. Use AJAX or forms to do the comms.

jQuery: Load body of page into variable

I'm using jQuery to load the result of a PHP script into a variable. The script is passed something that the user typed with a GET request. I want to take just what the script spit out into its <body> tag. Here's what I've tried:
JS:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {dataloaded = loaded;});
alert($(dataloaded).find('body'))
}
But it just displays [Objec object]. How can I get a useful value that is just the contents of the body of a loaded page?
I know the PHP works, I just need the JS.
The script echos something like 1!!2 (two numbers separated by two exclamation points).
Thanks!
You are trying to access the dataloaded which might not be assigned due to the asynchronous nature of AJAX calls. The only safe place to access it is inside the success callback. Also you could use the .html() function to get the contents of the body tag:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get('script.php', { i: typed }, function(loaded) {
alert($(loaded).find('body').html());
});
}
Also note that if the script.php only echoes 1!!2 without a <body> tag it won't work.
Without knowing what console.log prints it is hard to say, but try these
alert($(dataloaded).find('body').html());
Or
alert($(dataloaded).find('body').text());
I changed the page that I'm trying to fetch to XML. I'm using $.find to get each element of interest individually from the XML page, which suits this particular app well.
This problem has disappeared, as there is no longer a head section to ignore, and I'm just grabbing individual XML elements anyway.
Thanks for all your time and help!
Use JSON type. I am not sure about whether your Jquery script correct or not but using JSON with a correct usage would solve problem. ie.:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {dataloaded = loaded;},"json");
alert($(dataloaded).find('body'))
}
And POST variable from script.php after encoding JSON. Use Php's json_encode() function. You need to create variable as an array. For example:
<?php
$title = 'Hello World';
$content = 'Get well soon Japan!';
$arr=array('title'=>$title,'content'=>$content);
echo json_encode($arr);
?>
And Jquery would be something like:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {var dataloaded = loaded.title+" "+loaded.content;},"json");
$("body").html(dataloaded);
}
You may need to use Jquery's parseJson() functions on some situations. Don't think you will need here.

How do I assign a javascript variable to a PHP variable?

I have a javascript variable which holds some information and I want that to assign in a PHP variable. Here is what I am using:
<script type="text/javascript">
function redirectToFacebook()
{
var facebookMessage = encodeURI(document.getElementById('txt_msg').value);
}
</script>
<?php
$_SESSION['sess_facebook_message'] = facebookMessage;
?>
Any help is really appriciable.
Thanks in advance
Because PHP runs on the server, and JavaScript in the client, there is no way to set a PHP session variable after JavaScript works with it, as PHP has done executing before the page was even sent.
However...
If you use JavaScript to make a request (AJAX, imagehack or otherwise) to a PHP script that sets the variable, you can.
For example...
JavaScript:
function something() {
// do something with somevar
somevar = 'content';
// make an AJAX request to setvar.php?value=content
}
PHP:
$_SESSION['somevar'] = $_GET['somevar'];
Make sure you take security issues of client-generated data into account, though.
If you want to pass variables from the browser (javascript) to your backend server (PHP), you need to either:
1) Load a new page with Javascript parameters encoded either as POST or GET
2) Asynchronously call a PHP script (AJAX call) encoding the parameters as POST or GET
A simple example using a GET request (you simply append your parameters to the URL):
<script>
window.location = '/some-url?' + document.getElementById('text_msg').value;
</script>
You probably want to assign this piece of code to a button or something...
what you are trying to achieve is not possible due to API limitation.It does not provide that.
may be you can try to redirect with javascript and pass variables form php to js. They way yout tru it, it can't work.
may be, im realy not shure
try this.
<?php
function redirectToFacebook() {
var facebookMessage = ?>
<script>
document.write(encodeURI(document.getElementById('txt_msg').value));
</script>
<?php
}
?>
or using cookies.

Categories