PHP Curl通过Post Data上传文件

时间:2010-10-15 04:00:01

标签: php curl upload http-post

如何在$data内提交与此脚本位于同一目录中的文件。以下功能是我目前使用的功能。如果您在当前代码中发现任何错误,请告诉我。

function post_data($site,$data){
    $datapost = curl_init();
 $headers = array("Expect:");
    curl_setopt($datapost, CURLOPT_URL, $site);
 curl_setopt($datapost, CURLOPT_TIMEOUT, 40000);
    curl_setopt($datapost, CURLOPT_HEADER, TRUE);
 curl_setopt($datapost, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($datapost, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($datapost, CURLOPT_POST, TRUE);
    curl_setopt($datapost, CURLOPT_POSTFIELDS, $data);
     curl_setopt($datapost, CURLOPT_COOKIEFILE, "cookie.txt");
    ob_start();
    return curl_exec ($datapost);
    ob_end_clean();
    curl_close ($datapost);
    unset($datapost);    
}

1 个答案:

答案 0 :(得分:-1)

你的第一个问题是你依赖CURL, 开玩笑,但这是另一种皮肤养猫的方法:

// prepare post headers
$opts = array(
    'http' =>
    array(
        'method' => 'POST',
        'charset' => 'utf-8',
        'timeout' => '60', // must be set for error handling
        'content' => 'post data can be inserted here', // this can be a file
       ));
$context = @stream_context_create($opts);
// send post data and store response data
$response = @file_get_contents('http://www.example.org/file.php',
    false, $context);

// using this posting method one does not have to rely on any external libraries