- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Upload file with php to another php server
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:firstname.lastname@example.org/" . $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 −
- Initialize a session first.
- The desired transfer options can be set.
- The transfer can be performed.
- The session can be closed.
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.
- PHP file://
- How to force file download with PHP?
- How to upload file with selenium (Python)?
- How to upload large files above 500MB in PHP?
- How to upload multiple files and store them in a folder with PHP?
- file() function in PHP
- How to identify server IP address in PHP?
- How to create a file upload button with HTML?
- CSS Styling of File Upload Button with ::file-selector-button Selector
- Connecting to SAP HANA server on Cloud using PHP
- File Upload Example in Python
- How to display errors in PHP file?
- How to echo XML file in PHP
- How to import csv file in PHP?
- How to upload a file using JSP?