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

实现文件上传功能的PHP函数

发布时间:2023-09-25 04:25:53

实现文件上传功能的PHP函数:

function uploadFile($file, $targetDirectory) {
    $fileName = $file['name'];
    $fileTmpName = $file['tmp_name'];
    $fileSize = $file['size'];
    $fileError = $file['error'];

    $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
    $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    if (in_array($fileExtension, $allowedExtensions)) {
        if ($fileError === 0) {
            if ($fileSize < 5000000) { // restrict file size to 5MB
                $newFileName = uniqid('', true) . '_' . $fileName;
                $uploadPath = $targetDirectory . '/' . $newFileName;
                move_uploaded_file($fileTmpName, $uploadPath);
                return $uploadPath;
            } else {
                return 'File size is too large. Maximum file size is 5MB.';
            }
        } else {
            return 'Error uploading file. Please try again.';
        }
    } else {
        return 'Invalid file extension. Allowed file extensions are: ' . implode(', ', $allowedExtensions);
    }
}

这个函数接受两个参数:$file代表上传的文件(从$_FILES数组中获取),$targetDirectory代表文件要上传到的目录。

函数首先从$file数组中获取上传文件的名称、临时文件路径、文件大小和上传错误信息。

然后,通过strtolower和pathinfo函数获取文件的扩展名,并将其转换为小写。

接下来,函数检查文件扩展名是否符合允许的扩展名数组。

如果符合要求,函数继续检查文件是否没有上传错误。

如果文件大小小于5MB(可以根据需要设置),函数生成一个 的文件名,然后将临时文件移动到目标目录中的新文件名。

最后,函数返回上传文件的路径,如果有错误,则返回相应的错误消息。