Загрузка файла PHP Curl

Эй, пытаясь опубликовать файл с помощью 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 каждый объект $data (за # 1 )? С именем функции post_file ожидаемое поведение будет за # 1post_file один 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 ).