Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Upload file PHP sang server PHP khác


Hàm fopen, fread và fwrite có thể dùng để mở luồng file, đọc luồng dữ liệu và ghi dữ liệu đó vào file tương ứng.

Tài nguyên file không nhất thiết phải trỏ đến vị trí trên máy local.

Ví dụ chuyển file từ server local sang FTP server:

$file = "file_name.jpg"; 
$destination = fopen("ftp://username:password@example.com/" . $file, "wb"); 
$source = file_get_contents($file); 
fwrite($destination, $source, strlen($source)); 
fclose($destination);

Ảnh cần chuyển đến FTP server. Mở server ở chế độ ghi, ghi ảnh vào vị trí đó và đóng luồng.

Extension curl dùng Client URL Library (libcurl) chuyển file giữa các vị trí. Logic triển khai curl:

  • Khởi tạo session trước.
  • Thiết lập tùy chọn truyền tải mong muốn.
  • Thực hiện truyền tải.
  • Đóng session.

Session curl khởi tạo bằng 'curl_init'. Trả về resource dùng với các hàm curl khác.

Đích đến upload và các yếu tố session truyền tải thiết lập bằng 'curl_setopt'. Hàm nhận resource curl, hằng số định nghĩa sẵn setting và giá trị tùy chọn.

Ví dụ minh họa:

$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, 'https://server2/upload.php'); 
curl_exec($session_begin); 
curl_close($session_begin);

Server thứ hai xử lý như upload file thông thường.