upload a file to a remote server in php

To upload a file to a remote server in PHP, you can use the move_uploaded_file() function. Here's an example code:

main.php
<?php

$remote_url = 'http://remote.server.com/upload.php';
$file_name_with_full_path = $_FILES["file"]["tmp_name"];

// create a CURLFile object
$cfile = new CURLFile($file_name_with_full_path);

// send a POST request with CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remote_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => $cfile));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

echo $result;
497 chars
19 lines

In this code, we first define the remote URL to which we want to upload the file. We also get the file name with its full path using the $_FILES superglobal array.

Next, we create a CURLFile object that represents the file to be uploaded. This object takes the file name with its full path as its argument.

We then send a POST request to the remote server with CURL. The CURLOPT_POSTFIELDS option is set to an array containing the file we want to upload, with the parameter name "file".

Finally, we close the CURL session and display the response from the remote server.

Note: You will need to enable the CURL extension in PHP in order to use CURL functions.

gistlibby LogSnag