2

I am getting these errors in PHP:

Warning: file_get_contents(): Filename cannot be empty in C:\xampp\htdocs\myDocs\mainProject\upload_page.php on line 97

and

Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\myDocs\mainProject\upload_page.php on line 99 That is not an image.

This is my code:

<div class = "splash container-fluid">
          <form action = "upload_page.php" method = "POST" enctype="multipart/form-data">
         File:
         <input type= "file" name = "image"> <input type= "submit" value = "Upload">

      </form>
         </div>

          <?php
          //connect to database

          mysql_connect("localhost", "root", "") or die(my_sql_error());          
          mysql_select_db("natureall")or die(my_sql_error());        


          //file properties
          $file = $_FILES['image']['tmp_name'];

          if (!isset($file))
          echo "Please select an image";

           else{
              addslashes($image =  file_get_contents($_FILES['image']['tmp_name']));
                $image_name = ($_FILES['image']['name']);
               $image_size = getimagesize($_FILES['image']['tmp_name']);

           }

           if($image_size == FALSE)
               echo "That is not an image";
           else{
              if(! $insert = mysql_query("INSERT INTO photos VALUES ('', 'image_name', '', 'image')"))
                  echo "Problem uploading image";
               else{
                   $lastid = mysql_insert_id();
                   echo "Image uploaded.<p/>Your image:<p/><img src = get.php?id=$lastid";
               }
           }



          ?>

Also the

if (!isset($file))
          echo "Please select an image";

part does not generate the echo before the image is selected, it should shouldn't it. How could this be set before the image is browsed for?

Thanks for all your help everyone! I'm getting there. There are new records in the db but the image name is not travelling only the text 'image_name' and the blob is only 5b, so that's not right. I have this db being added to from an android app where the image is stored in a dir, but I haven't worked out how to do it from a webpage yet. Here is my code as it stands now tanks to the all the help, especially @Martin:

<?php
          //connect to database

          mysql_connect("localhost", "root", "") or die(my_sql_error());          
          mysql_select_db("natureall")or die(my_sql_error());        


          //file properties   


         if($_FILES['image']['error'] == 1){
    echo "The uploaded file exceeds the upload_max_filesize directive in php.ini.";
}
        elseif ($_FILES['image']['error'] == 2){
    echo "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
}
        elseif ($_FILES['image']['error'] == 3){
    echo "The uploaded file was only partially uploaded.";
}
         elseif ($_FILES['image']['error'] == 4){
    echo " No file was uploaded.";
}
        elseif ($_FILES['image']['error'] == 5){
    echo " Don't know this one.";
}
        elseif ($_FILES['image']['error'] == 6){
    echo " Missing a temporary folder. Introduced in PHP 5.0.3.";
}
        elseif ($_FILES['image']['error'] == 7){
    echo " Failed to write file to disk. Introduced in PHP 5.1.0. ";
}
         elseif ($_FILES['image']['error'] == 8){
    echo "  A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.  ";
}

else {
    //no error so uploaded something, 
    // therefore $_FILES['image']['tmp_name'] is a valid file.
   $image =  addslashes(file_get_contents($_FILES['image']['tmp_name']));


                $image_name = ($_FILES['image']['name']);

               $image_size = getimagesize($_FILES['image']['tmp_name']);

           }

           if($image_size == FALSE){
               echo "That is not an image";
           }
           else{
              if(! $insert = mysql_query("INSERT INTO photos VALUES ('', 'image_name', '', 'image')")){
                  echo "Problem uploading image";

              }
               else{
                   $lastid = mysql_insert_id();{
                   echo "Image uploaded.<p/>Your image:<p/><img src = get.php?id=$lastid";

                   }
               }
           }


          ?>
halfer
  • 19,824
  • 17
  • 99
  • 186

4 Answers4

1

Problem is your: $_FILES['image']['tmp_name']
You have to check that the array actually exist.

//file properties
if(isset($_FILES['image']['tmp_name']))
{
$file = $_FILES['image']['tmp_name'];
...

and then call

file_get_contents($file)

This should then give you your file

DerCommodore
  • 88
  • 1
  • 10
1

Many thanks to all who helped me especially @Martin and W3 Schools. After MANY hours of banging my head off a table this is what my solution looks like. It isn't displaying anything yet but it IS uploading an image to a dir and entering details into a table called photos. Using mysqli @Martin :-).

<?php
$target_dir = "C:/xampp/htdocs/myDocs/mainProject/res/images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = 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"] . "."."<br>";
        $uploadOk = 1;
    } else {
        echo "File is not an image."."<br>";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists."."<br>";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 4000000) {
    echo "Sorry, your file is too large."."<br>";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "PNG" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != "JPEG" && $imageFileType != "JPG") {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."."<br>";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded."."<br>";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."."<br>";
    } else {
        echo "Sorry, there was an error uploading your file."."<br>";
    }
}

if($uploadOk >0){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "natureall";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully"."<br>";

        $name = basename( $_FILES["fileToUpload"]["name"]);
        $path = $target_file;




$sql = ("INSERT INTO photos (name, path) VALUES('$name', '$path')");


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully"."<br>";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}


mysqli_close($conn); 
echo "Connection closed"."<br>";
    }

else{
    echo "Problem with image upload, entry to database not made."."<br>";
}


?>
0

Try it like this:

