Handy PHP
Wordtracker
Forum
Welcome, Guest
Please Login or Register.    Lost Password?
[function.file-get-contents]: failed to open stream: HTTP request failed!
(1 viewing) 1 Guest
Go to bottom
TOPIC: [function.file-get-contents]: failed to open stream: HTTP request failed!
#325
vujsa
Moderator
Posts: 143
graph
User Offline Click here to see the profile of this user
[function.file-get-contents]: failed to open stream: HTTP request failed! 3 Years, 10 Months ago Karma: 5
I recently got this really annoying warning message from a script I was working on to read XML feeds.

Warning: file_get_contents(www.somerandomdomainnamehere.com/feed.ph....1&search=my search term&ref=http%3A%2F%2Fhandyphp.com&limit=35) [function.file-get-contents]: failed to open stream: HTTP request failed! in /home/username/public_html/script.php on line 209

I was really perplexed since my test script worked fine with my sample XML file. It wasn't until I tried to use a remote XML file that I started having trouble. The key to the story is that I was using user input to to perform the feed search. So the user types "my search term" and the script sends a request to feed server for a feed that matched the search term. Once the script had the feed, it parsed it into a user friendly format.

The problem came when the script built the url to use to get the right feed. If a user used more than one word in their search term, there would be a blank space between the two words right! Well, your browser automatically replaces all of your blanks with %20 for you but unless you tell your script to do the same, it won't and you'll get the same warning message!

In order to encode your query url so that it won't have spaces, you can either use something like str_replace to replace the spaces with %20 or an easier way is to use a function like urlencode().

For example, if your search term was like this:
CODE

...
$term = $_GET['search'];
...


Just insert one line and all potentially problematic characters will be encoded before you try and send the request to the remote server:
CODE

...
$term = $_GET['search'];
$term = urlencode($term);
...


This has really saved me a bunch of headaches and I hope everyone will find it as useful as I did.

vujsa<br><br>Post edited by: vujsa, at: 2008/04/07 03:35
 
Logged Logged
 
Do not post small or one line posts.
Do not post unsolicited links or any referal links.
Do not post copied content.
Do not use foul language.
Always be respectful to the other posters.
  The administrator has disabled public write access.
Go to top
Earn More with LinkConnector
Wordtracker