温馨提示×

php file函数如何进行文件上传

PHP
小樊
81
2024-11-28 00:43:27
栏目: 编程语言

在PHP中,要实现文件上传,可以使用$_FILES全局数组来处理上传的文件。以下是一个简单的示例,展示了如何使用file_upload()函数进行文件上传:

  1. 创建一个HTML表单,包含一个文件输入字段和一个提交按钮:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="fileToUpload">Choose a file to upload:</label>
        <input type="file" name="fileToUpload" id="fileToUpload">
        <input type="submit" value="Upload File" name="submit">
    </form>
</body>
</html>

注意enctype="multipart/form-data"属性,它允许在表单中上传文件。

  1. 创建一个名为upload.php的PHP文件,用于处理文件上传:
<?php
if (isset($_FILES['fileToUpload'])) {
    $target_file = "uploads/" . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if the file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". htmlspecialchars(basename($_FILES["fileToUpload"]["name"])). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
} else {
    echo "No file selected.";
}
?>

这个PHP脚本首先检查$_FILES数组中是否存在名为fileToUpload的文件。如果存在,它将检查文件是否已经存在于服务器上,然后尝试将文件移动到uploads目录。如果上传成功,它将显示一条成功消息;否则,它将显示一条错误消息。

确保在运行此示例之前在服务器上创建一个名为uploads的目录,并设置适当的权限,以便PHP可以将文件上传到该目录。

0