0

So far i can upload a picture in my folder path, but i don't have an idea how can store that in Database. I have tried a couple of examples but no luck so far. Can anyone help me?

Upload.php

<?php
//turn on php error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $name     = $_FILES['file']['name'];
    $tmpName  = $_FILES['file']['tmp_name'];
    $error    = $_FILES['file']['error'];
    $size     = $_FILES['file']['size'];
    $ext      = strtolower(pathinfo($name, PATHINFO_EXTENSION));

    switch ($error) {
        case UPLOAD_ERR_OK:
            $valid = true;
            //validate file extensions
            if ( !in_array($ext, array('jpg','jpeg','png','gif')) ) {
                $valid = false;
                $response = 'Invalid file extension.';
            }
            //validate file size
            if ( $size/1024/1024 > 2 ) {
                $valid = false;
                $response = 'File size is exceeding maximum allowed size.';
            }
            //upload file
            if ($valid) {
                $targetPath =  dirname( __FILE__ ) . DIRECTORY_SEPARATOR. 'uploads' . DIRECTORY_SEPARATOR. $name;
                move_uploaded_file($tmpName,$targetPath); 
                header( 'Location: index.php' ) ;
                exit;
            }
            break;
        case UPLOAD_ERR_INI_SIZE:
            $response = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
            break;
        case UPLOAD_ERR_PARTIAL:
            $response = 'The uploaded file was only partially uploaded.';
            break;
        case UPLOAD_ERR_NO_FILE:
            $response = 'No file was uploaded.';
            break;
        case UPLOAD_ERR_NO_TMP_DIR:
            $response = 'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.';
            break;
        case UPLOAD_ERR_CANT_WRITE:
            $response = 'Failed to write file to disk. Introduced in PHP 5.1.0.';
            break;
        default:
            $response = 'Unknown error';
        break;
    }

    echo $response;
}
?>

uploadPicture.php

<?php 
include_once("login_check.inc");
include_once("database/connection.inc");

?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>PHP File Uploader</title>

    <!-- Bootstrap core CSS -->
    <link href="boostrap/css/bootstrap.min.css" rel="stylesheet">

  </head>

  <body>

    <!-- Static navbar -->
    <div class="navbar navbar-default navbar-static-top">
      <div class="container">
        <div class="navbar-header">
          <a class="navbar-brand" href="index.php">PHP File Uploader</a>
        </div>
      </div>
    </div>


    <div class="container">

        <div class="row">
           <?php 
            //scan "uploads" folder and display them accordingly
           $folder = "uploads";
           $results = scandir('uploads');
           foreach ($results as $result) {
            if ($result === '.' or $result === '..') continue;

            if (is_file($folder . '/' . $result)) {
                echo '
                <div class="col-md-3">
                    <div class="thumbnail">
                        <img src="'.$folder . '/' . $result.'" alt="...">
                            <div class="caption">
                            <p><a href="remove.php?name='.$result.'" class="btn btn-danger btn-xs" role="button">Remove</a></p>
                        </div>
                    </div>
                </div>';
            }
           }
           ?>
        </div>

          <div class="row">
            <div class="col-lg-12">
               <form class="well" action="upload.php" method="post" enctype="multipart/form-data">
                  <div class="form-group">
                    <label for="file">Select a file to upload</label>
                    <input type="file" name="file">
                    <p class="help-block">Only jpg,jpeg,png and gif file with maximum size of 1 MB is allowed.</p>
                  </div>
                  <input type="submit" class="btn btn-lg btn-primary" value="Upload">
                </form>
            </div>
          </div>

    </div> <!-- /container -->

  </body>
</html>

And this is my database table where i want to insert the picture path

Tomi
  • 45
  • 6
  • 2
    I see no code where you are trying to store it in the database. – Jeremy Harris Nov 10 '16 at 15:31
  • 1
    Possible duplicate of [How to upload images into MySQL database using PHP code](http://stackoverflow.com/questions/17717506/how-to-upload-images-into-mysql-database-using-php-code) – David Nov 10 '16 at 15:33
  • Read the content with `file_get_contents` then store it in a BLOB (or MEDIUMBLOB) MySQL field. – laurent Nov 10 '16 at 15:35

2 Answers2

0

You can save images to the database in multiple ways. I tend to base64 encode the image and save the extension. I don't know if this is the most practical method though.

// Encoding the image
$images = file_get_cntents('image.jpg');
$encodedImage = base64_encode($image);
Peter
  • 8,776
  • 6
  • 62
  • 95
0

I would question the desire to store images in the database to begin with. Generally speaking, storing binary files in a relational database is a bit of an anti-pattern. Probably the main use case for doing this is if you need to perform a binary search against the binary contents of the file, which is a rare use case.

Outside of that, putting files in database often poses the following problems:

  • It makes it more difficult to enable proper browser-side caching of the assets.
  • It makes your application much more bandwidth intensive to serve up these files. Why make your application retrieve the file from a database before being able to then serve it up to requesting client? This doubles the bandwidth necessary to serve this file to the end user, as the application first needs to retrieve the binary and then turn around and serve up that binary to the end client. This means your application is that much slower in the perception of your end user. Oftentimes, it is better just to get the file path reference from the DB and let the end client download files directly from web-accessible directory or other storage mechanisms (a CDN for example).
  • It makes maintaining your database more problematic as number of files grows. The size of data stored in your tables can become very large very quickly, impacting the various maintenance operations one might perform against the database - backups, restores, etc.
  • You lose the ability to operate against files as one would typically expect to work with a collection of files. Things such as mass file move/copies, revision control, etc. now become things you need to do via database interface, introducing additional complexity in your application.
Mike Brant
  • 70,514
  • 10
  • 99
  • 103