Solved

error in uploading thumbnail in mysql database

Posted on 2007-03-30
3
433 Views
Last Modified: 2013-12-13
hi,
I have an error in storing a thumbnail in mysql db ..
the code is (I have descriped my problem as a comments in the thumbnail section)  :

<?php

     require($_SERVER['DOCUMENT_ROOT'] . '\config\db_config.php');
$link = mysql_connect($db_host, $db_user, $db_password);
mysql_select_db($db_name,$link);
//Header("Content-Type: 'image/pjpeg'");
//echo $_POST['qqq'];
//echo $_FILES['images'][1]['tmp_name'];

//$date = time();
$date = date("Y-m-d");
//echo "<br>$date<br>";
$project_name = $_POST['Proj_name'];
/*if ($project_name == "")
{
echo <<< DATA
<script type=text/javascript>
window.alert("The project name should not be null or can not be duplicated please try agian!!");
</script>
DATA;
exit;
}*/
//echo "3<br>";
mysql_query("INSERT INTO `project` (`project_name`,`project_date`) VALUES ('$project_name','$date')", $link) ;
if (mysql_error())
{
$err = mysql_error();
echo <<< DATA
<script type=text/javascript>
window.alert("The project name should not be null or can not be duplicated please try agian.");
window.alert("Mysql error is : $err .");
</script>
DATA;
exit;}

//echo "4<br>";

