简体   繁体   English

cURL CURLOPT_WRITEFUNCTION和tmpfile()

[英]cURL CURLOPT_WRITEFUNCTION and tmpfile()

This code works: 此代码有效:

// 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);

This code does not: 此代码不:

// 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);

I am assuming that I cannot pass a stream via the 'use' to a function this way as it fails to copy the data. 我假设我无法通过“使用”将流传递给函数,因为它无法复制数据。 I guess my question is, how can I write the content of $str to $fp_tmp using CURLOPT_WRITEFUNCTION? 我想我的问题是,如何使用CURLOPT_WRITEFUNCTION将$ str的内容写入$ fp_tmp?

I'm a dummy, I forgot to reset the pointer using fseek(). 我是一个虚拟人,我忘记了使用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);

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

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