我是php的新手。我在php中创建了一个简单的上传表单。这是我的代码。
<html><head></head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload File:
<input type="file" name="upload" /><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
<?php
include("config.php");
if(isset($_POST['submit']) )
{
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
if ($_FILES['upload']['name'] == 0 ){
echo "<br><br> New record created successfully";
}
else {
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) === TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
$con->close();
}
?>
工作正常。但是如果我按下没有附加文件的提交,它会显示错误,警告:file_get_contents():在第20行的C:\ xampp \ htdocs \ contractdb \ filetest.php中,文件名不能为空。
我希望上传文件是可选的,因为并非每个用户都有要附加的文件。我还希望用户在上传后下载文件而不删除file_get_contents($ _ FILES [&#39; upload&#39;] [&#39; tmp_name&#39;])。
我该怎么做?
答案 0 :(得分:1)
您的检查应该在调用file_get_content()
之前进行,这样就不会抛出错误,只有在文件输入不为空时才调用该函数:
if(isset($_POST['submit']) ) {
if ($_FILES['upload']['size'] != 0 ) {
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']
['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
else {
echo 'error: empty file';
}
}
答案 1 :(得分:0)
试试这个:
if (isset($_POST['submit']) & ($_FILES['upload']['name']!=''))
{
// Statement
}