$types = array(
      'image/gif',
      'image/pjpeg',
      'image/x-png'      
);
$errors = 0;
$count_uploads = 0;
//echo "check1";
if (isset($_POST['submit']))
{
      for ($i = 0; $i < 10; $i++)
      {
            //echo $_FILES['images']['type'][$i]; echo "<br>";
            //echo $_POST['comment'][$i]; echo "<br>";
            if (is_uploaded_file($_FILES['images']['tmp_name'][$i]))
            {
                  //echo "test1 <br>";
                  if (in_array($_FILES['images']['type'][$i], $types))
                  {
                        $base_name = 'C:/Program Files/Apache Group/tmp/' . basename($_FILES['images']['tmp_name'][$i]);
                        //echo "test2 <br>";
                        if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $base_name))
                        {
                              //echo "test3 <br>";
                              $data = mysql_escape_string(fread(fopen($base_name, 'r'), filesize($base_name)));
                              //echo "$data";
                              //insert query
                              $imageName = $project_name.'_img_name_'. basename($_FILES['images']['name'][$i]);
                              //echo "$imageName";
                              //exit;
                              $imageSize = $_FILES['images']['size'][$i];
                              $imageType = $_FILES['images']['type'][$i];
                              $comment = $_POST['comment'][$i];
                              mysql_query("
                                    INSERT INTO img_pg
                                    VALUES ('$imageName', '$project_name', '$data', '$imageSize','$imageType')
                              ", $link) or die (mysql_error());
                              //'$comment'
                                 //Header( "Content-Type: $imageType");
                                 // Header( "Content-Length: $imageSize");
                                 
                                 
                                 
//------------------------------------------------------                                
 
//----- This section of code is to create thumbnails
//----- and store it in mysql database ..
//----- I am trying to do so by getting image data from
//----- image that aleady uploaded to db (see above code)
//----- that means I am trying to get a thumbnail from original
//----- image which has been uploaded
//----- the problem is :
//----- the thumbnail in not able to be stored in mysql database  
//----- any help on it please ??


                               
                                     

                              //echo "<br>$imageType<br>";  echo "<br><br>";
                             //echo "<br>$data<br>";
                              //  echo "<br><br>";
                              $src_img = imagecreatefromstring($data);
                              //echo "$src_img";                              
                              if ($src_img !== false) {
                                   Header( "Content-Type: $imageType");
                              }
                              $old_x=imageSX($src_img);
                              $old_y=imageSY($src_img);   //echo "$old_y";
                               $new_w = 150;
                              $new_h = 150;
                              if ($old_x > $old_y) {
                                    $thumb_w=$new_w;
                                    $thumb_h=$old_y*($new_h/$old_x);
                              }
                              if ($old_x < $old_y) {
                                    $thumb_w=$old_x*($new_w/$old_y);
                                    $thumb_h=$new_h;
                              }
                              if ($old_x == $old_y) {
                                    $thumb_w=$new_w;
                                    $thumb_h=$new_h;
                              }
                              $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
                              imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

                              switch ($imageType)
                              {
                                    case "image/pjpeg":
                                           $dst_img = imagejpeg($dst_img);
                                    mysql_query("
                                    INSERT INTO thumbs
                                    VALUES ('$imageName', '$project_name', '$dst_img', '$imageSize','$imageType')
                              ", $link) or die (mysql_error());
                                          break;
                                         
                                         
                                    case "image/x-png":
                                          $dst_img = imagepng($dst_img);
                                   mysql_query("
                                    INSERT INTO thumbs
                                    VALUES ('$imageName', '$project_name', '$dst_img', '$imageSize','$imageType')
                              ", $link) or die (mysql_error());
                                          break;
                                         
                                         
                                    case "image/gif":
                                          $dst_img = imagegif($dst_img);
                                     mysql_query("
                                    INSERT INTO thumbs
                                    VALUES ('$imageName', '$project_name', '$dst_img', '$imageSize','$imageType')
                              ", $link) or die (mysql_error());
                                          break;
                                         
                                    //default:
                                         
                                         
                              }
//------ End of thumbnail code                              
                             
                              switch ($i)
                              {
                                    case 0 :
                                    //echo "check2";
                                       mysql_query("update project set img0 = '$imageName' where project_name = '$project_name'  ", $link);
                                       mysql_query("update project set comment = '$comment' where project_name = '$project_name'  ", $link);
                                       break;
                                    case 1 :
                                       mysql_query("update project set img1 = '$imageName' where project_name = '$project_name'  ", $link);
                                       mysql_query("update project set comment = '$comment' where project_name = '$project_name'  ", $link);
                                       break;
                                    case 2 :
                                       mysql_query("update project set img2 = '$imageName' where project_name = '$project_name'  ", $link);
                                       mysql_query("update project set comment = '$comment' where project_name = '$project_name'  ", $link);
                                       break;
                                    case 3 :
                                       mysql_query("update project set img3 = '$imageName' where project_name = '$project_name'  ", $link);
                                       mysql_query("update project set comment = '$comment' where project_name = '$project_name'  ", $link);
                                       break;
                                    case 4 :
                                       mysql_query("update project set img4 = '$imageName' where project_name = '$project_name'  ", $link);
                                       mysql_query("update project set comment = '$comment' where project_name = '$project_name'  ", $link);
                                       break;
                                    case 5 :
                                       mysql_query("update project set img5 = '$imageName' where project_name = '$project_name'  ", $link);
                                       mysql_query("update project set comment = '$comment' where project_name = '$project_name'  ", $link);
                                       break;
                                    case 6 :
                                       mysql_query("update project set img6 = '$imageName' where project_name = '$project_name'  ", $link);
                                       mysql_query("update project set comment = '$comment' where project_name = '$project_name'  ", $link);
                                       break;
                                    case 7 :
                                       mysql_query("update project set img7 = '$imageName' where project_name = '$project_name'  ", $link);
                                       mysql_query("update project set comment = '$comment' where project_name = '$project_name'  ", $link);
                                       break;
                                    case 8 :
                                       mysql_query("update project set img8 = '$imageName' where project_name = '$project_name'  ", $link);
                                       mysql_query("update project set comment = '$comment' where project_name = '$project_name'  ", $link);
                                       break;
                                    case 9 :
                                       mysql_query("update project set img9 = '$imageName' where project_name = '$project_name'  ", $link);
                                       mysql_query("update project set comment = '$comment' where project_name = '$project_name'  ", $link);
                                       break;
                                   
                              }
                              unlink ($base_name);
                              $count_uploads++;
                        }
                        else
                        {
                               $errors++;
                              //echo "test4 <br>";
                              //array_push($errors, "File: #$i ({$_FILES['images']['name'][$i]}) could not be uploaded.");
                        }
                  }
                  else
                  {    
                        $errors++;
                        //echo "test5 <br>";
                        //array_push($errors, "File: #$i ({$_FILES['images']['name'][$i]}) has an invalid type ({$_FILES['images']['type'][$i]}).");
                  }
            }
            else
            {    
                  $errors++;
                   //echo "test6 <br>";
                  //array_push($errors, "File: #$i ({$_FILES['images']['name'][$i]}) could not be uploaded ");
            }
      }
echo <<< DATA
<script type=text/javascript>
window.alert("The number of uploaded images are : $count_uploads and the number of unuploaded images are : $errors");
</script>
DATA;
      //echo 'Done.' . (count($errors)) ? ' - but with errors:<br /><br />' . implode("<br />\n", $errors) : '';
//echo "$ff";
}
//echo "$imageType";

 //echo "$data";  
    ?>
    <html><head ></head >
    <body><a href="add.html" >go back</a>
    </body>
    </html >


any help would be greatly appreciated ..
0
Comment
Question by:Ameerh24
3 Comments
 
LVL 15

Expert Comment

by:JakobA
ID: 18826242
Are you by any chance on a windows server ?
the   fopen($base_name, 'r')   opens the image as a txt file and it should be opened as a binary file   fopen($base_name, 'rb')

$data = mysql_escape_string(fread(fopen($base_name, 'rb'), filesize($base_name)));

Also you should NOT add escape characters to the file. with a binary read the $data variable gets to contain exactly what is in the image file and that is what we vant.
so just:

$data = fread( fopen( $base_name, 'rb' ), filesize( $base_name ) );

or better yet:
$data = file_get_contents( $base_name );  // see: http://dk2.php.net/manual/en/function.file-get-contents.php

regards JakobA

PS: I would need a VERY good reason before storing an image in my database. generally it is much easier and faster to store the imagefile as a file on the server filesystem, and then just store the name of the file in the database.
0
 

Author Comment

by:Ameerh24
ID: 18828560
hi,
I am storing an image into database because these images are too important to the company .. so I am afraid of loosing any of them by fault of deleting
What do think ??
0
 
LVL 15

Accepted Solution

by:
qz8dsw earned 500 total points
ID: 18950926
A good backup regime is what I'd recommend.
Storing it in a database does not really give you any added coverage for it being deleted.
Delete a file, delete a row from a database.
Either way the image is gone.
Security on the files themselves and a good backup regime means you should not need to store them in the database.
(I.E totally agree with JakobA)
As JakobA said the speed of access of the picture, the speed of the database and ease of accessability means using files is by far a better way to go.

If these are so important then don't create a single point of failure by putting everything in a database.
If the database gets corrupted and can't start it's all your images affected, BUT someone deletes a file, with a good backup regime to some offline media (DLT/LTO tapes, CD, DVD) means it's very easy to get back. (We use Brightstore to backup to LTO/3 carts on a daily basis, then have a weekly, you can take it to monthly, six monthly, yearly if you have the storage for it)

Terry
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now