[php] Get fragment (value after hash '#') from a URL in php

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

This question is related to php url anchor url-fragment

The answer is


I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...

By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23. This, in turn, breaks the redirection.

Solution: Use the [NE] flag on the RewriteRule. NE stands for No Escape.

Discussion: This technique will of course also work with other special characters that mod_rewrite, by default, URL-encodes.

It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.


You can do it by a combination of javascript and php:

<div id="cont"></div>

And by the other side;

<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';

setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>

Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)


You need to parse the url first, so it goes like this:

$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'

If you need to parse the actual url of the current browser, you need to request to call the server.

$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'

A) already have url with #hash in PHP? Easy! Just parse it out !

if( strpos( $url, "#" ) === false ) echo "NO HASH !";
   else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0

Or in "old" PHP you must pre-store the exploded to access the array:

$exploded_url = explode( "#", $url ); $exploded_url[1]; 

B) You want to get a #hash by sending a form to PHP?
    => Use some JavaScript MAGIC! (To pre-process the form)

var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
    forms[i].addEventListener( // add a "listener"
        'submit', // for an on-submit "event"
        function () { //add a submit pre-processing function:
            var input_name = "fragment"; // name form will use to send the fragment
            // Try search whether we already done this or not
            // in current form, find every <input ... name="fragment" ...>
            var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
            if (hiddens.length < 1) { // if not there yet
                //create an extra input element
                var hidden = document.createElement("input");
                //set it to hidden so it doesn't break view 
                hidden.setAttribute('type', 'hidden');
                //set a name to get by it in PHP
                hidden.setAttribute('name', input_name);
                this.appendChild(hidden); //append it to the current form
            } else {
                var hidden = hiddens[0]; // use an existing one if already there
            }

            //set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
            hidden.setAttribute('value', window.location.hash);
        }
    );
}

Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']

Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )

C) You want to get the #hash in PHP JUST from requested URL?

                                    YOU CAN'T !

...(not while considering regular HTTP requests)...

...Hope this helped :)


That part is called "fragment" and you can get it in this way:

$url=parse_url("http://domain.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment

You can't get the text after the hash mark. It is not sent to the server in a request.


I found this trick if you insist want the value with PHP. split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP


If you are wanting to dynamically grab the hash from URL, this should work: https://stackoverflow.com/a/57368072/2062851

<script>
var hash = window.location.hash, //get the hash from url
    cleanhash = hash.replace("#", ""); //remove the #
    //alert(cleanhash);
</script>

<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>

Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.

A. setup your strings with a div id, so the name anchor goes where its supposed to and the javascript can change the text colors

<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>

B. Use Javascript to do the heavy work, on the server side, inserted in your PHP page, or wherever..

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

C. I am launching the java function automatically when the page is loaded.

<script>
$( document ).ready(function() {

D. get the anchor (#tesla) from the url received by the server

var myhash1 = $(location).attr('hash'); //myhash1 == #tesla

E. trim the hash sign off of it

myhash1 = myhash1.substr(1)  //myhash1 == tesla

F. I need to highlight the term and the description so i create a new var

var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1

G. Now I can manipulate the text color for the term and description

var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>

H. This works. client clicks link on client side (xyz.com#tesla) and goes right to the term. the term and the description are highlighted in blue by javascript for quick reading .. all other entries left in black..


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?

Examples related to anchor

How to open a link in new tab using angular? Attaching click to anchor tag in angular How to create a link to another PHP page Making href (anchor tag) request POST instead of GET? Difference between _self, _top, and _parent in the anchor tag target attribute How can I create a link to a local file on a locally-run web page? How to open link in new tab on html? Getting a link to go to a specific section on another page Pure CSS scroll animation Make anchor link go some pixels above where it's linked to

Examples related to url-fragment

How do I get the fragment identifier (value after hash #) from a URL? Get fragment (value after hash '#') from a URL in php