0

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

2 Answers 2

1

Your problem occurs because your get-parameter contains characters with a special meaning, such as %, ?, /, : and =.

The solution to this:

  • replace & by %26
  • replace / by %2F
  • replace : by %3A
  • replace ? by %3F
  • replace = by %3D

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.