Asked  7 Months ago    Answers:  5   Viewed   104 times

How can i select the fragment after the '#' symbol in my URL using PHP?
The result that i want is "photo45".

This is an example URL:
http://example.com/site/gallery/1#photo45

 Answers

25

If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.

If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.

Tuesday, June 1, 2021
 
jab
answered 7 Months ago
jab
37

You won't be able to do it in PHP - you can only access it in javascript - the fragment/hash never reaches the server, it is processed by the browser

in Javascript, you can access the fragment using

window.location.hash
Wednesday, March 31, 2021
 
Palladium
answered 9 Months ago
73

Try this:

$str = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip';
$pos = strrpos($str, '/') + 1;
$result = substr($str, 0, $pos) . urlencode(substr($str, $pos));

You're looking for the last occurrence of the slash sign. The part before it is ok so just copy that. And urlencode the rest.

Wednesday, March 31, 2021
 
TheTechnicalPaladin
answered 9 Months ago
25

Apache's mod_rewrite automatically decodes urlencoded strings when it does regex matching. But it only does this once, so you should be if you urlencode your string twice. This will re-escape all of those `%' characters.

try

$link = 'http://www.mydomain.com/'.urlencode(urlencode($str)).'/1';

or stop relying on rewrite rules and use a framework that handles URL routing properly.

Oh, and there should also be htmlentities() somewhere in there.

Saturday, May 29, 2021
 
Gordnfreeman
answered 7 Months ago
52

No need for jQuery

var type = window.location.hash.substr(1);
Saturday, June 5, 2021
 
avon_verma
answered 7 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share