在 CentOS 系统下,使用 PHP 实现文件上传需要遵循以下步骤:
<!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"]); // 获取上传文件的完整路径
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // 获取文件扩展名
// 检查文件是否为图片
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
} else {
echo "File is not an image.";
}
}
// 检查文件是否已存在
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
} 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.";
}
}
?>
info.php
的文件来检查 PHP 版本和配置信息:<?php
phpinfo();
?>
将此文件上传到你的服务器,并通过浏览器访问它(例如:http://your_server_ip/info.php)。你应该能看到 PHP 的详细信息。
uploads
目录,并设置适当的权限,以便 PHP 脚本可以将文件上传到该目录。你可以使用以下命令创建目录并设置权限:mkdir uploads
chmod 755 uploads
uploads
目录。注意:在实际生产环境中,你可能需要考虑更多的安全措施,例如验证上传文件的类型、大小和内容,以防止潜在的安全风险。