0

I am trying to store an image file in a psql database table. The table 'images' has two fields, 'id' of type integer & 'image' of type bytea.

I tried to modify image saving code from a tutorial on web. But my code is raising error & warning.

Here is the error message:

Notice: Undefined index: image in C:\xampp\htdocs\maps\un.php on line 48

Warning: fopen(): Filename cannot be empty in C:\xampp\htdocs\maps\un.php on line 50
cannot read image 

These errors are on lines inside if(isset($_POST["submit1"])){ block

How to correct these errors ?

Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Image Upload</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

</head>
<body>
<?php
require("connection.php");
?>

<div class="container-fluid">
          <h1 align="center">Test Form </h1>

   <form action="" method="post" class="needs-validation" novalidate enctype="multipart/form-data"> 
    <h2> Field </h2>
  <div class="form-row">
    <div class="col-md-4 mb-3">
      <label for="validationCustom01">Field ID</label>
      <input type="number" class="form-control" name="field_id" id="field_id" placeholder="insert field id" value="" required>
      <div class="valid-feedback">
        0
      </div>
    </div>
      <div class="col-md-4 mb-3">
      <label for="validationCustom02">IMG</label>
      <input type="file" class="form-control" name="image" id="image" placeholder="insert image" value="" required>
      <div class="valid-feedback">

      </div>
    </div>      
   </div>

  <button class="btn btn-primary" name="submit1" type="submit">Insert Image</button>
</form>


    <?php

          if(isset($_POST["submit1"])){

              $file_name = $_POST["image"];

              $img = fopen($file_name, 'r') or die("cannot read image\n");
              $data = fread($img, filesize($file_name));

              $es_data = pg_escape_bytea($data);
              fclose($img);   


            try {

                $sql = "INSERT INTO images (field_id, image)
                VALUES ('".$_POST["field_id"]."','.$es_data.')";
                 // echo "<meta http-equiv='refresh' content='0'>";
                if ($conn->query($sql)) {
                     echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
                          }
                          else{
                            echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
                      }
                            $dbh = null;
                    }
                        catch(PDOException $e)
                    {
                        echo $e->getMessage();
                        }
                    }   

                    //$conn = null;

                    ?>

    </div>    
</body>
</html> 
3
  • Is there a reason why you wanna store the whole image in a db? Why not only store the path? Commented Nov 6, 2018 at 9:23
  • @Lithilion: Because the images are of not high resolution & not in high quantity. Commented Nov 6, 2018 at 9:41
  • But storing images in a db really slows it down... Commented Nov 6, 2018 at 9:44

1 Answer 1

1

Files are stored in the $_FILES superglobal. There is no image in the $_POST.
The filename will be $_FILES["image"]["tmp_name"]. This is the path where php temporarily uploads it and you can handle it.

Ref: https://secure.php.net/manual/en/reserved.variables.files.php
https://secure.php.net/manual/en/features.file-upload.php

PS: Your code is vulnerable to SQL-Injection. Please use Prepared Statements or PDO.

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you: Undefined index: image error gone but this warning exists: Warning: fopen() expects parameter 1 to be a valid path, array given in C:\xampp\htdocs\maps\un.php on line 50 cannot read image. Line 50 is: $data = fread($img, filesize($file_name));
Are you sure its the right line? It says something about fopen, but its not in the line you showed
Sorry; $img = fopen($file_name, 'r') or die("cannot read image\n");
can you var_dump($file_name)?
Execute it before line 50 and comment the lines below.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.