嘿,尝试使用 curl 发布文件,一切正常。我有一个问题。我无法在 post_file() 函数之外声明我的文件。我在我的应用程序中多次调用此函数,因此希望它可以重用。
所以这是可行的:
function call_me(){
$file_path = "/home/myfile.mov";
$url = "http://myurl.com";
$this->post_file($url, $file_path);
}
function post_file($url, $file_path){
$data['Filedata'] = "@".$file_path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
return $response;
}
但是这不会:
function call_me(){
$file_path = "/home/myfile.mov";
$url = "http://myurl.com";
$data['Filedata'] = "@".$file_path;
$this->post_file($url, $data);
}
function post_file($url, $data){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
return $response;
}
有什么想法吗?干杯。
最佳答案
我真的看不出这两个代码集之间有什么区别(在可重用性方面)。 #2 的唯一好处是您传递了整个 $data
对象 - 如果这是一个好处...它会导致您的 CURL 出现安全问题发布...那么这真的比每次都创建一个新的 $data
对象更好吗(根据 #1)?使用函数名称 post_file
,预期行为将符合 #1 - 将单个文件发布到 URL,而代码 #2 可能会被利用/用于其他种类的东西。也许 #1 的可用性增强是:
function post_files($url,$files) {
//Post 1-n files, each element of $files array assumed to be absolute
// path to a file. $files can be array (multiple) or string (one file).
// Data will be posted in a series of POST vars named $file0, $file1...
// $fileN
$data=array();
if (!is_array($files)) {
//Convert to array
$files[]=$files;
}
$n=sizeof($files);
for ($i=0;$i<$n;$i++) {
$data['file'+$i]="@".$files[$i];
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
return $response;
}
至于为什么它现在对您不起作用 - 我猜其中某处有错字。这段代码是完全复制的还是你在为我们解释?在 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
行之前尝试 print_r($data);
。
函数无法知道对象是在函数内创建的 (#1) 还是传入的 (#2)。
关于php - curl PHP 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3892617/