使用cURL通过PHP进行带有$ _FILES的HTTP POST的问题

时间:2013-11-14 22:14:52

标签: php curl

基本上,我要做的是获取HTTP Post,并将文件保存在第一台服务器上,然后将帖子转发到第二台服务器,该服务器再次保存文件,然后生成一封电子邮件,其中该文件作为附件。目前,我将它发送到第二台服务器的工作地点,然后创建电子邮件并将其发送出去,这不是问题。

然而,当我尝试在那里添加第一台服务器时,我根本无法发送它,或打印出有意义的结果。以下是发送/接收脚本的代码:

<?php
$uploaddir = '/home/www/myfirstsite.com/3d/';
$uploadname = basename($_FILES['file']['name']);
$uploadfile = $uploaddir . $uploadname;


if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
        echo "OK\n";
} else {
    echo "ERROR\n";
}
echo "<br>";

$url = 'http://mysecondsite.com:12345/receive_scan.php';
//I use port 12345 because most of the important ports are being used already. 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_FILES);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
$result='Result: '.curl_exec ($ch);

echo $result;
echo curlerrno($ch);
echo curlerror($ch);
curl_close ($ch);

目前,当我发送HTTP帖子请求时,它打印出来:

OK
Result: 

我用来发送HTTP post请求的代码是:

<html><body>
<form enctype="multipart/form-data" action="http://myfirstsite.com/receive_scan.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="file" type="file" /><br />
<input type="submit" value="Upload File" />
</form>

接收的第二台服务器上的代码,如果我只是更改网站,则使用上面的代码,这是:

<?php
$uploaddir = './scans/';
$uploadname = basename($_FILES['file']['name']);
$uploadfile = $uploaddir . uploadname;

echo "File Received\n";
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
    echo "OK\n";
} else {
    echo "ERROR\n";
}
shell_exec("bash sendmail.bash ".$uploadfile." ".$uploadname);
?>

sendmail.bash只是一个使用msmtp向我的电子邮件发送电子邮件的脚本。

1 个答案:

答案 0 :(得分:0)

$ _FILES和curl post的结构不同 - 我3年前遇到过这个问题,花了我3天时间来解决:

function arraysToBrackets($array, $prefix, $level=0){

    $resarr = array();
    foreach ($array as $field => $data){
        if (is_array($data)){
            $resarr = array_merge($resarr, arraysToBrackets($data,
                    ($prefix?$prefix.'['.$field.']':$field),$level+1));
        }else{
            if ($level > 0){
                $resarr[$prefix.'['.$field.']'] = $data;
            }else{
                $resarr[$prefix.$field] = $data;
            }
        }
    }
    return $resarr;
}

$postThrough = arraysToBrackets($_POST);

if ($_FILES){

    foreach ($_FILES as $file => $details){
        if (is_array($details['name'])){
            foreach ($_FILES[$file]['name'] as $file2 => $details2){
                if ($_FILES[$file]['tmp_name'][$file2]){
                    $postThrough[$file.'['.$file2.']'] = '@'.$_FILES[$file]['tmp_name'][$file2];
                }
            }
        }else{
            if ($details['tmp_file']){
                 $postThrough[$file] = '@'.$details['tmp_file'];
            }
        }
    }
}