在 CentOS 系统中,使用 PHP 进行文件上传需要遵循以下步骤:
enctype 属性设置为 multipart/form-data,以便正确传输文件数据。<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<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>
<?php
$target_dir = "uploads/"; // 指定上传文件的目录
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); // 获取上传文件的完整路径
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // 获取文件扩展名
// 检查文件是否已经存在
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// 检查文件是否为图片
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// 检查文件是否已上传
if ($_FILES["fileToUpload"]["size"] > 500000) { // 限制文件大小为 500KB
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// 允许特定文件格式
if($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// 如果一切正常,尝试上传文件
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
php -v
uploads 的目录,并设置适当的权限,以便 PHP 脚本可以将文件保存到该目录。mkdir uploads
chmod 755 uploads
uploads 目录。注意:在实际应用中,你可能需要对上传的文件进行更严格的验证和处理,以确保安全性和可靠性。