欢迎访问宙启技术站
智能推送

PHP文件处理函数和文件上传

发布时间:2023-06-23 11:52:29

PHP文件处理函数

PHP提供了许多文件处理函数来操作文件。以下是一些最常用的PHP文件处理函数:

1. fopen() - 打开文件

2. fwrite() - 写入文件

3. fclose() - 关闭文件

4. fgets() - 读取文件一行

5. filesize() - 获取文件大小

6. unlink() - 删除文件

7. rename() - 重命名文件

8. copy() - 复制文件

9. file_exists() - 判断文件是否存在

文件上传

在网站开发中,文件上传是一个常见的需求。PHP提供了一个内置的方法来处理文件上传,那就是$_FILES数组。

以下是一个实现文件上传功能的简单示例代码:

<form action="upload.php" method="post" enctype="multipart/form-data">

    Select file to upload:

    <input type="file" name="fileToUpload" id="fileToUpload">

    <input type="submit" value="Upload File" name="submit">

</form>

upload.php文件:

<?php

$target_dir = "uploads/";

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

$uploadOk = 1;

$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file already exists

if (file_exists($target_file)) {

    echo "Sorry, file already exists.";

    $uploadOk = 0;

}

// Check file size

if ($_FILES["fileToUpload"]["size"] > 500000) {

    echo "Sorry, your file is too large.";

    $uploadOk = 0;

}

// Allow certain file formats

if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"

&& $imageFileType != "gif" ) {

    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";

    $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 ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";

    } else {

        echo "Sorry, there was an error uploading your file.";

    }

}

?>

以上代码会把上传的文件保存到uploads文件夹下,并对上传文件进行一些安全性检查。在实际开发中,需要根据具体需求对文件上传进行一些自定义配置和规范。