PHP fopen: failed to open stream: Success + how to save fetched content to a file?
I have programmed a "proxy.php" script (listed below), which would fetch an image specified in the ?img= parameter and print it to the STDOUT. This is needed for my Flash app to circumvent a missing crossdomain.xml at some sites.
It works, but I have 3 questions please. Also I'm coming to PHP from Perl and still have many gaps in my PHP-knowledge (but I realize, that stream_context_create and fpassthru probably use bucket brigades).
1) In my callback() function, how can I print开发者_如何学JAVA debugging messages to PHP log? (it is redirected to /var/log/messages at my CentOS machine)
2) Why do I get the error message failed to open stream: Success, do I miss a case in the callback() maybe?
PHP Warning: fopen() [<a href='function.fopen'>function.fopen</a>]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/html/proxy.php on line 19
PHP Warning: fopen(http://i136.odnoklassniki.ru/getImage?photoId=154105499212&photoType=0) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: Success in /var/www/html/proxy.php on line 19
3) Because my script is often called with the same image URL as parameter, I would like to extend it so that it saves the fetched file in a dir on the 1st call. And on the 1st and subsequent calls it should serve that cached file to STDOUT. Do you have a suggestion, how to make it in a memory-conserving way? I.e. I don't want to read the whole file at once with get_file_contents()
<?php
define('MAX_SIZE', 1024 * 1024);
$img = urldecode($_GET['img']);
if (strpos($img, '..') !== FALSE)
exit('Wrong URL: ' . $img);
$opts = array(
'http'=>array(
'method' => 'GET'
)
);
$ctx = stream_context_create($opts);
stream_context_set_params($ctx, array('notification' => 'callback'));
$fh = fopen($img, 'r', FALSE, $ctx);
if ($fh) {
fpassthru($fh);
fclose($fh);
}
function callback($code, $severity, $message, $message_code, $bytes_transferred, $bytes_total) {
if ($code == STREAM_NOTIFY_PROGRESS && $bytes_transferred > MAX_SIZE)
exit('File is too big: ' . $bytes_transferred);
if ($code == STREAM_NOTIFY_FILE_SIZE_IS)
if ($bytes_total > MAX_SIZE)
exit('File is too big: ' . $bytes_total);
else
header('Content-Length: ' . $bytes_total);
if ($code == STREAM_NOTIFY_MIME_TYPE_IS) {
if (stripos($message, 'image/gif') !== FALSE ||
stripos($message, 'image/png') !== FALSE ||
stripos($message, 'image/jpg') !== FALSE ||
stripos($message, 'image/jpeg') !== FALSE) {
header('Content-Type: ' . $message);
} else {
exit('File is not image: ' . $mime);
}
}
}
?>
Because:
sviss@sviss:~$ host i136.odnoklassniki.ru Host i136.odnoklassniki.ru not found: 3(NXDOMAIN)
精彩评论