Có rất nhiều giải pháp để upload file lên server cho PHP như sử dụng form, ajax, ftp, scp, … Hôm nay vinasupport sẽ hướng dẫn các bạn sử dụng curl để upload file tới server sử dụng php.
Để thực hiện tutorial này chúng ta cần 3 file sau:
- curl.php: Xử lý script curl để đọc và xử lý upload file tới server (client)
- upload.php: Xử lý file nhận từ client (server)
- data.txt: File dữ liệu
Xử lý upload file tới server
File: curl.php
<?php
// CURL init
$curl = curl_init();
$fields = [
'file' => curl_file_create('data.txt'),
'description' => 'Upload file to server by url (vinasupport.com)'
];
// Set CURL options
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://localhost/upload.php',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_VERBOSE => 1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $fields,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false
));
//create the multiple cURL handle
$mh = curl_multi_init();
//add the handle
curl_multi_add_handle($mh, $curl);
//execute the handle
do {
$status = curl_multi_exec($mh, $active);
if ($active) {
curl_multi_select($mh);
}
} while ($active && $status == CURLM_OK);
//close the handles
curl_multi_remove_handle($mh, $curl);
curl_multi_close($mh);
// all of our requests are done, we can now access the results
echo curl_multi_getcontent($curl);
Trường hợp bạn thực hiện trên local thì nên set 2 option là CURLOPT_SSL_VERIFYHOST và CURLOPT_SSL_VERIFYPEER về false để tránh xác thực certificate.
Xử lý file nhận từ client
File: upload.php
Ở đây mình chỉ hiển thị dữ liệu gửi lên từ client, còn các bạn có thể tùy ý xử lý dữ liệu.
<?php // Show request data var_dump($_FILES); var_dump($_POST);
Kết quả:

Nguồn: vinasupport.com