Uploading Files Using PHP CURL

Uploading Files Using PHP CURL

To upload image file using PHP Curl is very easy, simply use the following code:
<?php
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $postUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    // same as
    $post = array
    (
        "name" => "yourname",
        "file_upload"=>"@/path/to/your/image/file.jpg",
    );

    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $response = curl_exec($ch);
?>
Note that the ‘@’ is required for it to work, CURL automatically upload the give file to server or requested URL when it find the ‘@’ symbol in starting of file name. Please also note that the $post variable must be an array, not a string, so the following will only post “name” to the server while “file_upload” field will be ignored/failed:
    $post = "name=yourname&file_upload=@/path/to/your/image/file.jpg";

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *

My new Snowflake Blog is now live. I will not be updating this blog anymore but will continue with new contents in the Snowflake world!