Home >Backend Development >PHP Tutorial >Can file_get_contents() Perform File Uploads with multipart/form-data?
Uploading Files with file_get_contents() and multipart/form-data
Despite the ease of file uploads with CURL, users may be curious whether file_get_contents() can perform this task using the http stream context.
Multipart Content-Type presents a challenge in file uploading. It requires defining a boundary to delimit each part within the uploaded file. This boundary, as any string not contained in the content body, can be generated using a timestamp with microtime(true).
Once the boundary is defined, it must be specified in the Content-Type header. Additionally, a content body following the HTTP specification and the sent header needs to be constructed. Each form field name must be included in the Content-Disposition header, along with filename and Content-Type headers.
If multiple files are to be uploaded, the process of generating the $content string must be repeated for each file, specifying different FORM_FIELD values accordingly.
Finally, the stream context can be built using the context parameter of file_get_contents(). The http array within the context parameter configures the method (POST), headers (including the Content-Type with the multipart boundary), and content.
By executing file_get_contents() with the configured context, the file upload is initiated. Notably, binary file encoding is unnecessary as HTTP can effectively handle binary data.
The above is the detailed content of Can file_get_contents() Perform File Uploads with multipart/form-data?. For more information, please follow other related articles on the PHP Chinese website!