Home > Backend Development > PHP Tutorial > PHP file upload methods and summary of frequently asked questions

PHP file upload methods and summary of frequently asked questions

WBOY
Release: 2023-06-08 21:30:01
Original
1176 people have browsed it

PHP file upload method and summary of frequently asked questions

File upload is one of the common functions in web development, which can be used for users to upload avatars, files, etc. PHP provides a convenient file upload processing method. This article will introduce the PHP file upload method and a summary of common problems in detail.

1. PHP file upload method

  1. HTML form

To implement file upload, you need to use an HTML form, in which the enctype attribute needs to be set to "multipart/form -data" so that the browser can correctly encode the file data and transmit it to the server. The sample code is as follows:

<form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload File" name="submit">
</form>
Copy after login
  1. PHP file processing

PHP uses the $_FILES variable to process uploaded files. The specific steps are as follows:

(1) Check the file Is it wrong?

Use $_FILES"fileToUpload" to get the error code generated when the file is uploaded. If it is 0, it means the upload is successful. Other codes indicate errors that occurred during the upload process. The sample code is as follows:

if ($_FILES["fileToUpload"]["error"] > 0) {
  echo "Sorry, there was an error uploading your file.";
}
Copy after login

(2) Move the file

Use the move_uploaded_file() function to move the uploaded file from the temporary location to the specified location on the server. The sample code is as follows:

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
  echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
  echo "Sorry, there was an error uploading your file.";
}
Copy after login

2. Common problems and solutions

  1. Upload file size limit

By default, the upload file size limit is 2MB . You can adjust the limit size by modifying upload_max_filesize and post_max_size in php.ini, or use the ini_set() function in the code. The sample code is as follows:

ini_set('upload_max_filesize', '5M'); // 限制文件上传最大为5MB
ini_set('post_max_size', '7M'); // 限制 POST 请求数据最大为7MB
Copy after login
  1. File type restrictions

You can limit the file types allowed to be uploaded by checking $_FILES "fileToUpload" in the PHP code. At the same time, you can also use PHP's MIME type restriction to define the file types that are allowed to be uploaded in an array, and check whether the MIME type of the uploaded file is in this array to limit the file type. The sample code is as follows:

$allowed_types = array('image/jpeg', 'image/png'); // 允许上传的文件类型
if (!in_array($_FILES["fileToUpload"]["type"], $allowed_types)) {
  echo "Sorry, only JPG, JPEG, and PNG files are allowed.";
}
Copy after login
  1. Duplicate uploaded file name

If the uploaded file name already exists on the server, a file name conflict will occur. You can add a timestamp. Or use random numbers or other methods to solve it. The sample code is as follows:

$target_dir = "uploads/";
$extension = strtolower(pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_EXTENSION)); // 获取文件后缀名
$new_filename = uniqid() . '.' . $extension; // 带时间戳的文件名
$target_file = $target_dir . $new_filename;
Copy after login
  1. Image file processing

If you upload an image file, you can use PHP's GD library or Imagick extension to process the image, such as cropping, Zoom, watermark and other operations. The sample code is as follows:

// 使用 GD 库将图片调整为指定大小
$src = imagecreatefromjpeg($target_file);
$dst = imagecreatetruecolor(100, 100);
imagecopyresampled($dst, $src, 0, 0, 0, 0, 100, 100, imagesx($src), imagesy($src));
imagejpeg($dst, "uploads/new_image.jpg");

// 使用 Imagick 扩展加水印
$imagick = new Imagick($target_file);
$draw = new ImagickDraw();
$draw->setFontSize(36);
$draw->setFillColor('white');
$imagick->annotateImage($draw, 10, 50, 0, "My Watermark");
$imagick->writeImage("uploads/new_image.jpg");
Copy after login

Summary

This article introduces the PHP file upload method and a summary of common problems, including HTML forms, the use of $_FILES variables and solutions to common problems. I hope it will be useful to everyone. File upload function helps.

The above is the detailed content of PHP file upload methods and summary of frequently asked questions. 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 admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template