avinash shah
avinash shah

Reputation: 1445

php file_get_contents giving error

When I run the following query on browser:

http://127.0.0.1:8096/solr/select/?q=june 17&start=0&rows=8&indent=on&hl=on&hl.fl=Data&wt=json

I get results. No problems. Notice that there is a space between june and 17

However when I receive that query in my PHP i.e. $q=June 17 I use

$url="http://127.0.0.1:8096/solr/select/?q=$q&start=0&rows=8&indent=on&hl=on&hl.fl=Data&wt=json";
$json_O=json_decode(file_get_contents($url),true);

After this I see the following on my firebug:

<b>Warning</b>:  file_get_contents(http://127.0.0.1:8096/solr/select/?q=june 17&amp;start=0&amp;rows=8&amp;indent=on&amp;hl=on&amp;hl.fl=Data&amp;wt=json) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.1 505 HTTP Version Not Supported

However note that if there is no space between my query words (I mean if it is a single word) then everything is perfect.

Why does it work fine when I issue exactly same query on browser as compared to file_get_contents(). Any solutions would be appreciated.

Upvotes: 1

Views: 1863

Answers (2)

iblue
iblue

Reputation: 30414

This is, because the file_get_contents function sends a request to a web server in HTTP, which looks like this

GET /solr/select/?q=bla HTTP/1.0
Host: 127.0.0.1
...[more headers here]...

Note, that there is a the in HTTP version specified in the request (HTTP/1.0)

Now, if there is a space in your request string, you send something like

GET /solr/select/?q=bla foo HTTP/1.0
Host: 127.0.0.1
...[more headers here]...

Your server seems to parse foo as the version and returns 505 HTTP Version Not Supported. If you encode the space in the string (e.g. by replacing it with %20, this should not happen).

Upvotes: 1

Nadh
Nadh

Reputation: 7243

There is a space in the q parameter's value. Could be that. Try urlencode()ing the parameter.

$url="http://127.0.0.1:8096/solr/select/?q=".urlencode($q)."&start=0&rows=8&indent=on&hl=on&hl.fl=Data&wt=json";

$json_O=json_decode(file_get_contents($url),true);

Upvotes: 3

Related Questions