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

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

Jul 12, 2023 pm 08:16 PM
remote picture php save legal inspection

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!

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 admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add watermark and save remote images after saving them locally in PHP? How to add watermark and save remote images after saving them locally in PHP? Jul 11, 2023 pm 11:48 PM

How to add watermark and save remote images after saving them locally in PHP? In PHP development, we often encounter the need to save remote images locally. Sometimes, we may also need to add a watermark to the saved image to protect copyright or add additional information. This article will introduce how to use PHP to save remote pictures to local and add watermarks to the saved pictures. 1. Save remote images to local. First, we need to use PHP's file operation function to save remote images to local. Here is a simple example code: &

When saving remote images using PHP, how to check whether the image is legal before saving? When saving remote images using PHP, how to check whether the image is legal before saving? Jul 12, 2023 pm 08:16 PM

When saving remote images using PHP, 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

How to save remote image in PHP and generate unique filename? How to save remote image in PHP and generate unique filename? Jul 12, 2023 am 09:39 AM

How to save remote image in PHP and generate unique filename? In web development, we often encounter the need to save remote images to the local server. In order to avoid file name conflicts, we generally save these pictures by generating unique file names. This article will introduce how to use PHP to save remote pictures and generate unique file names. First, we need to use the file_get_contents() function in PHP to obtain the binary data of the remote image. The code is as follows: $url=&

How to save remote images in PHP? How to save remote images in PHP? Jul 13, 2023 pm 03:45 PM

How to save remote images in PHP? When developing websites, we often encounter situations where we need to save remote images. For example, we need to get a picture from another website and save it to our own server so that it can be displayed on our own website. PHP provides a simple and effective way to achieve this functionality. This article will introduce how to use PHP to save remote images, and attach code examples. First, we need to get the URL of the remote image. This can be done by using functions such as cURL or file_get_contents

How to save image information to the database when saving remote images using PHP? How to save image information to the database when saving remote images using PHP? Jul 13, 2023 pm 02:04 PM

How to save image information to the database when saving remote images using PHP? During the development process, it is often necessary to download images from a remote server and save relevant information to the database. This article will explain how to use PHP to complete this process. First, we need to get the content of the remote image and save it as a local file. PHP provides a function file_get_contents() that can be used to read the contents of remote files. The demo code is as follows: $remoteImageUrl='htt

Best practice for saving remote images to the server in PHP Best practice for saving remote images to the server in PHP Jul 11, 2023 pm 11:11 PM

Best practices for saving remote images to the server in PHP In web development, we often encounter the need to save remote images to the server. For example, you may need to grab an image from another website, or the user may have uploaded a remote image link. This article will introduce how to use PHP to implement this best practice of saving remote images to the server. First, we need a URL for the remote image. Suppose the URL of the image we want to save is: http://example.com/image.jpg. Next

What are the methods to save remote images using PHP? What are the methods to save remote images using PHP? Jul 13, 2023 am 09:04 AM

What are the methods to save remote images using PHP? In web development, obtaining and saving remote images is a common operation. As a popular programming language, PHP also has powerful functions and flexibility in processing images. This article will introduce several common methods of saving remote images using PHP, and attach code examples. Method 1: Use file_get_contents and file_put_contents functions $url="https://examp

How to verify the image format when saving remote images using PHP? How to verify the image format when saving remote images using PHP? Jul 12, 2023 pm 01:33 PM

How to verify the image format when saving remote images using PHP? During development, sometimes we need to save images on the remote server locally, such as saving images uploaded by users or grabbing images from web pages. In order to ensure that the saved image format is correct, we need to verify the format of the remote image. This article will introduce how to implement remote image format verification in PHP and provide corresponding code examples. 1. Obtain the format of the remote image. To verify the format of the remote image, you first need to obtain the file extension of the remote image. Can

See all articles