gpt4 book ai didi

php - 我怎样才能使 W3schools php 上传示例工作?

转载 作者:太空宇宙 更新时间:2023-11-04 09:17:10 24 4
gpt4 key购买 nike

我在 Linux 上使用 apache,我复制并粘贴了 https://www.w3schools.com/php/php_file_upload.asp 中的代码它得到了“抱歉,上传您的文件时出错”,可以在最后一个 else 语句中找到。

代码如下:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["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["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.";
}
}
?>

上传表格.php:

<!DOCTYPE html>
<html>
<body>

<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>

</body>
</html>

我什至尝试将 $target_dir = "uploads/" 更改为 $target_dir = "/var/www/html/uploads/" 因为我在那里创建了上传目录.如何获取我尝试上传的 jpg 文件并将其保存到本地服务器上的上传文件夹中。

最佳答案

这是您的代码:

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.";
}

由于您获得了 if/else 的后半部分,您知道 move_uploaded_file 返回了一个错误值。

所以 look at the documentation for that function :

Returns TRUE on success.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

由于您已经对该文件进行了一系列检查,您知道它是一个有效的上传文件,因此第三段必须是解释问题的段落。

它说会发出警告,所以turn on all errors and warnings然后查看输出的消息。

这会告诉您问题出在哪里(我猜是网络服务器没有目标目录的写权限)。

关于php - 我怎样才能使 W3schools php 上传示例工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46043591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com