Reputation: 13738
Here is my code;
<?php $url = @$_POST["ekleme"];
if (filter_var($url,FILTER_VALIDATE_URL) === FALSE) {
die("Geçersiz link!");
}
$cparams = array('http'=>array('method'=>"GET",'Accept'=>'image/jpg,image/gif,image/png'));
$context = stream_context_create($cparams);
$fp = @fopen($url, 'rb', false, $context);
if (!$fp) die("Problem with url");
$meta = stream_get_meta_data($fp);
var_dump($meta);
I am giving it an url for an pdf file. I expect it to give some kind of http error. But this is what I got;
array(10) {
["wrapper_data"]=>
array(9) {
[0]=>
string(15) "HTTP/1.1 200 OK"
[1]=>
string(35) "Date: Wed, 02 Jan 2013 14:16:02 GMT"
[2]=>
string(14) "Server: Apache"
[3]=>
string(44) "Last-Modified: Wed, 19 Dec 2012 13:53:09 GMT"
[4]=>
string(34) "ETag: "1c80e53-f5a7-4d134ef3b7b40""
[5]=>
string(20) "Accept-Ranges: bytes"
[6]=>
string(21) "Content-Length: 62887"
[7]=>
string(29) "Content-Type: application/pdf"
[8]=>
string(17) "Connection: close"
}
It continues to show other unrelated things. Did I get how Accept header works wrong, or am I doing something wrong? Is there a way to ask a server only send data if content type is something spesific?
Upvotes: 3
Views: 2604
Reputation: 943561
The Accept header lets a client tell the server what types of data it can handle.
The server may ignore it completely (this is normal if a resource only exists in one format) or it may use it to pick the format best suited to the client (it might respond with a 406 Not Acceptable error if it doesn't have the data in a suitable format).
You are experiencing the former behaviour. The URL points to a PDF file. The server isn't set up to decide between PDF and other formats, so it doesn't pay attention to the Accept header and it returns the PDF.
Is there a way to ask a server only send data if content type is something spesific?
The accept header is as close as you can get.
If you want to avoid downloading large files that you might not be able to process, make a HEAD request and check the Content-Type of the response before you make a GET request.
Upvotes: 3
Reputation: 28094
When receiving a file, you are responsible for checking the content type. The accept header is just for telling the server which content type you prefer, not which one you demand.
Here is an example on how to check the returned content type.
$meta = stream_get_meta_data($fp);
$allowed = array("image/jpg", "image/gif", "image/png");
foreach($meta['wrapper_data'] as $header) {
if(preg_match('/content-type: (.*)/i', $header, $matches)) {
if(!in_array(strtolower($matches[1], $allowed)) {
die("Invalid content type");
}
}
}
Upvotes: 1