Skip to main content

How upload file using cURL?

How upload file using cURL?

Here I am giving an example of how you can upload file using cURL in PHP.

Code:

<?php
	$request_url = ‘http://www.akchauhan.com/test.php’;
    $post_params['name'] = urlencode(’Test User’);
    $post_params['file'] =@.'demo/testfile.txt’;
    $post_params['submit'] = urlencode(’submit’);
 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $request_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
    $result = curl_exec($ch);
    curl_close($ch);
?>

Here we have first initialized the new CURL session using “curl_init” function. Then we have set few curl options for CURL session.

CURLOPT_URL: URL to fetch.

CURLOPT_POST: TRUE to regular HTML POST.

CURLOPT_RETURNTRANSFER: TRUE to return the transfer as a string of the return value of “curl_exec” instead of outputting it out directly.

CURLOPT_POSTFIELDS: The full data to post in a HTTP “POST” operation.

You can also set more options as per your requirement but these are
the minimum require options for file upload. You can find more
information about these options in PHP manual.

Then execute the CURL session through “curl_exec” function. This function will return the output of request.

Here the tricky part is ‘@’ symbol before file name. CURL
automatically upload the give file to server or requested URL when it
find the ‘@’ symbol in starting of file name.

Note: If you try this code on localhost under
windows operating system then you might get the error message “CURL is
failed to created the post data”. But this code is work fine under Linux
environment. So, try this on your server.

The requested file “test.php” consider this request as simple POST FROM request. Like if you use this form for request.

<form method=”post” action=”test.php” enctype=”multipart/form-data”>
	<input type=textname=namevalue=”Test User” />
	<input type=”file” name=”file” />
	<input type=”submit” name=”submit” value=”submit” />
</form>

, ,