此代码将文件传输到指定的文件夹和db表,但是当我在浏览器上启动/打开/运行页面时,它会自动向db表发送内容并且文件名字段为空。我没有甚至点击/上传任何东西。我不知道我是否正确解释了。问题是当我打开页面时,我检查了数据库表行并且创建了一个空行.id增加了btw,文件名字段为空。(不上传什么都没有。)代码有什么问题?
<?php
if(isset($_FILES['filename'])){
$errors= array();
$file_name = $_FILES['filename']['name'];
$file_size =$_FILES['filename']['size'];
$file_tmp =$_FILES['filename']['tmp_name'];
$file_type=$_FILES['filename']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"uploads/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "admin";
$filename = false;
if(isset($_FILES['filename'])){
$filename = $_FILES['filename']['name'];
}
// Create connection
mysql_connect($servername, $username, $password) or die ('MySQL Not found // Could Not Connect.');
mysql_select_db("admin") or die(mysql_error()) ;
mysql_query("INSERT INTO upload_test (fileName)
VALUES ('$filename')") ;
?>
我的表格:
<form name="form" method="POST" enctype="multipart/form-data" >
<input name="filename" type="file" id="filename" />
<input name="submit" type="submit" id="submit"/>
</form>
答案 0 :(得分:0)
那是因为你总是在执行INSERT语句。您只想在上传后插入记录。
if(isset($_FILES['filename'])){
$errors = array();
$file_name = $_FILES['filename']['name'];
$file_size =$_FILES['filename']['size'];
$file_tmp =$_FILES['filename']['tmp_name'];
$file_type=$_FILES['filename']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
// if there are no errors...
if (empty($errors)==true) {
// upload the file...
move_uploaded_file($file_tmp,"uploads/".$file_name);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "admin";
// and create a new record in the database
mysql_connect($servername, $username, $password) or die ('MySQL Not found // Could Not Connect.');
mysql_select_db("admin") or die(mysql_error()) ;
mysql_query("INSERT INTO upload_test (fileName) VALUES ('$file_name')") ;
echo "Success";
}else{
print_r($errors);
}
}
另一方面,获取文件扩展名的更简单方法是使用pathinfo()
$file_ext = pathinfo($_FILES['filename']['name'], PATHINFO_EXTENSION);