简体   繁体   中英

Getting data from url using PHP

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM