Curl PHP 文件上传

5

Hey, trying to post a file using curl and all is working great. I have one problem. I can't declare my file outside of my post_file() function. I call this function in my application many times so want it to be reusable.

So this works:

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;
}

However this does not:

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;
}

Any ideas? Cheers.

1个回答

5

我并没有看到这两个代码集之间在可重用性方面有什么区别。 #2 的唯一好处是你传递了整个 $data 对象 - 如果这真的是一个好处的话... 它会导致 CURL post 的安全问题... 所以这真的比每次创建一个新的 $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)。

嘿,安全不是问题,因为我们正在与外部API通信。我们需要进行多个POST请求,有时带有文件,有时只带有字符串值。我相当确定它与“@”中的“@.$file_path”有关。我稍微改了一下措辞,但字面上我只是复制并粘贴该行并更改传递的变量。此外,只会发布1个文件。 - bradley
1
K - 那么我明白为什么你想允许调用函数来确定(str)值或文件(@str)。但我仍然要说,这很可能是一个打字错误。#1 确定表单输入名称(Filedata),而 #2 允许任何名称 - 如果接收代码假定文件将以某个名称传递,则 #2 可能会轻易地发送文件,但随后被忽略。print_r($data);显示了什么? - Rudu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接