我在我的webiste上做了一个注册表。我已经要求填写姓名和电子邮件(对我来说很容易,因为是文本字段(,但我如何才能要求填写国家、照片和爱好?现在,我想在添加数据库和上传到服务器之前检查空字段和文件类型。我该怎么做?谢谢
<?php
if (isset($_POST['submit'])){
if (empty($_POST["name"]) || empty($_POST["email"])) {
$emptyErr = " Required field!"; // Error which will be shown if a field is empty
$name = $_POST['name']; // I put this field to remember user entries if a field is empty
$email = $_POST['email'];
} else {
$con = mysql_connect("localhost","username","password"); // Connect to database
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("database_name",$con);
$target = "gallery/profilepictures/"; // Folder for pictures on server
$pic=(time().'_'.$_FILES['photo']['name']); // I wanna rename the pictures on server. I put time in front of original name
$hobbies = implode(", ",$_POST['hobbies']);
$hot = "INSERT INTO table_name (name,email,country,hobbies,default_img)
VALUES ('$_POST[name]','$_POST[email]','$_POST[country]','$hobbies','$pic')";
mysql_query($hot,$con);
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target . $pic))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Oops! Error! Try again!";
}
}
}
?>
<form enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<table style="width:700px">
<tr><td>Name:</td><td><input type="edit" name="name" size="50" value="<? echo $name?>"><?php if (empty($_POST["name"])) {echo $emptyErr;}?></td></tr>
<tr><td>Email:</td><td><input type="edit" name="email" size="50" value="<? echo $email?>"><?php if (empty($_POST["email"])) {echo $emptyErr;}?></td></tr>
<tr><td>Country:</td><td><select name="country"><option value="USA" selected>USA</option>
<option value="UK">UK</option>
<option value="UAE">UAE</option>
</select></td></tr>
<tr><td>Photo:</td><td><input type="file" name="photo"></td></tr>
<tr><td>Hobbies:</td><td><input type="checkbox" name="hobbies[]" value="football">football
<input type="checkbox" name="hobbies[]" value="tennis">tennis
<input type="checkbox" name="hobbies[]" value="carting">carting
<input type="checkbox" name="hobbies[]" value="online games">online games
</td></tr>
<tr><td colspan=2><input type="submit" name="submit" class="btn btn-custom2 radius fr" value="Adăugați unitatea de cazare »"></td></tr>
<tr><td> </td></tr>
</table>
</form>
为了检查文件大小和类型,可以使用类似的
if($_FILES["imagefile"]["size"] >= 2120000) {
echo "Max size exceeded";
die();
}else {
$imageData = @getimagesize($_FILES["imagefile"]["tmp_name"]);
if($imageData === FALSE || !($imageData[2] == IMAGETYPE_GIF || $imageData[2] == IMAGETYPE_JPEG || $imageData[2] == IMAGETYPE_PNG)) {
echo "Invalid file type";
die();
}
}
如果您只需要服务器端检查空字段,则可以使用
if(!empty($PostedData))
//allow
else
echo "Field(s) missing.";
die();