Home > Backend Development > PHP Problem > How to upload files and save them to the database in php

How to upload files and save them to the database in php

PHPz
Release: 2023-04-06 10:04:01
Original
1860 people have browsed it

File uploading is a very common feature in modern applications, and web applications are no exception. In web applications, we sometimes need to allow users to upload files such as pictures, documents, etc., and PHP is a popular server-side scripting language that can easily handle file upload operations. In this article, we will explain how to save uploaded files into a database using PHP.

  1. HTML form preparation

First, we need an HTML form so that the user can select the file to upload. We use HTML5's element to build the form. The HTML 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="上传文件" name="submit">
</form>
Copy after login

The action attribute in the form tag specifies the URL of the file upload processing script, and the method attribute specifies the The HTTP method used. We use the POST method because we need to save the uploaded file to the server.

The enctype attribute specifies the encoding type to be used. In order to be able to upload files, we specify multipart/form-data.

element is used to select the file to upload. We also added a submit button so users can upload selected files to the server.

  1. Server-side processing script

Now we need to write a PHP script to handle the request to upload the file. We will write this script in the upload.php file. In this script, we will first check if the uploaded file exists and if the upload was successful. If the upload is successful, we will get the data from the uploaded file and save it to the database.

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "文件是一个图片类型 - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "文件不是一个图片类型.";
    $uploadOk = 0;
  }
}

// Check if file already exists
if (file_exists($target_file)) {
  echo "已存在同名文件.";
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "文件太大了.";
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "只支持JPG, JPEG, PNG和GIF文件类型.";
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "文件上传失败.";

// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "文件 ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). "已经被上传.";
    
    // 保存文件数据到数据库中 
    
  } else {
    echo "文件上传发生错误.";
  }
}
?>
Copy after login

In this script, the $target_dir variable specifies the directory for uploading files. The $target_file variable specifies the file name to save to. The $_FILES variable contains the data of the uploaded file. We use the basename() function to get the file name and the strtolower() function to convert the extension to lowercase. The $uploadOk variable is used to track whether the upload is successful, and the $imageFileType variable stores the type of uploaded file.

We use the getimagesize() function to check whether the uploaded file is of image type. If it is an image type, we will output the mime type of the file. If not, we will set the $uploadOk variable to 0, indicating that the upload failed.

Next, we check if the file already exists. If it exists, set the $uploadOk variable to 0, indicating that the upload failed.

We also check if the file size meets the requirements. If it is larger than 500 KB, set the $uploadOk variable to 0, indicating that the upload failed.

Finally, we check whether the file type meets the requirements. Now only JPG, JPEG, PNG and GIF types are supported. If not, set the $uploadOk variable to 0, indicating that the upload failed.

If all checks pass, try to move the uploaded file to the specified directory. If the move is successful, a message that the file has been uploaded is output and the data of the uploaded file is saved in the database. Otherwise, an error message is output.

  1. Save file data to the database

After successfully uploading the file, we need to save the file data to the database. In this example, we create a database table with 3 fields: id, fileName, and fileData.

Achieving this function requires a database connection and a $sql statement. The $sql statement needs to insert both the file name and the file data. In PHP, we can use the fopen(), fread() and fclose() functions to process file data. So, to insert file data into the $sql statement, we need to first use the fopen() function to open the file, then use the fread() function to read data from the file, and finally use the fclose() function to close the file. The code is as follows:

<?php
$conn = new mysqli("localhost", "root", "", "test");
if ($conn->connect_error) {
  die("连接数据库失败: " . $conn->connect_error);
}

// Check server connection
if ($conn->connect_error) {
  die("连接数据库失败: " . $conn->connect_error);
} 

$fileName = $_FILES["fileToUpload"]["name"];
$fileData = "";

// Open the file for reading
$file = fopen($target_file, "r");

// Read from the file until the end
while(!feof($file)) {
  $fileData .= fread($file, 8192);
}

// Close the file
fclose($file);

// Prepare SQL statement
$sql = "INSERT INTO upload_files (fileName, fileData) VALUES ('$fileName', '$fileData')";

if ($conn->query($sql) === TRUE) {
  echo "上传成功!";
} else {
  echo "上传失败:" . $conn->error;
}

$conn->close();
?>
Copy after login

In this script, we open the file and use the fread() function to read all the data of the file. This data is stored in the $fileData variable, and new uploaded file data is inserted in the $sql statement.

Now, we have implemented the function of saving uploaded files into the database.

Summary

In this article, we introduced how to upload files and save file data into a database using PHP. We started with an HTML form, then wrote a server-side processing script and saved the uploaded file data into a database. This example demonstrates a complete process of uploading and saving files to the database and should be useful to web developers.

The above is the detailed content of How to upload files and save them to the database in php. 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