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:
$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif'); // 允许的图片格式 $extension = pathinfo($imageUrl, PATHINFO_EXTENSION); // 获取文件后缀名 if (!in_array(strtolower($extension), $allowedExtensions)) { die('Invalid file format'); }
$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'); }
$maxFileSize = 2 * 1024 * 1024; // 最大文件大小为2MB $fileSize = filesize($tempFilePath); if ($fileSize > $maxFileSize) { die('File size too large'); }
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'; }
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!