首页 > 解决方案 > 如何在 PHP 上传器中重命名某些文件扩展名?

问题描述

我正在努力做到这一点,因此当用户上传 .sh 文件时,它会在文件到达我的服务器之前将文件扩展名更改为 .txt。我目前的代码是

$fileName = $_FILES["file"]["name"];
$fileSize = $_FILES["file"]["size"];
$fileExt = explode(".", $fileName);
$fileRealExt = strtolower(end($fileExt));
$uploadDirectory = "/uploads/";
$currentDirectory = getcwd();
$uploadPath = $currentDirectory . $uploadDirectory . basename($fileName);
$newFileName = uniqid("", true)  . "." . $fileRealExt;
$fileTmpName = $_FILES["file"]["tmp_name"];
$fileUploadPath = $currentDirectory . $uploadDirectory . $newFileName;
$notAllowed = array("sh");
if (isset($_POST["submit"])) {
        if (in_array($fileRealExt, $notAllowed)) {
                $fileName = $fileExt[0] . ".txt";
                $newFileName = uniqid("", true)  . ".txt";
                $didUpload = move_uploaded_file($fileTmpName, $fileUploadPath);
                if ($didUpload) {
                        header("Location: $uploadDirectory$newFileName");
                } else{
                        header("Location: error.php");
                }
        }
}
?>

现在它所做的是header()将您带到带有 .txt 扩展名的随机文件名,但它会在那里并且根本不会上传。我怎样才能解决这个问题?

标签: phpfile-uploadtemporary-filestmp

解决方案


推荐阅读