卷曲PHP文件上传

bra*_*ley 5 php curl file-upload

嘿,尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)

但是,这不是:

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;
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?干杯.

Rud*_*udu 5

我并没有真正看到两个代码集之间的差异(对于可重用性).#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;
}
Run Code Online (Sandbox Code Playgroud)

至于为什么它现在不适合你 - 我猜这里有一个错字.这段代码是完全复制的,还是你为我们解释的?尝试print_r($data);curl_setopt($ch, CURLOPT_POSTFIELDS, $data);一行.

函数无法知道对象是在函数(#1)中创建还是传入(#2).