tags:

views:

59

answers:

4

I am trying to use file_get_contents() to get the html from a page.
the following works great: file_get_contents('http://www.mypage.com?Title=Title') but the following causes an error:

$Title = 'Title';
file_get_contents("http://www.mypage.com?Title=$Title")

The error is:

Bad Request

Your browser sent a request that this server could not understand.
The request line contained invalid characters following the protocol string.

Apache/1.3.41 Server at eiit.org Port 80

Does anyone know why?

+1  A: 

Variables inside single quotes dont get interpolated; try:

$Title = 'Title';
file_get_contents("http://www.mypage.com?Title=$Title")
Erik
oops I did use double quotes, that was a typo when I put it in here
Brian
Why don't you copy who knows if you made any other typos :)
Erik
I prefer not to post actual code. I like to anonymize it before I post it.
Brian
Pascals post is why you should copy don't let anyone see if you've made basic errors.
Erik
+2  A: 

You are using a string with single-quotes ; and there is no variable interpolation with single-quotes.

Which means the URL you're trying to fetch is http://www.mypage.com?Title=$Title, and not http://www.mypage.com?Title=Title.

You should use a double-quoted string, to have variable interpolation :

$Title = 'Title';
file_get_contents("http://www.mypage.com?Title=$Title");


If this still doesn't work :

  • Check if your URL is OK : instead of directly passing it to file_get_contents, store it in a variable, and echo it -- just to be sure it's right.
  • Why is there no page-name in your URL ?
    • You have the domain-name : www.mypage.com
    • And a parameter+value : Title=Title
    • But no file/page ? i.e., why don't you have something like http://www.mypage.com/index.php?Title=$Title ? Or even http://www.mypage.com/?Title=$Title ?
  • You might have to urlencode the values you're passing as parameters in the URL.
Pascal MARTIN
that's it, I didn't urlencode the GET data
Brian
A: 

Have you tried http://www.mypage.com/?Title=$Title? The slash after the domain name is the path - you must always have a path in an HTTP request.

Max Shawabkeh
not always true: put http://www.smarty.net?hello in your browser ... the slash gets rewritten in (by the webserver) but your request gets the site
Erik
@Erik : is it the webserver that adds the slash, or your browser ? Checking the HTTP request, it seems the browser sends a GET request that starts with a /, even if I didn't put it in the original URL -- which indicates the / is added by the browser, and not the server
Pascal MARTIN
Pascal is right. `GET HTTP/1.1` is not a valid HTTP request. The browser converts it to `GET / HTTP/1.1`.
Max Shawabkeh
I just assumed it was the webserver =x My error :)
Erik
A: 

if i don't if you have resolved your problem, but another way you can try. (although i don't think it matters)

$Title = 'Title';
$result=file_get_contents("http://www.mypage.com?Title=".$Title)
ghostdog74