【问题标题】:PHP fopen: failed to open stream: Success + how to save fetched content to a file?PHP fopen:打开流失败:成功+如何将获取的内容保存到文件中?
【发布时间】:2026-01-26 15:55:01
【问题描述】:

我编写了一个“proxy.php”脚本(如下所列),它将获取 ?img= 参数中指定的图像并将其打印到 STDOUT。这是我的 Flash 应用程序在某些站点上规避缺少的 crossdomain.xml 所必需的。

它有效,但我有 3 个问题。此外,我是从 Perl 开始使用 PHP 的,但我的 PHP 知识仍有很多空白(但我意识到,stream_context_create 和 fpassthru 可能使用桶旅)。

1) 在我的 callback() 函数中,如何将调试消息打印到 PHP 日志? (它在我的 CentOS 机器上被重定向到 /var/log/messages)

2) 为什么我会收到错误消息failed to open stream: Success,我可能错过了 callback() 中的一个案例吗?

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&amp;photoType=0) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: Success in /var/www/html/proxy.php on line 19

3) 因为我的脚本经常使用与参数相同的图像 URL 来调用,所以我想对其进行扩展,以便在第一次调用时将获取的文件保存在一个目录中。在第一次和随后的调用中,它应该将该缓存文件提供给 STDOUT。你有什么建议,如何以节省记忆的方式制作它? IE。我不想用 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);
                }
        }
}

?>

【问题讨论】:

    标签: php stream buckets


    【解决方案1】:
    1. 因为:

      sviss@sviss:~$ host i136.odnoklassniki.ru
      Host i136.odnoklassniki.ru not found: 3(NXDOMAIN)
      

    【讨论】:

      最近更新 更多