如何在yii2中通过cUrl方法发布文件

时间:2017-08-24 05:40:55

标签: php curl yii2

我将从控制器附加一个文件并完成

 $filePath = Yii::getAlias("@backend/web/uploads/".$filename);

添加此文件后,它会发布到操作网址。我尝试使用

    $request = curl_init($url_path);
    curl_setopt($request, CURLOPT_POST, true);
    curl_setopt(
        $request,
        CURLOPT_POSTFIELDS,
        array(
            'filedata' => $file_path
        ));


    curl_setopt($request, CURLOPT_RETURNTRANSFER, true); 

但它不起作用。我需要解决方案yii2

1 个答案:

答案 0 :(得分:0)

你应该使用'file'=> '@' curl_setopt($ curl_handle,CURLOPT_SAFE_UPLOAD,false);

PHP 5.6 +上的

工作和测试示例

服务器端(index.html):

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select file to upload:
        <input type="file" name="myf" id="myf">
        <input type="submit" value="Upload" name="submit">
</form>

</body>
</html>

服务器端(upload.php):

<?php

error_reporting(E_ALL); 
ini_set('display_errors', 1);

echo $_FILES["myf"]["tmp_name"];
move_uploaded_file($_FILES["myf"]["tmp_name"], 'f.dat');

?>

客户端(curl-test.php),您需要:

<?php

$args['myf'] = '@/Users/Oleg/Temp/curl-test-php/example.txt';

$request = curl_init('http://domain.ru/upload/upload.php');
curl_setopt($request, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $args);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
curl_close($request);

?>

https://wiki.php.net/rfc/curl-file-upload 关于CURLOPT_SAFE_UPLOAD以及在需要安全解决方案时使用未弃用方法的正确方法