Recent Posts

Showing posts with label file_get_contents. Show all posts
Showing posts with label file_get_contents. Show all posts

failed to open stream: HTTP request failed HTTP/1.1 400 Bad Request file_get_contents

When make request with file_get_contents sometimes we have to pass some arguments, one possible scenario is pass a string with two words including spaces. If you put the string without the proper format gives the error failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request file_get_contents.

So the solution is to apply the urlencode function for the string:

$str = urlencode("download moblileji now");
$url = "http://myurl/myfile.php?message=$str";
$string = file_get_contents($url, false); 

Post data using file_get_contents in PHP

Sending an HTTP POST request using file_get_contents is not that hard, actually : as you guessed, you have to use the $context parameter.

There's an example given in the PHP manual, at this page : HTTP context options (quoting) :

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);
Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents -- nothing more

As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...