我在使用PHP上传文件时遇到问题。我已经和它搏斗了几天。我确信解决方案很简单,但我是一名新的编码员。
我正在从书中复制练习(PHP第4版)。当我尝试使用此脚本上传任何内容时,没有任何反应。该页面只是刷新。没有打印错误或任何错误。
我在Windows 10上使用WAMP。这是代码。有什么事情可以跳到任何人身上吗?
<!DOCTYPE html>
<html>
<head>
<title>Upload A File</title>
</head>
<body>
<?php // Script 11.4 - upload_file.php
// address error reporting
error_reporting(E_ALL & ~E_NOTICE);
// Check if the form was submitted
if ($_SERVER['REQEST_METHOD'] == 'POST') {
// Move file to final destination
if (move_uploaded_file ($_FILES['the_file']['tmp_name'], "../uploads/{$_FILES['the_file']['name']}")) {
echo '<p>Your file has been uploaded.</p>';
} else { // Problem!
echo '<p style="color: red;"> Your file could not be uploaded because: ';
// Print an error message if file relocation didn't work
switch ($_FILES['the_file']['error']) {
case 1:
echo 'The file exceed the upload_max_filesize setting in php.ini';
break;
case 2:
echo 'The file exceed the MAX_FILE_SIZE setting in the HTML form';
break;
case 3:
echo 'The file was only partially uploaded';
break;
case 4:
echo 'No file was uploaded';
break;
case 6:
echo 'The temporary folder does not exist.';
break;
default:
echo 'Something unforseen happened.........';
break;
}
// Complete the error message and close both conditionals
echo '.</p>'; // Complete the end of paragraph
} // End of move_uploaded_file() IF
} // End of submission IF
?>
<form action="upload_file.php" enctype="multipart/form-data" method="post">
<p>Upload a file using this form:</p>
<input type="hidden" name="MAX_FILE_SIZE" value="300,000">
<p><input type="file" name="the_file"></p>
<p><input type="submit" name="submit" value="Upload This File"></p>
</form>
</body>
</html>
答案 0 :(得分:0)
你在这一行中有一个错字:
if ($_SERVER['REQEST_METHOD'] == 'POST') {
应该是
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
旁注:不要压制通知。您应该始终使用error_reporting(E_ALL)
,或者至少使用error_reporting(E_ALL & ~E_STRICT)
设置,它将帮助您学习检查是否设置了变量或数组索引等良好实践。它会要求你写一些额外的样板代码,但以后会为你节省很多痛苦。在这种情况下,您会马上发现Undefined index "REQEST_METHOD" in line 7
。
答案 1 :(得分:0)
什么跳出来对我?
1 )好吧,Zasada先生是正确的$_SERVER['REQUEST_METHOD']
有拼写错误(信用到期)。此外,缺少开头<html>
标记(尽管这不会影响PHP)。
2 )在最终项目中,使用用户代理提供的文件名$_FILES['the_file']['name']}
是不可取的,不采取安全预防措施(过滤/验证)。有些人会完全避免使用用户提供的文件名。
3 )文件移动声明中缺少is_uploaded_file($_FILES['the_file']['tmp_name'])
。有人可能会说move_uploaded_file()
就够了,但我说快速的双重检查不会有害。 : - )
if(is_uploaded_file($_FILES['the_file']['tmp_name']) &&
move_uploaded_file ($_FILES['the_file']['tmp_name'], "../uploads/{$_FILES['the_file']['name']}")){}