使用CURL上传PHP文件

时间:2016-01-18 04:36:54

标签: php curl

我使用PHP将文件从服务器s1上传到服务器s2我的代码是:

// initialise the curl request
    $request = curl_init('http://myip/filepath/');

    // send a file
    curl_setopt($request, CURLOPT_POST, true);
    curl_setopt(
        $request,
        CURLOPT_POSTFIELDS,
        array(
          'file' => new CurlFile('photos/081452_7893637.jpg')
        ));

    // output the response
    curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
    echo curl_exec($request);

    // close the session
    curl_close($request);

当我运行此脚本时,错误是:

The requested URL / was not found on this server.

但是当我从URL浏览它时,它工作正常。 任何人都可以帮助我的脚本有什么问题吗? 感谢

1 个答案:

答案 0 :(得分:0)

// initialise the curl request
    $request = curl_init('http://myip/filepath/');


    function getFile($filename, $contentType, $postname)
{
    if (function_exists('curl_file_create')) {
        return curl_file_create($filename, $contentType, $postname);
    }
    $value = "@{$this->filename};filename=" . $postname;
    if ($contentType) {
        $value .= ';type=' . $contentType;
    }
    return $value;
}


    // send a file
    curl_setopt($request, CURLOPT_POST, true);
    curl_setopt(
        $request,
        CURLOPT_POSTFIELDS,
        array(
          'file' =>getFile('photos/081452_7893637.jpg','image/jpeg','dummy.jpg')
        ));

    // output the response
    curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
    echo curl_exec($request);

    // close the session
    curl_close($request);