Sitemap / Advertise

Information



Tags



Share

How to send and receive files via cURL in PHP

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement


Banggood
Banggood


Definition

In this tutorial, I will show you how to transfer files to a corresponding web page via cURL in PHP easily without struggling with creating an HTML form in every attempt at gathering user information.

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.(1)

Code

Save the send.php and receive.php files in the same directory.

Sending:

Define the web page you want to send files via cURL - receive.php.

Get the full file path of the requested file.

Create arguments for the post request.

To send file properties in the secure communication protocol, use the curl_file_create function - for php 5.5+ - instead of the deprecated method.

Initial the cURL request.

Set CURLOPT_URL, CURLOPT_POST, and CURLOPT_POSTFIELDS parameters.

Get the result of the request.

Stop the request.

Print the result with the response transferred by the receive.php.

Receiving:

If the cURL request is successful, save the file with the sender's name.

Print the status message.

Display the currently saved file if it is an image.


--------- send.php -----------

<?php

$web_page_to_send = "http://localhost/receive.php";

$file_name_with_full_path = $_SERVER['DOCUMENT_ROOT']."/images/test.jpg";

$post_request = array(
    "sender" => "TheAmplituhedron", 
	"file" => curl_file_create($file_name_with_full_path) // for php 5.5+
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $web_page_to_send);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_request);
$result = curl_exec($ch);
curl_close($ch);
echo "<br><br>Result: ".$result;

?>

--------- receive.php -----------

<?php

if(isset($_POST['sender'])){
	$file_name = $_POST['sender']."-".$_FILES['file']['name'];
	move_uploaded_file($_FILES['file']['tmp_name'], $file_name);
	
	echo "Successful Attempt! <br><br>Filename: ".$file_name;
	echo '<br><br> <img src="'.$file_name.'"></img>';
	
}else{
	echo 'Unauthorized Access!';
}

 ?>
 

Result:

article-image
Figure - 109.1

References

(1) https://www.php.net/manual/en/intro.curl.php