php - 使用 file_get_contents vs curl 获取文件大小

标签 php performance curl file-upload

我的服务器上运行了一个文件上传脚本,该脚本还具有远程上传功能。一切正常,但我想知道通过 URL 上传的最佳方式是什么。现在我正在使用 fopen从粘贴在名为“from”的文本框中的远程 url 获取文件。我听说 fopen 不是最好的方法。这是为什么?

另外我正在使用 file_get_contents 从 URL 获取文件的文件大小。我听说curl在这方面更好。为什么会这样,以及如何将这些更改应用于此脚本?

<?php
$from = htmlspecialchars(trim($_POST['from']));

if ($from != "") {
    $file = file_get_contents($from);
    $filesize = strlen($file);

    while (!feof($file)) {
        $move = "./uploads/" . $rand2;
        move_upload($_FILES['from']['tmp_name'], $move);

        $newfile = fopen("./uploads/" . $rand2, "wb");
        file_put_contents($newfile, $file);
    }
}
?>

最佳答案

您可以使用 filesize 获取磁盘上文件的文件大小。
file_get_contents实际上将文件放入内存中,所以 $filesize = strlen(file_get_contents($from));已经获取了文件,除了查找它的大小之外,您什么也不做。你可以代替你fwrite调用file_put_contents ;

见:file_get_contentsfile_put_contents .
curl当您需要更多访问 HTTP 时使用协议(protocol)。 StackOverflow上有很多问题和例子使用curl在 PHP 中。

所以我们可以先下载文件,在这个例子中我将使用file_get_contents ,获取其大小,然后将文件放在本地磁盘上的目录中。

$tmpFile = file_get_contents($from);
$fileSize = strlen($tmpFile);
// you could do a check for file size here
$newFileName = "./uploads/$rand2";
file_put_contents($newFileName, $tmpFile);

在您的代码中,您有 move_upload($_FILES['from']['tmp_name'], $move);但是 $_FILES仅当您拥有 <input type="file"> 时才适用元素,你似乎没有。

附言您可能应该将文件名中允许的字符列入白名单,例如 $goodFilename = preg_replace("/^[^a-zA-Z0-9]+$/", "-", $filename)这通常更容易阅读和更安全。

代替:
while (!feof($file)) {
    $move = "./uploads/" . $rand2;
    move_upload($_FILES['from']['tmp_name'], $move);

    $newfile = fopen("./uploads/" . $rand2, "wb");
    file_put_contents($newfile, $file);
}

和:
$newFile = "./uploads/" . $rand2;
file_put_contents($newfile, $file);
file_get_contents 读入整个文件整个文件由 file_put_contents 编写

关于php - 使用 file_get_contents vs curl 获取文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23308320/

相关文章:

php - 如何通过 unix socket 设置 Apache2 和 PHP-FPM?

javascript - 在 Javascript 中运行代码以使 PHP 和 HTML 文件从 ONLOAD 事件运行

mysql - 如何使用MySql获得高速性能?

php - 在 PHP 中使用 fopen($url) 和 curl 有什么重要区别?

php - SQL 语句危险的标志

php - 基于 SQL Server/PHP/Web 的管理工具 - 有哪些用于 SQL Server 的类似于 phpmyadmin 的工具?

c# - 在添加字典之前检查字典中是否存在键的最佳方法?

Java字节码 "excessive"的dup数算不算 "poor"码?

ssl - NGINX 说 "client sent no required SSL certificate while reading client request headers"我们如何排除故障?

php - 使用 CURL 获取 JSON 数据