file_get_contents() expects parameter 3 to be resource

By On

I am trying to make a get request using file_get_contents and I want to get back the HTTP headers from the response along with the content body. Whenever I try to provide the headers to the function, I get the error "file_get_contents() expects parameter 3 to be resource". I am not sure what I am doing wrong here. This is the code that I am using. Does anyone know what the cause of this is?

$httpOptions = array('http' => array(
 'method'  => 'GET',
 'ignore_errors' => true
));
$dom = str_get_html(file_get_contents($url, false, $context));

1 Answer

- Advertisment -
SEMrush
Answered By Isaac Ortega On

The file_get_contents function does not allow the third argument to be the array of headers. You need to convert the headers into a stream context first and pass this context as an argument to the function. I have modified your original code with the correct stream conversion. The following should allow you to get the headers from the response. The headers can be found in a variable called $http_response_header

$httpOptions = array('http' => array(
 'method'  => 'GET',
 'ignore_errors' => true
));
$context  = stream_context_create($httpOptions);
$dom = str_get_html(file_get_contents($url, false, $context));