I'm making a PHP image proxy script. I need it to not only echo the contents of the image it requests, but also identically reproduce the header of the image request.
I've seen one, and the other, but not both together... and these cURL option things confuse me. How would I do this?
Sorry, I'm not sure what is you want.
This is the example to get from a image url, echo header and save image to a file.
But, if you want a proxy, you should use web server (Nginx, Apache, etc), PHP is no need
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://img3.cache.netease.com/www/logo/logo_png.png");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_REFERER, "http://www.163.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
list($header, $image) = explode("\r\n\r\n", $return, 2);
echo $header;
file_put_contents("/tmp/logo.png", $image);
You can get all the headers (not as raw text) with getallheaders()
- http://www.php.net/manual/en/function.getallheaders.php
Then string them back together:
$headers = "";
foreach (getallheaders() as $name => $value) {
$headers = "$name: $value\r\n";
}
$headers .= "\r\n"; // Double newline to signal end of headers (HTTP spec)
Then I think the best way is to use a socket connection, rather than CURL like so:
$response = '';
$fp = fsockopen('example.org', 80);
fputs($fp, $headers);
while (!feof($fp)) {
$response .= fgets($fp, 128);
}
fclose($fp);
Note that you may need to modify the host/request headers (because this is an identical copy, as you asked), and you may need to implement redirect following.