Site icon Init HTML

Tự tạo Proxy cho hình ảnh đơn giản với PHP

Để thực hành bài viết này, các bạn cần:

Đầu tiên, bạn tạo thư mục proxy trong thư mục htdocs.

proxy/
├── view.php

Tại tập tin view.php.

<?php
	$url = isset($_GET['url']) ? $_GET['url'] : null;
	
	if (!$url) {
		die('Please, inform URL');
	}
	
	$imgInfo = getimagesize($url);
	
	if (stripos($imgInfo['mime'], 'image/') === false) {
		die('Invalid image file');
	}
	
	header('Pragma: public');
	header('Cache-Control: max-age=2628000');
	header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 2628000));
	header("Content-type: " . $imgInfo['mime']);
	readfile($url);
?>

Hoặc sử dụng PHP cURL.

<?php
    $url = isset($_GET['url']) ? $_GET['url'] : null;

    if (!$url) {
        die('Please, inform URL');
    }

    $imgInfo = getimagesize($url);

    if (stripos($imgInfo['mime'], 'image/') === false) {
        die('Invalid image file');
    }

    //The cURL stuff...
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $picture = curl_exec($ch);
    curl_close($ch);

    //Display the image in the browser
    header('Pragma: public');
    header('Cache-Control: max-age=2628000');
    header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 2628000));
    header("Content-type: " . $imgInfo['mime']);
    echo $picture;
?>

Proxy sẽ tự lấy hình ảnh, tạo cache 30 ngày trên trình duyệt người dùng như một hình ảnh bình thường. Để sử dụng, bạn cần truyền đường dẫn của hình ảnh vào sau localhost/proxy/view.php?url=, ví dụ: http://localhost/proxy/view.php?url=https://i.imgur.com/waLFYwo.jpg.

Để dùng cho website, bạn có thể tải thư mục vừa tạo lên máy chủ của bạn, sử dụng tương tự như ví dụ. Để tăng tốc độ tải ảnh và tiết kiệm băng thông hơn, các bạn có thể sử dụng tính năng Page Rules của Cloudflare.

Chúc các bạn thành công!

Exit mobile version