views:

34

answers:

1
A: 

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).

Rudu
Hey, security is not a problem as we are talking to an external API. We need to make multiple post request, sometimes with files, sometimes with just string values. I'm pretty sure it has something to do with the "@" in "@".$file_path; I have paraphrasing slightly but literally all I do is copy and past the line and change the variables passed. Additionally there will only ever be 1 file posted.
bradleyg
K - well then I see why you'd want to allow the calling function to dictate (str) value or file (@str). Still gonna say this is likely a typo. **#1** dictates the form-input-name (`Filedata`) while **#2** allows any name - if your receiving code assumes the file will be delivered with a certain name **#2** could easily be sending the file, but it's then ignored. What does the `print_r($data);` show?
Rudu