我的服务器上运行了一个文件上传脚本,该脚本还具有远程上传功能。一切正常,但我想知道通过 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_contents和 file_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/