我目前正在编写最基本的文件上传来从输入type =“file”属性转到我们的服务器。这是我的HTML:
<form enctype="multipart/form-data" action="register-complete.php" method="post">
<h5>Register Now</h5>
<input type="text" class="form-control" name="Username" placeholder="Login Name"/><br />
<input type="text" class="form-control" name="Displayname" placeholder="Display Name"/><br />
<input type="text" class="form-control" name="Email" placeholder="Email" /><br />
<input type="radio" name="Paypal" value="1" /> This is my Paypal email.<br />
<input type="radio" name="Paypal" value="0" /> I do not want payment. I wish to preserve anonymity.<br /><br />
Avatar Picture: <br /><input type="file" name="AvatarPicture" id="AvatarPicture" />*500kb max file size.<br />*Accepted filetypes: .jpg, .png<br /><br />
<input type="text" class="form-control" name="Description" placeholder="Account Description"/><br />
<input type="password" class="form-control" name="Password" placeholder="Password"/><br />
<input type="password" class="form-control" name="PasswordConfirm" placeholder="Confirm Password"/><br />
<p class="text-center"><input type="submit" class="btn btn-primary" value="Register" name="submit" /></p>
</form>
基本上我只关心AvatarPicture输入,只是让它将文件上传到我的服务器。这是我必须做的PHP代码。
$username = $_REQUEST["Username"];
$displayname = $_REQUEST["Displayname"];
$email = $_REQUEST["Email"];
$paypal = $_REQUEST["Paypal"];
$target_dir = "images/avipictures/";
$target_file = $target_dir . basename($_FILES["AvatarPicture"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["AvatarPicture"]["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["AvatarPicture"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
echo "Sorry, only JPG, JPEG, PNG 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["AvatarPicture"]["tmp_name"],$target_file)) {
echo "The file has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
这与w3schools代码发球完全相同。但是我收到内部服务器500错误,除非我将move_uploaded_file()中的“tmp_name”更改为“name”,这只会导致else语句。我整天都在乱搞这个问题而且我刚刚把头发弄掉了,这段代码应该是多么简单,但似乎根本就没有。有任何想法吗? (另外,file_uploads设置为on,默认最大文件大小设置为50mb。)
答案 0 :(得分:0)
如果没有合适的日志文件,我无法说明问题是什么,但可能是您尝试写入的目录不存在或者您没有写入的权限。您确定您尝试写入的images / avipictures /目录是否存在,以及Web服务器是否有权写入它?如果没有,您需要创建目录并在其上设置权限,以便Web服务器可以写入该目录。