2

file_get_content (HTTP uri ではない) を使用してローカル ファイルにタイムアウトを設定する方法を知りたいのですが、NFS マウント パーティションが非常に遅く、タイムアウト (たとえば 5 秒) 後にあきらめることを好みます。

file_get_contents("/mnt/photo/photo.jpg");

他の同様の質問への回答を読みましたが、ソリューションは HTTP でのみ機能し、ローカル ファイルでは機能しないと思います。

$ctx = stream_context_create(array('http'=>array('timeout' => 1200)));

また、このソリューションは私向けではなく、Web 向けでもあると思いますよね?

ini_set('default_socket_timeout', 900);
4

2 に答える 2

1

ストリームをノンブロッキング モードに設定しstream_set_blocking、タイムアウトになるまでファイルの読み取りを試みることができます。何かのようなもの:

function readReallyBigFile($path, $timeoutSeconds = 5) {
    if (false === $stream = fopen($path, "r")) {
        throw new \RuntimeException('Cannot open file');
    }

    stream_set_blocking($stream, 0);

    $timeout = time();

    $contents = '';
    while (!feof($stream)) {
        $contents .= fread($stream, 8192);
        if ((time() > $timeout + $timeoutSeconds)) {
            throw new \RuntimeException('Timeout reached out');
        }
    }

    fclose($stream);

    return $contents;
}

$img = readReallyBigFile('/mnt/photo/photo.jpg');
于 2016-11-10T13:06:43.007 に答える