为什么file_get_contents需要这么长时间? [英] Why does file_get_contents take so long?

查看:127
本文介绍了为什么file_get_contents需要这么长时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我向服务器上的PHP脚本发出AJAX POST请求.该脚本反过来向外部服务器上的php脚本发出GET请求,以检查文本文件的内容.但是,返回结果要花费很长时间.为什么会这样?

I make an AJAX POST request to a PHP script on my server. That script in turn makes a GET request to a php script on an external server to check the contents of a text file. However, it takes a very long time to come back with a result. Why is the case?

AJAX将请求发布到服务器上的脚本

session_start();
$fileName = $_POST['textFile'];
$result = file_get_contents($_SESSION['serverURL']."fileReader.php?textFile=$fileName");
echo $result;

GET请求到另一台服务器上的脚本

$fileName = $_GET['textFile'];

if (file_exists('text/'.$fileName.'.txt')) {

    $lines = file('text/'.$fileName.'.txt');

    echo $lines[sizeof($lines)-1];

}
else{
    echo 0;
}

这些是非常简单的脚本,它只检查很小的文本文件,为什么要花这么长时间?

These are very simple scripts and its only checking a very small text file, so why does it take so long?

我正在网站上提出其他AJAX请求,但是这些肯定不会引起问题.话虽这么说,该文本文件的返回值总是与另一个AJAX请求的完成同时发生,该请求启动了一个需要花费一些时间才能在我的服务器上完成的脚本,但是它们之间会如何相互影响?他们不应该对吗?

I am making other AJAX request on my site but these surely can't be causing a problem. Having said this, the returned value of that text file always co-incides with the completion of another AJAX request which initiates a script that takes a while to complete on my server, but how would these effect each other?! They shouldn't right?

推荐答案

您不必通过HTTP路由即可获取文件的最后一行.为什么不留在文件系统中并使用类似的函数来检索最后一行:

You don’t have to take the route over HTTP to get the last line of a file. Why don’t you stay inside the file system and use a function like that to retrieve the last line:

function fileGetLine($filename, $line) {
    if (!is_file($filename) || !is_readable($filename)) {
        // invalid file name or not readable
        return false;
    }
    if (!is_int($line)) {
        // invalid line number
        return false;
    }
    $lines = file($filename);
    $lineCount = count($lines);
    if ($line < 0) {
        // negative line number, count from end
        $line = $lineCount + $line;
    }
    if ($line < 0 || $line >= $lineCount) {
        // line number out of bounds
        return false;
    }
    return $lines[$line];
}

session_start();
echo fileGetLine('text/'.basename($_POST['textFile']).'.txt', -1);

这篇关于为什么file_get_contents需要这么长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