<?php
      //connect to database

      mysql_connect("localhost", "root", "") or die(my_sql_error());          
      mysql_select_db("natureall")or die(my_sql_error());        


      //file properties
      if (!isset($_FILES['image'])) {
          echo "Please select an image";
      } else {
            $file = $_FILES['image']['tmp_name'];
            $image = addslashes(file_get_contents($file));
            $image_name = ($_FILES['image']['name']);
           $image_size = getimagesize($_FILES['image']['tmp_name']);
           if ($image_size === FALSE) {
                 echo "Not an image";
           } else {
                 if(! $insert = mysql_query("INSERT INTO photos VALUES ('', 'image_name', '', 'image')"))
              echo "Problem uploading image";
           else{
               $lastid = mysql_insert_id();
               echo "Image uploaded.<p/>Your image:<p/><img src = get.php?id=$lastid";
           }
       }
       }
Janno
  • 542
  • 4
  • 15
  • This answer is not useful and fails to correct numerous important mstakes as well as fails to explain the corrections, if any, that you have applied to the OP code . – Martin Aug 23 '16 at 12:11
0
//file properties
      $file = $_FILES['image']['tmp_name'];

     if (!isset($file))
      echo "Please select an image";

No no no no no.

What you are doing here is setting $file to some value and then asking if it is set. even if the upload fails, you're setting to something.

What you should be doing is properly checking for PHP upload errors.

Thus:

if($_FILES['image']['error'] == 4){
    echo "File is empty";
}
elseif ($_FILES['image']['error'] !== 0){
    echo "Some other error";
}
else {
    //no error so uploaded something, 
    // therefore $_FILES['image']['tmp_name'] is a valid file.
   $image =  file_get_contents($_FILES['image']['tmp_name']);
}

Some other issues you have

          addslashes($image =  file_get_contents($_FILES[]...));
  • addslashes($image = file_get_contents(...) You are here unclosing your addslashes. You forgot the closing bracket and added an extra one to the file_get_cotents. A type, basically.

  • Referencing the same line; you are setting the addslashes on the wrong side of the =. You have this all jumbled up and while not recommended, the correct syntax is:

      $image = addslashes(file_get_content($_FILES['image']['tmp_name']))
    
  • Are you aware that above you are adding slashes to the data content of the file, rather than the file name string? This is almost certainly wrong and is certainly very bad practise.

  • You are using a DEPRECATED database connection suite, and this is extremely dangerous and should be updated immediatey. Read more here.

  • It is good practise for logic and clarity to always wrap your if statements in curly brackets. One line statements without curly brackets followed by multi-line else statements is just asking for code mistakes to be made.

  • You seem overall to be mixing yourself up between the data filename string and the data file contents.
  • Why are you saving the file data to the database? That's very inefficient, surly easier to simply save the file name (as you've done) and file saved location address (~URL) and store the file in this directory on your server.

Some file upload very good reading:

PHP file upload manual guide and How can i get the content of uploaded file in php?

EDIT: More info Help

So you've got some data being saved to your DB but the image name isnot being saved correctly. the best way of fixing this is really to set your own image name, for example $image_name=date("ymdhis"). This is because different Operating Systems have different ways of encoding file paths and file names, so if your imagehas the name "image_101 oh yeah.jpg" this can cause issues on other file systems that don't recognise spaces, for example.

There can also be issues with file systems if the image name is to long (for example longer than 64 characters on some systems.

A good solution is, as stated above, to set your own name, or alternatively, to clean the name that is given:

$image_name = preg_replace("/[^0-9a-z.]/i","",$_FILES['image']['name']);
//This means that $image_name can only contain dot, a-z or 0-9 (case insensitive) basic ascii characters. 
//meaning this new name will be compatible with all OS.

Another important aspect is to use PHP Error Logging to correctly display warnings and errors that can help you debug your code.

Further research would be needed in case you're trying to save invalid data types to MySQL column types, such as saving VARCHAR data to an INT column, etc.

AND YOU NEED TO REALISE MYSQL_ IS DEPRECATED AND SHOULD NOT BE USED!!!

Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132
  • Thank you Martin, I used the error finding and found that I was getting this error: 'The uploaded file exceeds the upload_max_filesize directive in php.ini' I selected a smaller image and the process seemed to work in as far as I got another entry into the database table. The problem is that the field where the image name should appear is only showing the text 'Image_name' and the BLOB is only 5 bytes. As far as the php.ini file goes, is this an internal file within php.myadmin because I have not created that file on my side. – Javaiskillingme Aug 23 '16 at 13:04
  • phpini is one of PHPs core system files. This error is easy to fix with a quick search of SO or a search engine. – Martin Aug 23 '16 at 13:10
  • Thank you Martin, edited the php.ini file and the process worked in as much as it didn't cause that error and created another record. However, the image name and blob are still not correct. I am storing the image in a directory when I am doing the same job from my android app which I am trying to develop in conjunction with the webpage. It is working using postman but I am having difficulty getting aroung the new runtime permissions. With the webpage however I am not using java (obviously). I would love to feed the files into the db using the same process but I will need to figure it out . – Javaiskillingme Aug 23 '16 at 13:33
  • @Javaiskillingme have you done everything suggested in my answer? – Martin Aug 23 '16 at 13:50
  • If you are storing the image file in a directory then you don't need to use `file_get_contents` or database `blob` fields at all. – Martin Aug 23 '16 at 13:50
  • thank you, this is my code now, sorry too long. Ill place it in the original question. – Javaiskillingme Aug 23 '16 at 14:52
  • Thanks Martin, deprecated, I hear ya! – Javaiskillingme Aug 23 '16 at 17:00