-1

How i get the code from this url in a variable?

http://www.site.com/#code=123

I tried this:

if (isset($_GET['code'])){
   $code = $_GET['code']; 
}

But the api returns a # instead of & or ?

I found a way with javascript thanks everybody

<script>
var hash = false;
checkHash();

function checkHash(){
    if(window.location.hash != hash) {
        hash = window.location.hash;
        processHash(hash);
    } t=setTimeout("checkHash()",400);
}

function processHash(hash){

    window.location.href = "code.php?code=" + hash.substr(7);

}

3 Answers3

1

Can you try this in PHP,

 $url=parse_url("http://www.site.com/#code=123");
 echo $fragment =  $url["fragment"];//code=123
 if($fragment!=""){
    list($codeName, $codeValue) = @explode("=", $fragment);
    echo $codeValue; //123
 }

Ref: http://in3.php.net/parse_url

Krish R
  • 22,583
  • 7
  • 50
  • 59
1

The hashtag fragment is not part of the HTTP protocol and is only for clients as an orientation inside a single page. You cannot parse this with PHP because it does not get send through the network as a request.

http://www.w3.org/TR/WD-html40-970708/htmlweb.html

Fragment URLs

The URL specification en vigeur at the writing of this document ([RFC1738]) offers a mechanism to refer to a resource, but not to a location within a resource. The Web community has adopted a convention called "fragment URLs" to refer to anchors within an HTML document. A fragment URL ends with "#" followed by an anchor identifier. For instance, here is a fragment URL pointing to an anchor named section_2:

You said an API returns you this URL. Consider the URL saved in your variable $url, you can use Krish R's answer by starting with $url = parse_url($url);.

If you want to LOAD the contents from the URL, the rabbit goes like file_get_contents('http://www.site.com/'); - as said, because hashtag is not part of HTTP.

Daniel W.
  • 31,164
  • 13
  • 93
  • 151
0

I think your PHP is ok, but the url seems strange. Before the first 'key=value' in the url there should be a ? symbol.

mcsilvio
  • 1,098
  • 1
  • 11
  • 20
  • Hmm. In that case, all I can recommend is to verify the output by dropping the API URLs in your browser manually. Then you can see what your program will see. This won't work for APIs that accept POST requests (and PUT, DELETE), but for GET requests (which yours is) its a useful method. – mcsilvio Jan 09 '14 at 16:26