此代码有效:
// Create temp file to write to
$fp_tmp = tmpfile();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $name);
curl_setopt($ch, CURLOPT_FILE, $fp_tmp);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_REFERER, 'https://dl.dropboxusercontent.com');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
// Write the files
$fp = fopen($orderfile->getFileLocation(), 'w');
stream_copy_to_stream($fp_tmp, $fp);
此代码不会:
// Create temp file to write to
$fp_tmp = tmpfile();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $name);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_REFERER, 'https://dl.dropboxusercontent.com');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $str) use (&$fp_tmp) {
$length = fwrite($fp_tmp, $str);
return $length;
});
$result = curl_exec($ch);
curl_close($ch);
// Write the files
$fp = fopen($orderfile->getFileLocation(), 'w');
stream_copy_to_stream($fp_tmp, $fp);
我假设我无法通过'use'将流传递给函数,因为它无法复制数据。我想我的问题是,如何使用CURLOPT_WRITEFUNCTION将$ str的内容写入$ fp_tmp?
答案 0 :(得分:3)
我是个假人,我忘了用fseek()重置指针。
// Create temp file to write to
$fp_tmp = tmpfile();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $name);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_REFERER, 'https://dl.dropboxusercontent.com');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $str) use (&$fp_tmp) {
$length = fwrite($fp_tmp, $str);
return $length;
});
$result = curl_exec($ch);
curl_close($ch);
// Write the files
$fp = fopen($orderfile->getFileLocation(), 'w');
fseek($fp_tmp, 0);
stream_copy_to_stream($fp_tmp, $fp);