File_Get_Contents Throws 400 Bad Request Error PHP

file_get_contents throws 400 Bad Request error PHP

You might want to try using curl to retrieve the data instead of file_get_contents. curl has better support for error handling:

// make request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.twitter.com/1/statuses/user_timeline/User.json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);

// convert response
$output = json_decode($output);

// handle error; error output
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {

var_dump($output);
}

curl_close($ch);

This may give you a better idea why you're receiving the error. A common error is hitting the rate limit on your server.

PHP file_get_contents returns with a 400 Error

You need to set user agent for file_get_contents like this, and you can check it with this code. Refer to this for set user agent for file_get_contents.

<?php
$options = array('http' => array('user_agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) Gecko/20100101 Firefox/53.0'));
$context = stream_context_create($options);
$response = file_get_contents('https://owapi.net/api/v3/u/Xvs-1176/blob', false, $context);
print_r($response);

HTTP/1.1 400 Bad Request in file_get_contents

The URL you posted is not valid in a technical way. A browser will take care of that if you enter such a URL, but on a more technical level you have to deal with such details yourself.

In this case there is a blank inside the urls request parameter. Such a character is not valid in a URL. Therefore you have to escape it. Have a try with these variants:

  • http://www.example.com/Movies.aspx?movname=Raja+Natwarlal

  • http://www.example.com/Movies.aspx?movname=Raja%20Natwarlal

Note that you cannot simply use a function like urlencode() to process the whole URL. That would also escape things like slashes and the like. That function is meant to escape a string such that it can be used as a single token inside an URL.

How can I handle the warning of file_get_contents() function in PHP?

Step 1: check the return code: if($content === FALSE) { // handle error here... }

Step 2: suppress the warning by putting an error control operator (i.e. @) in front of the call to file_get_contents():
$content = @file_get_contents($site);



Related Topics



Leave a reply



Submit