📜  php准备好的语句上传文件 - PHP(1)

📅  最后修改于: 2023-12-03 15:03:45.469000             🧑  作者: Mango

PHP准备好的语句上传文件

在Web开发中,文件上传是非常常见的操作之一。PHP作为一种Web编程语言,提供了许多简单而有效的方法来处理文件上传。以下是PHP处理文件上传的一些准备好的语句,可以帮助程序员轻松有效地进行文件上传操作。

HTML表单

在上传文件之前,我们需要为上传文件的HTML表单指定“enctype”属性。这个属性告诉服务器在处理此表单时需要使用“multipart/form-data”编码。以下是HTML表单的示例:

<form method="post" enctype="multipart/form-data">
    <input type="file" name="myfile">
    <input type="submit" value="Upload">
</form>
PHP上传代码
单个文件上传

以下PHP代码可用于上传单个文件:

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

// 检查文件是否已存在
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// 检查文件大小是否超过10MB
if ($_FILES["myfile"]["size"] > 10000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// 允许上传的文件格式(此处为图片格式)
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

// 检查上传状态
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// 如果所有检查都通过,则上传文件
} else {
    if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $target_file)) {
        echo "The file ". htmlspecialchars( basename( $_FILES["myfile"]["name"])). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
多个文件上传

以下PHP代码可用于上传多个文件:

<?php
$target_dir = "uploads/";
$uploadOk = 1;
foreach($_FILES["myfiles"]["tmp_name"] as $key=>$tmp_name) {
    $target_file = $target_dir . basename($_FILES["myfiles"]["name"][$key]);
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    
    // 检查文件是否已存在
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    
    // 检查文件大小是否超过10MB
    if ($_FILES["myfiles"]["size"][$key] > 10000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    
    // 允许上传的文件格式(此处为图片格式)
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    
    // 检查上传状态
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // 如果所有检查都通过,则上传文件
    } else {
        if (move_uploaded_file($tmp_name, $target_file)) {
            echo "The file ". htmlspecialchars( basename( $_FILES["myfiles"]["name"][$key])). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>
结论

这些PHP准备好的语句可以帮助程序员以最简单和最有效的方式处理文件上传,无论是单个还是多个文件。将这些语句和示例代码和HTML表单一起使用即可轻松完成文件上传操作。