get #var from url in php code error - php

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

Related

Find targeted #id from parent includer with php [duplicate]

Assuming a URL of:
www.example.com/?val=1#part2
PHP can read the request variables val1 using the GET array.
Is the hash value part2 also readable? Or is this only upto the browser and JavaScript?
The main problem is that the browser won't even send a request with a fragment part. The fragment part is resolved right there in the browser. So it's reachable through JavaScript.
Anyway, you could parse a URL into bits, including the fragment part, using parse_url(), but it's obviously not your case.
Simple test, accessing http://localhost:8000/hello?foo=bar#this-is-not-sent-to-server
python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"
Serving HTTP on 0.0.0.0 port 8000 ...
localhost - - [02/Jun/2009 12:48:47] code 404, message File not found
localhost - - [02/Jun/2009 12:48:47] "GET /hello?foo=bar HTTP/1.1" 404 -
The server receives the request without the #appendage - anything after the hash tag is simply an anchor lookup on the client.
You can find the anchor name used within the URL via javascript using, as an example:
<script>alert(window.location.hash);</script>
The parse_url() function in PHP can work if you already have the needed URL string including the fragment (http://codepad.org/BDqjtXix):
<?
echo parse_url("http://foo?bar#fizzbuzz",PHP_URL_FRAGMENT);
?>
Output: fizzbuzz
But I don't think PHP receives the fragment information because it's client-only.
It is retrievable from Javascript - as window.location.hash. From there you could send it to the server with Ajax for example, or encode it and put it into URLs which can then be passed through to the server-side.
The hash is never sent to the server, so no.
The answer is no.
The main purpose of the hash is to scroll to a certain part of the page where you have defined a bookmark. e.g. Scroll to this Part when page loads.
The browse will scroll such that this line is the first visible content in the page, depending on how much content follows below the line.
Yes javascript can acces it, and then a simple ajax call will do the magic
What about:
Dynamically grab the #hash
<script>
var urlhash = window.location.hash, //get the hash from url
txthash = urlhash.replace("#", ""); //remove the #
//alert(txthash);
</script>
<?php
$hash = "<script>document.writeln(txthash);</script>";
echo $hash;
?>
To make it more fluent:
Full Example using just Javascript and PHP
<script>
var urlhash = window.location.hash, //get the hash from url
txthash = urlhash.replace("#", ""); //remove the #
function changehash(a,b){
window.location.hash = b; //add hash to url
//alert(b); //alert to test
location.reload(); //reload page to show the current hash
}
</script>
<?php $hash = "<script>document.writeln(txthash);</script>";?>
<a onclick="changehash(this,'#hash1')" style="text-decoration: underline;cursor: pointer;" >Change to #hash1</a><br/>
<a onclick="changehash(this,'#hash2')" style="text-decoration: underline;cursor: pointer;">Change to #hash2</a><br/>
<?php echo "This is the current hash: " . $hash; ?>
I think the hash-value is only used client-side, so you can't get it with php.
you could redirect it with javascript to php though.
Th part of an URI after the # is called "fragment" and is by definition only available/processed on client side (see https://en.wikipedia.org/wiki/Fragment_identifier).
On the client side, this can be accessed using javaScript with window.location.hash.
<?php
$url=parse_url("http://domain.com/site/gallery/1?user=12#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
?>
This is should work
Yes you can:
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
We can do it with another approach too, Like first of all get the hash value from js and call the ajax using that parameter and can do whatever we want
Another solution is to add a hidden input field to the php page:
<input type="hidden" id="myHiddenLocationHash" name="myHiddenLocationHash" value="">
Using javascript/jQuery you can set the value of this field on the page load or responding to an event :
$('#myHiddenLocationHash').val(document.location.hash.replace('#',''));
In php on the server side you can read this value using the $_POST collection:
$server_location_hash = $_POST['myHiddenLocationHash'];

setting and getting session variables

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>

passing variables from javascript to php

i am passing variable from javascript php with the following code by using cookie.
<script type="text/javascript">
function gTest() {
var country = 'hello testing';
document.cookie = 'name=document.write(country);' ;
document.write(country);
}
gTest();
</script>
<?php
echo "<br>";
var_dump($_COOKIE['name']);
?>
it works fine if we change to
document.cookie = 'name=hello' ;
i want to pass variable value to php in same page...i don't want to send to another page.
thanks
$_COOKIE is populated with the data sent from the browser to the server.
The JS to change the cookie won't run until the response is sent back and the JavaScript is executed.
The values in $_COOKIE won't update until you make a new HTTP request.
You can use XHR.
JavaScript (using jQuery):
$.ajax('script.php', {
data: { 'name': 'hello' }
});
PHP:
var_dump($_GET['name']);
You cant.
Ok, I think I got to explain. On your page, there is the Javascript first, then the PHP code, but it doesnt execute in that order.
First the server execute the PHP code, send the page as HTML and the javascript is executed on the client side.
If you really dont want to reload the whole page, the only way to do it is to use an ajax request to a page where your PHP code is. Simply use JQuery and replace your PHP code with this :
$('#result').load('showCookie.php');
Content of showCookie.php will be your var_dump and the page will do exactly what you want, except that you have called an additional page with JQuery.

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.

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