When saving remote images using PHP, how to check whether the image is legal before saving?

WBOY
Release: 2023-07-12 20:18:02
Original
915 people have browsed it

When using PHP to save remote images, how to check whether the image is legal before saving?

During development, we often encounter the need to save remote images, such as crawling images on web pages, users uploading avatars, etc. However, in order to ensure the security of the server and reduce unnecessary waste of resources, we need to perform a legality check before saving remote images. This article will introduce how to use PHP to check the legality of images before saving, and provide corresponding code examples.

1. Check the legality of the image
Before saving the remote image, we need to ensure that the image is legal and avoid saving malicious scripts or unsupported file formats. The following are some common checking methods:

  1. Checking the file suffix
    The file suffix is ​​a simple way to determine the file type. Usually, we can use PHP's pathinfo function to get the file extension and compare it with the supported image formats. You can use the in_array function to determine whether the file suffix name is within the allowed range, as shown below:
$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif'); // 允许的图片格式
$extension = pathinfo($imageUrl, PATHINFO_EXTENSION); // 获取文件后缀名

if (!in_array(strtolower($extension), $allowedExtensions)) {
    die('Invalid file format');
}
Copy after login
  1. Check the file format
    In addition to checking the file suffix name, we can also pass the file The header information determines the file format. Before saving the remote image, you can use PHP's get_headers function to send a HEAD request to obtain the response header information. Then, we can set the corresponding Content-Type header field according to different file formats, and then compare it with the supported image formats. The following is a sample code:
$responseHeaders = get_headers($imageUrl);
$contentType = '';

foreach ($responseHeaders as $header) {
    if (strpos($header, 'Content-Type:') === 0) {
        $contentType = substr($header, 14);
        break;
    }
}

$allowedContentTypes = array('image/jpeg', 'image/png', 'image/gif');
if (!in_array($contentType, $allowedContentTypes)) {
    die('Invalid file format');
}
Copy after login
  1. Check file size
    To avoid saving overly large images, we can limit the size of the uploaded file. You can use PHP's filesize function to get the file size and then compare it to the set maximum value. The following is a sample code:
$maxFileSize = 2 * 1024 * 1024; // 最大文件大小为2MB
$fileSize = filesize($tempFilePath);

if ($fileSize > $maxFileSize) {
    die('File size too large');
}
Copy after login

2. Save remote images
After confirming the legality of the remote image, we can use PHP's file_put_contents function to save the image to the server. The following is a sample code:

// 获取远程图片内容
$imageData = file_get_contents($imageUrl);

// 生成保存路径和文件名(可根据实际需求修改)
$savePath = 'path/to/save/directory/';
$saveFileName = uniqid() . '.' . $extension;
$saveFilePath = $savePath . $saveFileName;

// 保存图片
if (file_put_contents($saveFilePath, $imageData)) {
    echo 'Save successfully';
} else {
    echo 'Save failed';
}
Copy after login

The above is how to check whether the image is legal before saving when using PHP to save a remote image. By checking the file extension, file format, file size, etc., you can increase the security of the server and ensure that the saved pictures are legal. Hope this article can help you.

The above is the detailed content of When saving remote images using PHP, how to check whether the image is legal before saving?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!