【发布时间】:2019-03-14 13:14:02
【问题描述】:
我想启用将文件直接上传到根目录。支持的文件扩展名应为:.txt、.rar、.xml、.zip。我正在尝试使用 w3schools 的代码来执行此操作,因为我是 php 和 wordpress 插件开发的初学者。插件有效,左侧管理栏有一个菜单图标,管理页面上有一个上传选项,但是当我“上传”文件时,上传文件夹中没有文件(我首先尝试这样做就像代码在 w3schools 上。代码是:
HTML
<div class="wrap">
<h2>Test file upload page</h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</div>
和 PHP 文件 (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 image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// 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.";
}
}
?>
我知道这不是一个好方法,而且我想要做的事情有 Wordpress 功能,但我只是想尝试这种方式......如果你知道更好的方法,我会感谢您睁开我的眼睛。另外,我还有一个问题:文件上传可以在本地工作吗?我的意思是,我正在使用 MAMP 在 localhost 上做所有事情,这是出于练习目的。
我没有编辑任何代码来支持我需要的文件扩展名,因为我首先想测试它是否适用于图像文件,但事实并非如此。
编辑 1:
我还看到在 php.ini 文件中 file_uploads 指令应该设置为 On:
file_uploads = On
但是,wordpress 目录中没有 php.ini 文件。有没有办法用 wordpress 插件编辑 php.ini 文件?也许这就是问题所在。只是猜测。
【问题讨论】:
标签: php wordpress file-upload