I don't really see a difference (for re-usability) between the two code sets. The only benefit of #2, is you're passing in the whole $data
object - if that's a benefit at all... it leads to security issues with your CURL post... so is this really better than creating a new $data
object each time (per #1)? With the function name post_file
the expected behaviour would be per #1 - post a single file to the URL, while code #2 could be exploited/used for other kinds of things. Perhaps a usability enhancement of #1 would be:
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;
}
As to why it's not working for you right now - I'm guessing there's a typo in there somewhere. Is this code copied exactly or are you paraphrasing for us? Try a print_r($data);
just before the curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
line.
There's no way for a function to know if the object was created within the function (#1) or passed in (#2).