MechaMetalHead
MechaMetalHead

Reputation: 51

file_get_contents(): Filename cannot be empty (uploading files to be optional)

I am new to php. I made a simple upload form in php. This is my code.

<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(); 
}   

?>

It works fine. But if I press the submit with no files attached, it displays the error, Warning: file_get_contents(): Filename cannot be empty in C:\xampp\htdocs\contractdb\filetest.php on line 20 .

I want uploading files to be optional because not every user has the files to attach. I also want the user to download the files after uploading without removing file_get_contents($_FILES['upload']['tmp_name']).

How do I do this?

Upvotes: 0

Views: 10145

Answers (2)

スージン
スージン

Reputation: 153

Try this:

if (isset($_POST['submit']) & ($_FILES['upload']['name']!=''))
{
    // Statement
}

Upvotes: 0

Amr Aly
Amr Aly

Reputation: 3905

Your check should take in place before calling file_get_content() so it does not throw an error and you only call the function if file input is not empty:

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';
 }
}

Upvotes: 2

Related Questions