使用PHP,很容易將文件上傳到服務器。我試圖掩蓋所有事情,並儘可能簡化。
在您「的php.ini」文件,搜索php.ini的file_uploads指令,並將其設置爲開:
file_uploads = On
您可能還需要改變允許文件大小在php.ini文件,如果文件您要上傳的是比什麼是允許更大:
post_max_size = 8M; //make larger if needed
upload_max_filesize = 8M; //make larger if needed
做出這些更改後一定要重新啓動你的web服務器
(阿帕奇/ nginx的。)
- 的upload_max_filesize不應該大於post_max_size要
創建HTML表單,允許用戶選擇他們要上傳的圖片文件:
<!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>
一些規律可循的HTML表單上面:
如果沒有上述要求,文件上傳將不起作用。
其他的事情,以通知:
- 類型=「文件」的標籤的屬性示出了輸入字段作爲一個文件選擇控制,具有「瀏覽」按鈕旁邊的輸入控制
上面的表格將數據發送到名爲「upload.php」的文件,我們將在下一步創建該文件。
的「upload.php的」文件中包含的代碼,上傳文件:
<?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.";
}
}
?>
一些變量解釋:
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is used as a flag
$imageFileType holds the file extension of the file
的「一旦選擇了一個文件」表明你希望它出現立即?上傳完成後,只能設置'$ _FILES'超全局。 PHP是服務器端語言,不能監視文件輸入。你需要一個基於Javascript的解決方案。 – Oldskool 2014-12-13 11:45:22
請先看書或看教程! – Rizier123 2014-12-13 11:45:55
[客戶端和服務器端編程有什麼區別?](http:// stackoverflow。com/questions/13840429 /客戶端與服務器端編程之間的區別) – 2014-12-13 11:47:36