Monday, April 25, 2011

File Upload via CURL in PHP

Most of us must have used CURL in PHP, But have you uploaded file using it. If not I must say it is very easy .

Here is the simplest way to upload the file via CURL.


<?php
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, "http://someurl_will_go.here/test.php");
    curl_setopt($ch, CURLOPT_POST, true);
    // same as <input type="file" name="file">
    $post_array = array(
        "file"=>"@/full_path/of_the_file/with.extension",
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array); 
    $response = curl_exec($ch);
?>
]]>

Please note "@"  in front of the file name.
You can get the file in same way i.e is using "$_FILES". so you can get file in test.php in $_FILES['file']

Thanks.

2 comments:

  1. Great and helpful information. nice file uploading coding. Thanks for posting.
    http://www.dreamdestinations.in/

    ReplyDelete