PHP & Hash / Fragment Portion of URL

半世苍凉 提交于 2020-01-19 03:28:13

问题


I am trying to find a way to save the hash portion of a url and as a PHP variable. This idea is a bit kooky, but bear with me...

I'd like to extract the "location" fragment from the following URL and save it as a PHP variable.

http://www.example.com/#location

However, discussion at this link indicates that the fragment of a URL is only reachable through JavaScript.

But would it be possible to create a link where the fragment is duplicated in the URL, parsed by PHP, and then removed by mod rewrite? So....

Original url:

http://www.example.com/location/#location

PHP gets location variable thanks to the plain "location" in the URL

Apache then rewrites the link to:

http://www.example.com/#location

I'm curious to know if there is an elegant way to solve this problem.


回答1:


You'll need to use Javascript to read this. There are a few different options - upon page load, you could use an XmlHTTPRequest (AJAX request) to tell the server what the additional URL parameters were. Alternatley you could check to see if there are additional parameters (also via Javascript), and if you find any, post back to a different URL that has these parameters encoded into the URL itself.




回答2:


The Fragment is never sent to the server, according to this thread on the Mod_Rewrite forums. So, this might be impossible unless you use AJAX to change the page after the fact.

Another idea would be to have Javascript turn the hash into a $_GET paramater, and then refresh the page.




回答3:


you could send hash fragment via AJAX to PHP script and do an immediate refresh (reload of the page)




回答4:


Once you have send the values to server via AJAX. You can set the fragment values in SESSION. When you refresh the page, you can get the fragment which was set in session and process then display the corresponding content. Because we can't get get the fragment values through PHP_SELF / QUERY_STRING and etc. We need this to increase the speed of our web page like Gmail.




回答5:


It's contained in the "fragment" value returned from PHP's parse_url function.

From PHP manual:

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>

Will return:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path


来源:https://stackoverflow.com/questions/1162008/php-hash-fragment-portion-of-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!