Download PHP Curl File

Hey, trying to publish the file using curl and everything works fine. I have one problem. I cannot declare my file outside of my post_file () function. I call this function in my application many times, so I want it to be reused.

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, it is 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? Greetings.

+5
source share
1 answer

( ) . # 2 , $data - ... CURL... , $data ( # 1)? post_file # 1 - URL- 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;
}

, - - . ? print_r($data); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);.

, (# 1) ( # 2).

+5

All Articles