使用file_get_contents vs curl获取文件大小

bon*_*y11 1 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);
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

Vic*_*ory 6

您可以使用filesize获取磁盘上文件的文件大小.

file_get_contents实际上将文件存入内存所以$filesize = strlen(file_get_contents($from));已经获取文件,除了找到它之外,你只是不做任何事情.你可以代替你fwrite打电话file_put_contents;

请参阅:file_get_contentsfile_put_contents.

curl当您需要更多访问HTTP协议时使用.curl在PHP中使用StackOverflow有很多问题和例子.

所以我们可以先下载该文件,在本例中我将使用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);
Run Code Online (Sandbox Code Playgroud)

在你的代码有 move_upload($_FILES['from']['tmp_name'], $move);,但是$_FILES当你有一个只适用<input type="file">元素,这似乎你不.

PS您可能应该在文件名中列出允许的字符,例如, $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);
}
Run Code Online (Sandbox Code Playgroud)

附:

$newFile = "./uploads/" . $rand2;
file_put_contents($newfile, $file);
Run Code Online (Sandbox Code Playgroud)

整个文件被读取file_get_contents整个文件被写入file_put_contents