The fopen, fread and fwrite functions can be used to open a file stream, read a data stream and write that data to a file respectively.
The file resource doesn't necessarily need to point to a location on the local machine itself.
Below is an example that transfers a file from the local server to ftp server −
$file = "file_name.jpg"; $destination = fopen("ftp://username:email@example.com/" . $file, "wb"); $source = file_get_contents($file); fwrite($destination, $source, strlen($source)); fclose($destination);
The image needs to be transferred to an FTP server. Hence the server is opened in write mode, and the image is written to that location and the stream is closed.
The curl extension uses Client URL Library (libcurl) to transfer files from one location to the other. The logic of implementing a curl solution follows the below logic −
The curl session can be initialized using the 'curl_init' function. It returns a resource that could be used with other curl functions.
The destination to upload the file and other factors associated with the transfer session can be set using the 'curl_setopt'.
This takes the curl resource, that is a predefined constant which represents the setting and the optional value.
Below is an example demonstrating the same −
$session_begin = curl_init(); curl_setopt($session_begin, CURLOPT_POST, true); curl_setopt($session_begin, CURLOPT_POSTFIELDS, array('file' => 'path/to/file.txt')); curl_setopt($session_begin, CURLOPT_URL, 'http://server2/upload.php'); curl_exec($session_begin); curl_close($session_begin);
The second server can be handled as a regular file upload.