PHP上傳文件的步驟如下:在HTML表單中添加一個元素,用type屬性設置為file。
PHP上傳文件的步驟如下:
1. 在HTML表單中添加一個元素,用type屬性設置為file。
2. 在表單中添加一個提交按鈕,用來提交表單數據。
3. 在表單的action屬性中添加一個PHP文件,它將接收文件并處理它。
4. 在PHP文件中,使用$_FILES全局變量檢查文件是否上傳成功。
5. 使用move_uploaded_file()函數將文件從臨時目錄移動到指定的目錄。
6. 如果文件上傳成功,則顯示一條消息,指出文件已成功上傳。
以下是一個示例代碼:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(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.";
}
}
?>
本站系公益性非盈利分享網址,本文來自用戶投稿,不代表碼文網立場,如若轉載,請注明出處
評論列表(23條)