Home > Backend Development > PHP Tutorial > PHP implements online gallery function

PHP implements online gallery function

PHPz
Release: 2023-06-22 17:54:02
Original
1847 people have browsed it

In the modern Internet era, the gallery function has become a standard feature of many websites, and PHP, as a powerful programming language, also provides a variety of ways to implement this function.

This article will introduce how to use PHP to implement a simple online gallery function to upload, browse and delete pictures.

1. Preparation

Before using PHP to implement the online gallery function, we need to prepare some basic work:

1. Install PHP and MySQL.

2. Prepare the server to support PHP file upload.

3. Use the following command to create a new MySQL user and password on the host:

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'user_password';

4. Create a new MySQL database and table to store gallery information. You can use the following commands:

CREATE DATABASE mydb;

CREATE TABLE images (
id int(11 ) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
path varchar(255) NOT NULL,
uploaded_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

5. Create a new folder to store uploads picture of.

2. Implement the upload function

First, we need to create an HTML form to allow users to upload image files. This form must have the enctype="multipart/form-data" attribute to upload files. The following is the form code:

<input type="file" name="file" id="file">
<input type="submit" name="submit" value="上传">
Copy after login

In this form, we define a file upload element and implement an "Upload File" button in native HTML. When the user clicks this button, the form will upload the file to the upload.php file on the server.

Next, we need to write the code for the upload.php file to complete processing and saving the uploaded file. The following is the code:

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES"file");
$uploadOk = 1 ;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check whether the file is an image type
if(isset($_POST["submit"])) {

$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
    echo "文件是一个图像," . $check["mime"] . ".";
    $uploadOk = 1;
} else {
    echo "文件不是一个图像。";
    $uploadOk = 0;
}
Copy after login

}

// Check if the file already exists
if (file_exists($target_file)) {

echo "抱歉,文件已经存在。";
$uploadOk = 0;
Copy after login

}

// Check the file Size
if ($_FILES"file" > 500000) {

echo "抱歉,您的文件太大。";
$uploadOk = 0;
Copy after login

}

// Allow specific file formats
if($imageFileType != "jpg" && $ imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {

echo "抱歉,只能上传JPG、JPEG、PNG和GIF格式的文件。";
$uploadOk = 0;
Copy after login

}

// Check upload status
if ($uploadOk == 0) {

echo "抱歉,您的文件未能上传。";
Copy after login

// If all goes well, try moving the file to the target directory
} else {

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
    echo "文件" . basename( $_FILES["file"]["name"]). "上传成功。";

    // 将文件路径、名称和上传时间保存到数据库中
    $img_name = $_FILES["file"]["name"];
    $img_path = $target_file;
    $sql = "INSERT INTO images (name, path) VALUES ('$img_name', '$img_path')";
    $result = mysqli_query($conn, $sql);
} else {
    echo "抱歉,发生了错误,您的文件无法上传。";
}
Copy after login

}
?>

The code first performs several checks, such as checking whether the file is an image, whether the file already exists, file size limits, and allowed file formats. If all these checks pass, the file can be moved to the specified directory and some information saved in the database for browsing and deletion operations.

3. Implement the browsing function

Next step, we need to implement the function of browsing the uploaded pictures. To do this, we need to read the image information saved in the database and display it on the web page.

The following is the code:

// Get the paths of all images from the database
$sql = "SELECT id, name, path FROM images";
$result = mysqli_query($conn, $sql);

// Loop through the path and name and output HTML
while($row = mysqli_fetch_assoc($result)) {

$img_id = $row["id"];
$img_name = $row["name"];
$img_path = $row["path"];
echo '<div class="image">';
echo '<a href="view.php?id=' . $img_id . '"><img src="' . $img_path . '" title="' . $img_name . '"></a>';
echo '</div>';
Copy after login

}
?>

4. Implement the deletion function

The last step is to add the function of deleting images. When a user uploads an image and no longer needs it, they can choose to delete it from the gallery.

The following is the code:

if(isset($_GET["delete"])) {

$id = $_GET["delete"];

// 从数据库中删除记录
$sql = "DELETE FROM images WHERE id='$id'";
$result = mysqli_query($conn, $sql);

// 删除本地文件
$info_query = "SELECT path FROM images WHERE id='$id'";
$info_result = mysqli_query($conn, $info_query);
$row = mysqli_fetch_assoc($info_result);
unlink($row["path"]);

// 将用户重定向到基页面
header("location: index.php");
Copy after login

}
?> ;

This code will delete records from the database based on the image ID and delete the specified local file. After that, redirect the user to the basic gallery page.

Summary

Through the introduction of this article, we can understand how to use PHP to implement online gallery functions, including the functions of uploading, browsing and deleting pictures.

It should be noted that some important details involved in the code, such as input validation, file size limits, and file type validation, are all set up to ensure security and integrity. In practical applications, these codes can be modified and extended according to your own needs.

The above is the detailed content of PHP implements online gallery function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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