0

i have a problem. I have made a PHP proxy to get json data from an external server using this code :

<?php 
$url = $_GET['url'];

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
$data = curl_exec($ch);
curl_close($ch);

echo("<h1>".$url."</h1>");

echo (substr($data,0,-1));

?>

But i have to pass this link "http://isohunt.com/js/json.php?ihq=ubuntu&sort=age" and since i have an & in there my php script can't properly evaluate the link. How i solve the issue?

hakre
  • 193,403
  • 52
  • 435
  • 836
DxW
  • 1,414
  • 3
  • 11
  • 23
  • possible duplicate of [How to encode a URL in Javascript?](http://stackoverflow.com/questions/332872/how-to-encode-a-url-in-javascript) – hakre Feb 24 '12 at 20:43

4 Answers4

3

Before passing the target URL to the script via the url GET parameter, encode it with urlencode() (or an equivalent depending on where the target URL enters the situation).

The encoding will be automatically reversed when you retrieve $_GET['url'], leaving you with the original (desired) URL. (Kudos to Quentin for correcting me here).

Hope this helps.

jstephenson
  • 2,170
  • 14
  • 14
  • 1
    `$_GET` will decode URLs automatically (that's have the point of it). The problem is that they aren't being encoded in the first place! – Quentin Feb 24 '12 at 20:29
  • @Quentin Thanks - beer and Stackoverflow don't mix. That's something like 10 edits under belt now :$ ... – jstephenson Feb 24 '12 at 20:35
1

use urlencode to generate the link, e.g.

echo '<a href="http://example.com/my-script.php?url="';
echo url_encode( $url );
echo '">click here</a>';

which should output

<a href="http://example.com/my-script.php?url=http%3A%2F%2Fisohunt.com%2Fjs%2Fjson.php%3Fihq%3Dubuntu%26sort%3Dage">click here</a>
scibuff
  • 13,377
  • 2
  • 27
  • 30
1

Presumably when you have characters in your data that have special meaning in URIs (such as &) you are failing to encode them (as %26 for that particular character).

Since you are tagging this jquery-ajax: stop constructing your URIs manually. Let jQuery do it:

$.ajax({
  url: "myProxy.php",
  data: { 
    url: "http://isohunt.com/js/json.php?ihq=ubuntu&sort=age" 
  },
  success: function(){
    // yada yada
  }
});
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Try to URL encode before passing url to the url argument. Use the below mentioned link if you want to be quick.

http://meyerweb.com/eric/tools/dencoder/