在构建一个网站时,我们经常需要将用户上传的图片存储到服务器上,这可以通过PHP来实现,PHP是一种广泛使用的开源脚本语言,特别适合于Web开发并可以嵌入HTML,本文将详细介绍如何使用PHP将图片上传到网站空间。
我们需要创建一个HTML表单,用户可以在这个表单中选择他们想要上传的图片,这个表单应该包含一个文件输入字段和一个提交按钮。
Markup
<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>
在上面的代码中,action
属性指定了当用户点击提交按钮时,表单数据将被发送到哪个PHP脚本进行处理。method
属性指定了数据的传输方式,这里我们使用POST方法,因为文件上传通常使用这种方法。enctype
属性指定了编码类型,这里我们使用multipart/form-data
,这是因为文件上传需要这种编码类型。
接下来,我们需要创建一个PHP脚本来处理用户上传的图片,这个脚本应该首先检查是否有文件被上传,然后获取文件的信息,包括文件名、大小和类型,我们需要将文件移动到一个我们希望存储图片的目录。
PHP
<?php
$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) { // 500KB
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 ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
在上面的代码中,我们首先定义了一个目标目录,然后获取了用户上传的文件的信息,我们检查了文件是否是一个实际的图片,是否已经存在,以及文件的大小和类型是否符合我们的要求,如果所有的检查都通过了,我们就尝试将文件移动到目标目录,如果文件成功上传,我们就显示一条消息告诉用户文件已经成功上传,如果有任何错误发生,我们就显示一条错误消息。
还没有评论,来说两句吧...