php中上传z找照片到本地服务器
时间: 2024-01-22 18:18:53 浏览: 23
你可以使用 PHP 的文件上传功能将照片上传到服务器。以下是一个简单的示例:
1. 创建一个 HTML 表单以允许用户选择要上传的文件:
```html
<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>
```
2. 创建一个 PHP 脚本来处理上传的文件:
```php
<?php
$target_dir = "uploads/"; // 上传目录
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); // 上传文件的完整路径
$uploadOk = 1; // 上传标志
// 检查文件是否为图像
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;
}
}
// 检查文件是否已经存在
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// 检查文件大小
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// 允许特定的文件格式
$allowed_extensions = array("jpg", "jpeg", "png", "gif");
$file_extension = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(!in_array($file_extension, $allowed_extensions)) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// 如果上传标志为 0,则表示上传失败
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// 如果上传标志为 1,则表示上传成功
} 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.";
}
}
?>
```
上传的文件将保存在指定的目录中,例如:uploads/。注意,你需要确保上传文件的目录具有正确的权限,以便 PHP 脚本可以将文件写入该目录。