Reputation: 103
I am trying to search wikipedia and get the results in php. It works when I enter the url as a hard coded string in the php file but if I try to get the url as an argument it returns this:
["",[],[],[]]
Here is the code with the hard coded string:
<?php
$opts = array('http' =>
array(
'user_agent' => 'User1 (http://www.exampe.com/)'
)
);
$context = stream_context_create($opts);
$url = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=yolo';
echo file_get_contents($url, FALSE, $context);
?>
Here is the version that takes an argument from its url:
<?php
$opts = array('http' =>
array(
'user_agent' => 'User1 (http://www.exampe.com/)'
)
);
$context = stream_context_create($opts);
$url = $_GET['url'];
echo file_get_contents($url, FALSE, $context);
?>
This is how I input arguments:
http://example.com/test.php?url=http://en.wikipedia.org/w/api.php?action=opensearch&search=yolo
Upvotes: 0
Views: 96
Reputation: 96
Your problem occurs because your get-parameter contains characters with a special meaning, such as %, ?, /, : and =.
The solution to this:
There are more characters that require replacement, but that do not occur in your URL.
your URL then becomes
http://example.com/test.php?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Fapi.php%3Faction%3Dopensearch%26search%3Dyolo
You can easily do this with the php function urlencode
Upvotes: 1
Reputation: 1231
You have to encode your query string before submit it
http://example.com/test.php?url=http://en.wikipedia.org/w/api.php?action=opensearch&search=yolo
to
http://example.com/test.php?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Fapi.php%3Faction%3Dopensearch%26search%3Dyolo
Upvotes: 0