如何使用PHP上传文件

文件上传是Web应用程序中最使用的功能。
PHP提供了一种将文件上传到服务器的简单方法。
使用PHP,我们可以通过编写最小代码将文件或者图像上传到服务器。
在本教程中,我们将提供PHP脚本以将文件上传到服务器上的目录。
使用我们的PHP文件上传脚本我们可以将包括图像的所有类型的文件上传到PHP中的服务器。

HTML上传表单

首先,需要创建HTML表单,允许用户选择要上载的文件。

确保<form>标记包含以下属性。

  • method="post"
  • enctype="multipart/form-data"

此外,请确保<input>标记包含'type =“file”'属性。

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select File to Upload:
    <input type="file" name="file">
    <input type="submit" name="submit" value="Upload">
</form>

上面的文件上传表单将被提交给Upload.php文件以将文件上传到服务器。

在PHP中上传文件(upload.php)

PHP提供了一个名为'move_uploaded_file()'的函数,将上传的文件移动到新位置。
使用'move_uploaded_file()'函数,我们可以在php中上传文件。

以下代码用于在PHP中上传文件。
指定“$targetdir”变量中的目录,其中将放置上载的文件。
此外,定义要允许上传的文件类型。

<?php
$statusMsg = '';
//file upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])) {
    //allow certain file formats
    $allowTypes = array('jpg','png','jpeg','gif','pdf');
    if(in_array($fileType, $allowTypes)){
        //upload file to server
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
            $statusMsg = "The file ".$fileName. " has been uploaded.";
        }else{
            $statusMsg = "Sorry, there was an error uploading your file.";
        }
    }else{
        $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
    }
}else{
    $statusMsg = 'Please select a file to upload.';
}
//display status message
echo $statusMsg;
?>
日期:2020-06-02 22:15:57 来源:oir作者:oir