在mysql数据库中存储图像并不起作用。现在怎么办?

时间:2015-04-11 13:18:31

标签: php mysql file-upload

我现在正在尝试将图像上传到我的数据库,然后显示它们。但在我的剧本中似乎是一个错误,我找不到它:(所以现在我希望来自这个社区的人可以在这种情况下帮助我 - 这真的很棒!非常感谢!我知道这对我来说很重要读,对不起。

以下是代码表单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';
    }
}

以下是显示图片的脚本:

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

我不知道这是什么错误,但这是在打开显示图片的网站后显示的内容:

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;

这是mysql结构的截图: Link to screenshot

我希望你能帮助我! 非常感谢!!

1 个答案:

答案 0 :(得分:0)

  

不推荐使用:mysql_connect()[function.mysql-connect]:不推荐使用mysql扩展,将来会删除它:在第7行的/users/ibm/www/beta/loadpic.php中使用mysqli或PDO

您应该重写代码以使用PDO或mysqli。要使其正常工作,请尝试使用:

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

但这不是解决方案,而是测试它是否正常工作。由于您可以向我们共享二进制数据,因此开头的错误就是破坏您的脚本。

标题 您还需要发送正确的标题,让浏览器识别出这是一个图像,而不是网页。一旦你在这里使用了一个GIf,你可以尝试:

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

发送第一个输出之前。但是你需要在将图像保存到db之前检查mime类型,并保存它。然后你可以用二进制数据获取它并在显示时发回。

addslashes 不是必需的。请参阅this回答并调整您的代码。