Home > Backend Development > PHP Problem > Example analysis of how to use PHP to implement the function of previewing without uploading

Example analysis of how to use PHP to implement the function of previewing without uploading

PHPz
Release: 2023-04-04 13:36:02
Original
634 people have browsed it

PHP is a commonly used server-side programming language, often used for Web development. Its advantage is that it is easy to learn and use, and is widely used in commercial and open source projects. During the development process, uploading files is a must because it provides a simple and effective way to upload files to the web server. However, sometimes we hope that the files uploaded by users are not displayed directly on the web page, but need to be processed in the background before being displayed. So how do we achieve this?

In this article, I will introduce how to use PHP to implement the function of previewing without uploading. Before you begin, make sure you are familiar with PHP basics.

Step 1: Create an HTML form

First, we need to create a file upload form on the HTML page so that users can upload files. In the form, we need to add a standard file type input element and a submit button. The code is as follows:

<html>
    <head>
        <title>文件上传示例</title>
    </head>
    <body>
        <form action="upload.php" method="post" enctype="multipart/form-data">
            <input type="file" name="file">
            <br>
            <input type="submit" value="上传">
        </form>
    </body>
</html>
Copy after login

Step 2: Upload and process the file

When the user clicks the submit button , the form's data will be sent to the upload.php file on the server. We need to complete the task of file upload and processing in this file.

First, we need to check whether the uploaded file exists and determine whether there are errors during the upload process. In order to achieve this function, we can use the PHP built-in functions is_uploaded_file() and move_uploaded_file(). The code is as follows:

<?php

if (isset($_FILES["file"]) && !empty($_FILES["file"]["name"])) {
    $file = $_FILES["file"];

    // 检查上传的文件是否是有效的文件
    if (!is_uploaded_file($file["tmp_name"])) {
        die("上传文件无效");
    }

    // 将上传的文件从临时目录移动到我们指定的目录
    if (!move_uploaded_file($file["tmp_name"], "./upload/" . $file["name"])) {
        die("无法移动文件");
    }

    // 在这里对上传的文件进行处理,例如调用ImageMagick库对图片进行处理
    // ......
} else {
    die("请选择要上传的文件");
}

?>
Copy after login

In this example, we first check whether the uploaded file is valid. If the file is invalid, output "The uploaded file is invalid" and exit the program. If the file is valid, it is moved to the directory we specified. If any error occurs during the move, "Unable to move file" is output and the program exits. Finally, in other parts of this script, we can do something with the uploaded file.

Step 3: Do not return to preview directly

In the above code, we have uploaded and processed the file. However, our goal is not to return the preview directly. In order to achieve this goal, we need to save the URL of the uploaded file into a database and generate a key at the same time. We can then pass this key to the user and tell them to use it to view the file in the future.

Suppose we have a database named "files" which contains a column named "url" and a column named "key". We can save the URL of the uploaded file and the generated key into the database using the following code:

<?php

// 建立数据库连接
$host = "localhost";
$username = "root";
$password = "";
$database = "files";
$conn = mysqli_connect($host, $username, $password, $database);

// 检查连接
if (!$conn) {
    die("连接失败: " . mysqli_connect_error());
}

if (isset($_FILES["file"]) && !empty($_FILES["file"]["name"])) {
    $file = $_FILES["file"];

    // 检查上传的文件是否是有效的文件
    if (!is_uploaded_file($file["tmp_name"])) {
        die("上传文件无效");
    }

    // 将上传的文件从临时目录移动到我们指定的目录
    if (!move_uploaded_file($file["tmp_name"], "./upload/" . $file["name"])) {
        die("无法移动文件");
    }

    // 在这里对上传的文件进行处理,例如调用ImageMagick库对图片进行处理
    // ......

    // 将上传文件的URL和生成的密钥存储到数据库中
    $url = "http://www.example.com/upload/" . $file["name"];
    $key = md5($url . time());
    $sql = "INSERT INTO files (url, `key`) VALUES (&#39;$url&#39;, &#39;$key&#39;)";

    if (mysqli_query($conn, $sql)) {
        echo "上传成功,密钥是 $key";
    } else {
        echo "上传失败,请重试";
    }
} else {
    die("请选择要上传的文件");
}

// 关闭数据库连接
mysqli_close($conn);

?>
Copy after login

In the above code, we have used the MySQLi library to connect to the database. We first establish the connection before uploading the file and close the connection after uploading the file. We then store the URL of the uploaded file and the generated key into the database so that we can later look up the file based on the key.

Step 4: Display the file

Now that we have uploaded the file and saved it to the database, we can find the file based on the key and display it. We just need to create a URL containing the "key" query string parameter and then link it to a link or button in the HTML page. When the user clicks the link or button, the system uses that key to look up the file from the database and displays it in a new page.

The following is a simple sample code:

<?php

// 建立数据库连接
$host = "localhost";
$username = "root";
$password = "";
$database = "files";
$conn = mysqli_connect($host, $username, $password, $database);

// 检查连接
if (!$conn) {
    die("连接失败: " . mysqli_connect_error());
}

if (isset($_GET["key"]) && !empty($_GET["key"])) {
    $key = $_GET["key"];

    // 从数据库中查找URL
    $sql = "SELECT url FROM files WHERE `key`=&#39;$key&#39; LIMIT 1";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        // 找到URL
        $row = mysqli_fetch_assoc($result);
        $url = $row["url"];
        echo '<img src="&#39; . $url . &#39;">';
    } else {
        // 找不到URL
        die("文件不存在");
    }
} else {
    die("无效的密钥");
}

// 关闭数据库连接
mysqli_close($conn);

?>
Copy after login

In the above code, we first establish a database connection. We then check the query string for the "key" parameter and use that to look up the URL from the database. If found, the file is displayed. Otherwise, if the key is invalid, an error message is output.

Conclusion

In this article, we introduced how to use PHP to implement the function of previewing without uploading. We can save the URL of the uploaded file into the database and generate a key for it. We can then pass that key to the user and tell them to use that key to view the file in the future. Using this method, we can have greater control over the files on the website and ensure that files can only be viewed under specific conditions.

The above is the detailed content of Example analysis of how to use PHP to implement the function of previewing without uploading. 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