简体   繁体   English

PHP:用file_put_content保存wget返回的文件

[英]PHP: Save the file returned by wget with file_put_content

I'm replacing a function that downloads a file with cURL and returns its content in a variable, then outside the function the code writes this variable to a file with file_put_content.我正在用 cURL 替换下载文件的 function,并在变量中返回其内容,然后在 function 之外,代码将此变量写入带有 file_put_content 的文件。 Because of requirements of the system I have to use wget now, so I'm using something like this:由于系统的要求,我现在必须使用 wget,所以我正在使用这样的东西:

function GetData($strdata,$wwwurl){
    $content = exec("wget --post-data '".$strdata."' -qO- ".$wwwurl);
    return $content;
}

But when I later use file_put_content to save the content of $content, the size of the file is way smaller than it should be (1kb when it should be around 480kb).但是当我稍后使用 file_put_content 来保存 $content 的内容时,文件的大小比它应该的小得多(1kb,当它应该在 480kb 左右时)。 I can't remove file_put_content as it's used in several places of the code (that would take us a very long time) and all I can edit must be into that function. If I launch wget with "-O test.zip" instead of "-O-" the file is downloaded and saved fine, the same happens if I launch the command from command line.我无法删除 file_put_content,因为它在代码的多个位置使用(这会花费我们很长时间),而且我可以编辑的所有内容都必须进入 function。如果我使用“-O test.zip”而不是启动 wget “-O-”文件已下载并保存良好,如果我从命令行启动命令,也会发生同样的情况。 Any ideas?有任何想法吗?

Its because exec doesn't return the whole data.这是因为exec不返回整个数据。 Take a look at the documentation https://www.php.net/manual/en/function.exec.php :查看文档https://www.php.net/manual/en/function.exec.php

Return Values: The last line from the result of the command.返回值:命令结果的最后一行。

But shell_exec (or just backticks) returns whole data: https://www.php.net/manual/en/function.shell-exec.php .但是shell_exec (或只是反引号)返回整个数据: https://www.php.net/manual/en/function.shell-exec.php

Example:例子:

<?php

$url = 'https://file-examples-com.github.io/uploads/2017/02/zip_5MB.zip';

$content = exec("wget -qO- $url");

var_dump(strlen($content));

$content2 = shell_exec("wget -qO- $url");

var_dump(strlen($content2));


file_put_contents('1.zip', $content);
file_put_contents('2.zip', $content2);

Output: Output:

int(208)
int(5452018)

2.zip works (all 5MB data), 1.zip obviously not (just some bytes from the end). 2.zip 有效(所有 5MB 数据),1.zip 显然无效(只是末尾的一些字节)。

So don't treat exec 's return value as the whole output of the command.因此,不要将exec的返回值视为命令的整个 output。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM