1

I am trying for days now to upload images to my database and then to display them. But in my script seems to be a mistake, and I can't find it :( So now I hope someone from this community can help me in this case - that would be really great! Thanks very much! I know it is much to read, sorry.

Here is the code form insert.php:

<?php
/*Enter your password on line 29*/
error_reporting(E_ALL);
ini_set("display_errors", 1);



if(!isset($_FILES['userfile']))
{
    echo '<p>Please select a file</p>';
}
else
{
    try {
    $msg= upload();  //this will upload your image
    echo $msg;  //Message showing success or failure.
    }
    catch(Exception $e) {
    echo $e->getMessage();
    echo 'Sorry, could not upload file';
    }
}

// the upload function

function upload() {
    $host="localhost";
$user="YYYY";
$pass="XXXX";
$db="ibm_sfreund";

    $maxsize = 10000000; //set to approx 10 MB

    //check associated error code
    if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {

        //check whether file is uploaded with HTTP POST
        if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {    

            //checks size of uploaded image on server side
            if( $_FILES['userfile']['size'] < $maxsize) {  

               //checks whether uploaded file is of image type
              //if(strpos(mime_content_type($_FILES['userfile']['tmp_name']),"image")===0) {
                 $finfo = finfo_open(FILEINFO_MIME_TYPE);
                if(strpos(finfo_file($finfo, $_FILES['userfile']['tmp_name']),"image")===0) {    

                    // prepare the image for insertion
                    $imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));

                    // put the image in the db...
                    // database connection
                    $con = mysql_connect("localhost", "...", "...");
                    mysql_select_db('...',$con);

                    // our sql query
                    $id_xd = $_POST["id"];
                    $sql = "UPDATE artikel SET image='{$imgData}', name='{$_FILES['userfile']['name']}', mime='{$_FILES['userfile']['type']}' WHERE id='$id_xd';";

                    // insert the image
                    mysql_query($sql) or die("Error in Query: " . mysql_error());
                    $msg='<p>Image successfully saved in database.</p>';
                }
                else
                    $msg="<p>Uploaded file is not an image.</p>";
            }
             else {
                // if the file is not less than the maximum allowed, print an error
                $msg='<div>File exceeds the Maximum File limit</div>
                <div>Maximum File limit is '.$maxsize.' bytes</div>
                <div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
                ' bytes</div><hr />';
                }
        }
        else
            $msg="File not uploaded successfully.";

    }
    else {
        $msg= file_upload_error_message($_FILES['userfile']['error']);
    }
    return $msg;
}

// Function to return error message based on error code

function file_upload_error_message($error_code) {
    switch ($error_code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION:
            return 'File upload stopped by extension';
        default:
            return 'Unknown upload error';
    }
}

Here is the script to displaying the picture:

<?php
 // just so we know it is broken
 error_reporting(E_ALL);
 // some basic sanity checks
 if(isset($_GET['id']) && is_numeric($_GET['id'])) {
     //connect to the db
     $con = mysql_connect("localhost", "...", "...");
     mysql_select_db('...',$con);

     // get the image from the db
     $sql = "SELECT image,mime FROM artikel WHERE id=" .$_GET['id'] . ";";

     // the result of the query
     $result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
        $row = mysql_fetch_object($result);     

     /*Only to check output*/           
     $img_final = $row->image;
     echo $img_final;

     /*Only to check output*/

 }
 else {
     echo 'Please use a real id number';
 }

I don't know what the mistake is, but this is what it shows after opening the site for displaying the pic:

Deprecated: mysql_connect() [function.mysql-connect]: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /users/ibm/www/beta/loadpic.php on line 7
GIF87a^–ãÌÌÌ–––···£££œœœªªª¾¾¾ÅÅű±±,^–þÈI«½8ëÍ»ÿ`(Ždižhª®lë¾p,Ïtmßx®ï|ïÿÀ pH,ȤrÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàRëìíìåBïîûëðòëõÂ80ÏüöeÀoÀ LØnaCp)´@±âþô@ P_Ç~C~‹H`€»tÚ (@³&Mɵ³—"¿‰mÚÄ)3"ÏmÙñÌ£Ò$ÙÁt¹Ž@ލ?M®;Êk€©ì¬r£`£¯b>õPP¤Ro$eGV¢Ö\7´wLmñÌU8Ðǰ÷Æ<æÚuº5qa ¹0|xíĿЀÕá Ò¯ÑJœ دÚÊð5¥ÀZo;³^GèMÙunºˆD{»ì¿sœ'uË·juíFGœ<ÜcqÏÑa˜^¡o€ë3îh3»ö/kØ—¶v>Ê)œ„/¡ |ûÑiþSSvèuÖQ^ø7h€÷^Àù­w  R`‚ÚìC@ÒU×yÍ!È XY•¡†Ðˆž"‡Ùì3ˆuã[êç™…ÆqPl$´˜#]ª™ŸŒ0Ù¡‡8®Ÿn‚ùˆ›•An Ù!)S†Ubq4nãÓn˜‡“N• ^b &–&rùy^ {ëü׿[–šw–-Öß{Úù yœ¸¢{~àÎ q¶ÆÕ£ñºœ˜þÈhuìD ¨;‚RHh§W¹u<†:Û—§Î÷#•¦MPiÛ Çb¬œHkr¼ZsºBÈ)mÔJ›|°þVÛ±]……h‘ÁÆ£,¤Ì®­±Î"Å寤q9粚ªç›_ÛâÇ+Vy‹m¹ì°Š ‘ŒMÛl•ávËgÔáéldM8è}¼m›"†ñ‚jÛ6öÕÊ–; ¤^¥ïjëê®CœdT,YÅbC¥9:%ü¬L0^“Q¹‘\oP[PS]5­,¢;8¾ü§5#xAÐmšçεØÙëJ½vdÑŠJLÒ€ñÐ º%šMoœi°ÅeUÔZ_$jå´TªÄÏñÌÐ][WÉw‰]^Ûocü=k¿*øà„nøáˆ'®øâŒ7îøãG.ùä”WnùåN˜g®ùæœwîùç ‡.ú褗nú騧®úꬷîúë°Ç.ûì´×nûí¸ç®ûî¼÷îûïÀ/üðÄoüñÈ'¯üòÌ7ïüóÐG/ýôsD;

This is a screenshot of the mysql structure: Link to screenshot

I hope you can help me! Thanks so much!!

CodeWithCoffee
  • 1,896
  • 2
  • 14
  • 36
mm ibm
  • 43
  • 5
  • Doing `echo $img_final;` is normal for your output to be `GIF87a^–ãÌÌÌ...` – Funk Forty Niner Apr 11 '15 at 13:20
  • So what should I do? – mm ibm Apr 11 '15 at 13:22
  • Yeah I already tried this, but it doesn't work – mm ibm Apr 11 '15 at 13:24
  • @mmibm What did you try exactly? `` should come close. And you have an sql injection problem. – jeroen Apr 11 '15 at 13:27
  • @jeroen This: `echo "";` – mm ibm Apr 11 '15 at 13:29
  • Which means the browser will try to fetch `GIF87a^–ãÌÌÌ–––···£££œœœªªª¾¾¾ÅÅű±...` from the server. No, that won't work... – jeroen Apr 11 '15 at 13:30
  • 1
    You'd make your life a lot easier if you just store the image on the file-server and the path in the database. – jeroen Apr 11 '15 at 13:31
  • 1
    @jeroen Storing images on fileserver is not always the best solution. – yergo Apr 11 '15 at 13:36
  • I tryed this now. also doesnt work... How can i do this, storing the image on the file server then path in database? – mm ibm Apr 11 '15 at 13:36
  • 1
    @yergo Perhaps not always, but it is if you are storing images up to 10Mb and are using stuff like `add_slashes` on your image data. – jeroen Apr 11 '15 at 13:40
  • I would be so happy if one of u guys could help me :) – mm ibm Apr 11 '15 at 13:48
  • @mmibm If you want to store the files as images, check the manual on file uploads: http://php.net/manual/en/features.file-upload.post-method.php – jeroen Apr 11 '15 at 13:49
  • And how do i save the link automaticlly to the database then? – mm ibm Apr 11 '15 at 13:54
  • @yergo In my opinion, jeroen's proposal is right. You should not store images as blobs/raw_data on the database. You can create a `directory` inside your web-development space, and create an` md5/openssl string` as directory's name. Then in this directory you save (again) with a hash as image name. So you only have to `store to the database` two hashes, for getting the image. – Themis Beris Apr 11 '15 at 13:57
  • @yergo Structure : `/photo_uploads/md5(dir1)/md5(name)` The `Structure` makes quite hard for the site to be crawled and if you set `dir1` to have a fixed size(e.g. 30 pics/dir) then you can create directories and search through less files by knowing the dir_name on the database. – Themis Beris Apr 11 '15 at 14:03
  • @ThemisBeris how about couple of servers hidden under balance-loader sharing a lot os same static content. Even separate static server can have a performance hiccup when under 1k/rps it has to fetch everything from filesystem. Sometimes it IS performance-wise to fetch content from db, to cache it in eg. varnish. This qustion is not about best practice to serve pictures, but how to do it with provided code. – yergo Apr 11 '15 at 14:14
  • @yergo You can optimize/cache files on the web server too. And i don't think that Stackoverflow's aim is to give you working code. – Themis Beris Apr 11 '15 at 15:08

1 Answers1

0

Deprecated: mysql_connect() [function.mysql-connect]: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /users/ibm/www/beta/loadpic.php on line 7

You should rewrite your code to use PDO or mysqli. To make it working just now, try using:

 error_reporting(0);
 ini_set('display_errors', 0);

but thats not a solution, rather thing to test if its working at all. As you are able to share binary data to us, that error at the beginning is all that crushes your script.

header: Also you need to send a proper header, to let browser recognise that this is an image, not a webpage. Once you use here a GIf, you can try:

header("Content-type: " . image_type_to_mime_type(IMAGETYPE_GIF));

before sending first output. But you need to check mime type out before saving an image to db ans save it too. Then you can fetch it with binary data and send back when displaying.

addslashes is not quite necessary. Please refer to this answer and adjust your code.

Community
  • 1
  • 1
yergo
  • 4,761
  • 2
  • 19
  • 41
  • Now it shows only the letters and so on without the warning. But how can i display the image? – mm ibm Apr 11 '15 at 13:27
  • @mm: you will need a `Content-type` header as well. [Try this search](https://duckduckgo.com/?q=Content-type+header+PHP+GIF). – halfer Apr 11 '15 at 13:28
  • Isn't there any other mistake in the script that might crash everything? – mm ibm Apr 11 '15 at 13:30
  • Content-type was not working previously or is not working in current state? Plase check my update and test it out. – yergo Apr 11 '15 at 13:32
  • Ok now it says the image cannot be show cause it contains errors? – mm ibm Apr 11 '15 at 13:35