[英]Can't upload a file with PHP. Page just refreshes
我在使用PHP上傳文件時遇到問題。 我已經和它搏斗了幾天。 我確信解決方案很簡單,但我是一個新的編碼器。
我正在從一本書(PHP for the 4th 4th edition)復制練習。 當我嘗試使用此腳本上傳任何內容時,沒有任何反應。 該頁面只是刷新。 沒有錯誤打印或任何東西。
我在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>
你在這一行有一個錯字:
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 )嗯,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']}")){}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.