phpproxy

Creating HTTP Proxy and Detecting mimeType using finfo, it broke entire code (php)


I'm trying to create HTTP proxy in php and I got error on setting Content-Type header. This code broke my entire code:

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->buffer(fread($sc, 512));
header("Content-Type: {$mimeType}");

so I start debugging, I changed code like that:

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->buffer(fread($sc, 512));
echo $mimeType;

It said image/jpg and the link I'm trying to access via the proxy is also jpg. So It is detecting properly, but then I re-changed to header("Content-Type: {$mimeType}") from echoing it, somehow it stop working. Please check this screenshot, Content-Type is image/jpg but the image returned to me is nothing (actually it appears when image is broken).

Full Code:

$context = stream_context_create([
    "http" => [
        "method" => "GET",
        "header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36\r\n"
    ]
]);

$content = fopen($url, 'rb', false, $context);

if ($content) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);

    // removing 2 lines below will make it work again
    $mimeType = $finfo->buffer(fread($content, 512));
    header("Content-Type: {$mimeType}");


    fpassthru($content);
    fclose($content);
} else {
    http_response_code(500);
    echo "Failed to retrieve the requested resource.";
}

The reason I did not use get_headers($url, 1) to get Content-Type instead, there are website do not returning that properly.


Solution

  • You are reading up to 512 bytes with fread but never send those bytes to the client. You are trimming the beginning of the response.

    Echo the bytes before calling fpassthru:

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    
    $head = fread($content, 512);
    // TODO: check that there are sufficient bytes to determine the mime type.
    // fread is not guaranteed to return 512 bytes and must be called
    // repeatedly as required.
    
    $mimeType = $finfo->buffer($head);
    header("Content-Type: {$mimeType}");
    
    echo $head;
    fpassthru($content);