任务
将二进制文件从远程媒体处理服务器下载到网络服务器。
这有效,但我无法捕获 curl stdout 输出
$result = shell_exec('curl -v http://domain.com/images/dir/dir/dir/file.jpg --user username:password -o/usr/www/htdocs/images/dir/dir/dir/file.jpg');
注意: 我没有使用 PHP curl 包装器方法来完成这项任务,部分原因是我从未使用 PHP curl 包装器进行 FTP 下载。
问题 有人可以解释如何捕获我正在执行的命令的输出或使用 PHP curl 包装器的简单示例吗?
这是我尝试过的,但我遇到的问题是如何将新文件放置在目标服务器上——错误的行是 CURLOPT_FILE 行。我不想创建一个 stub 文件,打开它然后写入它。
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $ftpserver.$file['directory'].$filename); #input
curl_setopt($curl, CURLOPT_FILE, $dest); #output
curl_setopt($curl, CURLOPT_USERPWD, "$user:$password");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
谢谢
最佳答案
根据 a comment在 PHP 手册中,您必须确保在正确写入文件之前关闭 curl 流和文件处理程序。我将在此处复制示例以供搜索:
<?php
$fh = fopen('/tmp/foo', 'w');
$ch = curl_init('http://example.com/foo');
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);
curl_close($ch);
# at this point your file is not complete and corrupted
fclose($fh);
# now you can use your file;
read_file('/tmp/foo');
?>
此外,我会讨论将 CURLOPT_RETURNTRANSFER 与 CURLOPT_FILE 一起使用的优点,因为 CURLOPT_RETURNTRANSFER 告诉 curl 将获取的结果作为 curl_exec() 的结果返回。如果您只是将其写入文件,则可能不需要它。
关于php - 将 curl stdout 捕获到 PHP 中的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1848204/