Uploading Files with file_get_contents() Using HTTP Stream Context
Uploading files via a web form can be achieved seamlessly using the cURL extension. However, it's also possible to perform file uploads using PHP's file_get_contents() function in conjunction with the HTTP stream context.
Multipart Content-Type
To upload a file using file_get_contents(), it's crucial to define a "multipart/form-data" Content-Type. This specifies that the request contains multiple parts, including the file data and any associated parameters. The delimiter used to separate these parts is known as a boundary.
Building the Content Body
The content body must follow the specifications of HTTP and the Content-Type header. For each file being uploaded, include the following information:
Creating the File Contents
Using file_get_contents(), obtain the contents of the file to be uploaded. Append it to the content body.
Setting Request Headers and Context
Define the Content-Type header and create an HTTP stream context using stream_context_create(). Set the request method to POST, add the headers, and specify the content body.
Executing the Upload
Finally, execute the file_get_contents() function with the appropriate URL and the configured context.
Note
Binary files can be directly sent without encoding. HTTP supports binary data transfer.
By following these steps, you can leverage file_get_contents() and the HTTP stream context to upload files to a remote web server.
The above is the detailed content of Can file_get_contents() be used for HTTP file uploads?. For more information, please follow other related articles on the PHP Chinese website!