PHP - Content-type not specified assuming application/x-www-form-urlencoded

hannsch picture hannsch · Nov 22, 2013 · Viewed 32.4k times · Source

For 2 days I'm having trouble with my PHP script on my server. I've changed nothing and suddenly it didn't work anymore.

Here is the code:

$query = http_build_query($data);
$options = array(
    'http' => array(
        'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                    "Content-Length: ".strlen($query)."\r\n",     
        'method'  => "POST",
        'content' => $query,
    ),
);
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n",'method'  => 'POST',
        'content' => http_build_query($data),));
$contexts = stream_context_create($opts);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $contexts, -1, 40000);

I'm getting these error messages:

Notice: file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded in

Warning: file_get_contents(https://mobile.dsbcontrol.de): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error in

But when I try the script locally it works perfectly.

Answer

AbraCadaver picture AbraCadaver · Nov 22, 2013

You are passing $contexts to file_get_contents() and that only contains the User-Agent header in the $opts array. All other headers and options are in the $options array which you add in to $context but aren't using. Try:

$query = http_build_query($data);
$options = array(
    'http' => array(
        'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                    "Content-Length: ".strlen($query)."\r\n".
                    "User-Agent:MyAgent/1.0\r\n",
        'method'  => "POST",
        'content' => $query,
    ),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context, -1, 40000);