php cURL发送文件无法正常工作

时间:2018-01-16 08:36:57

标签: php curl

我正在尝试通过php cURL发送.txt文件,但没有成功。

我的cURL代码如下所示:

$filedata = curl_file_create('../path/to/file.txt', 'text/plain', 'file.txt');

$array = array(
    'action' => 1,
    'file' => $filedata,
    'sec_secure' => $sec_secure,
)

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://domain_name.com/url/to/script.php');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
$result = curl_exec($ch);
curl_close($ch);

$response = 0;

if($sec_secure == $result){
    $response = 1;
}

接收script.php:

if(isset($_FILES['file'])){
    $contents = file_get_contents($_FILES['file']['tmp_name']);
    $response = $_POST['sec_secure'];
}
else{
    $response = '';
}
echo $response;

问题是总是给我 $ response = 0

有谁知道为什么会发生这种情况以及如何使其正常工作?

修改

我在$ array之后错过了这一行:

$array = http_build_query($array);

也许这导致了这个问题?

2 个答案:

答案 0 :(得分:1)

您必须为文件传输设置enctype=”multipart/form-data”

CURLOPT_HEADER设为true

CURLOPT_HTTPHEADER设为array("Content-Type:multipart/form-data");

答案 1 :(得分:0)

在卷曲中添加标题。

$array = array(
    'action' => 1,
    'file' => $filedata,
    'sec_secure' => $sec_secure,
)
$array = json_encode($array);

$headers = array(

        'Content-Type: application/json',
            'Content-Length: ' . strlen($array)
    );

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $array);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
$result = curl_exec($ch);
curl_close($ch);

$response = 0;

if($sec_secure == $result){
    $response = 1;
}

像这样更改代码。