[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 474
  • Last Modified:

Storing Images in PHP and Mysqli NOT Mysql

I am trying to understand the logic behind storing a image into a file and uploading the file..
Iam going through a TUTORIAL but i don't understand the logic:::
First File:

<?php
function myUpload() {
     print "The myUpload function has been called!<br>";
     print "The temporary file name is ".$_FILES['aFile']['tmp_name'];
     if (is_uploaded_file($_FILES['aFile']['tmp_name'])) {
             $fileName = $_FILES['aFile']['tmp_name'];
             print "<br>The file $fileName was uploaded successfuly";
             $realName = $_FILES['aFile']['name'];
             print "<br>The real file name is $realName";
             print "<br>Copying file [$realName] to the uploads-directory";

move_uploaded_file($_FILES['aFile']['name'],
"/home/students/ics325sp06/ics325sp0604/public_html/uploads/".
$realName);
     }
     else {
print"<br>Possible a file upload attack:".
$_FILES['aFile']['name'].".";
     }
}
?>
<html>
<body>
<?php
// Check to see if the upload button has been pressed
if ($_REQUEST['task'] == "uploadfile") {
        myUpload();     // call the function myUpload()
}
?>
<form enctype="multipart/form-data"  method="POST"
action="loadfile.php?task=uploadfile">
File Name: <INPUT TYPE="FILE" NAME="aFile" SIZE="35"><br>
<input type="hidden" name="MAX_FILE_SIZE" value="2000000"><br>
<input type="submit" value="Upload" name="B1">
Please wait for confirmation
</form>
<a href=loadfile.php>Clean screen!</a>
</body>
</html>    
   

The form comes up good but my question is what file shall i be uploading:::
a regular file or image because when i upload an image::::::????????That is my biggie....
Here is what i get::::

The myUpload function has been called!
The temporary file name is /tmp/php4IjY8n
The file /tmp/php4IjY8n was uploaded successfuly
The real file name is 4.jpg
Copying file [4.jpg] to the uploads-directory


And there is second file that asks for an upload....code omitted because of length





0
miloudi
Asked:
miloudi
  • 10
  • 7
1 Solution
 
AndyAelbrechtCommented:
File Name: <INPUT TYPE="FILE" NAME="aFile" SIZE="35">

that is the file you shall be uploading (this input type gives u an inputbox with a button; click the button and an open file dialog pops up, where you can select the file to upload). this file will be known as "aFile" on the receiving end of the script.
all uploaded files are stored in the $_FILES array. if you put a print_r($_FILES) in the myUpload function, you'll see what i mean. $_FILES['aFile']['tmp_name'] gives us the temporary filename the uploaded file has been given, $_FILES['aFile']['name'] is the original filename of the uploaded file.

move_uploaded_file($_FILES['aFile']['name'],"/home/students/ics325sp06/ics325sp0604/public_html/uploads/".$realName);
this last function moves the uploaded file (function name says it all ? ;-)) to the directory specified by you; $realName has been set to $_FILES['aFile']['name'], so you output will be (in your example) 4.jpg again, the file you uploaded in the first place.

basically, when you upload a file (with <form enctype="multipart/form-data"  method="POST">), your file gets uploaded to a temporary location (hence the $_FILES['varname']['tmp_name'], because that's the only place the webserver knows for sure it can write files. After you check if this file is indeed the uploaded file, you move it to where you want it to be.


judging by the code, you can upload *any* file with this script.
0
 
waygoodCommented:
move_uploaded_file($_FILES['aFile']['name],"/home/students/ics325sp06/ics325sp0604/public_html/uploads/".$realName);

should be using $_FILES['aFile']['tmp_name'] as this is what the file is called on the server
0
 
miloudiAuthor Commented:
Ok here is what i did,

I found out a tutorial...
setup a form with upload button/browse and here is the upload fie:::

//connect to the DB
...
$image_caption = $_POST['image_caption'];
$image_username = $_POST['image_username'];
$image_tempname = $_FILES['image_filename']['name'];
$today = date("y-m-d");

//upload image and check image type
$ImageDir = "/home/students/ics325sp06/ics325sp0604/public_html/project4/uploads/";
$ImageName = $imageDir . $image_tempname;

if (move_uploaded_file($_FILES['image_filename']['tmp_name'],
                  $ImageName)) {

//get info about the pic

list($width, $height, $type, $attr) = getImageSize($ImageName);

switch ($type) {
      case 1:
            $ext = ".gif";
            break;
      
      case 2:
            $ext = ".jpg";
            break;
      
      case 3:
            $ext = ".png";
            break;
            default:
            echo "Sorry, but the file uploaded was not a GIF, JPG, or PNG file";
}

//insert into table

$insert = "INSERT INTO images
      (image_caption, image_username, image_date)
      VALUES
      ('$image_caption', '$image_username', '$today')";

$insertresults = $connect->query($insert);

$lastpicid = mysqli_insert_id($connect);

$newfilename = $ImageDir . $lastpicid . $ext;

rename($ImageName, $newfilename);


}

?>
...i understand the logic and it looks beautiful, however i get the following::::

Warning: move_uploaded_file(pic_morocco2.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /home/students/ics325sp06/ics325sp0604/public_html/project4/check_image.php on line 18

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpzmE7rx' to 'pic_morocco2.jpg' in /home/students/ics325sp06/ics325sp0604/public_html/project4/check_image.php on line 18

Here is the pic

missing pic...


the permission is 777 on the uploads dircetory and also on the two files(form and upload)...
any suggestions...
i tried # pics...

Thank you guys.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
AndyAelbrechtCommented:
if you are certain about the permissions on the upload directory, what about the permissions on the /tmp directory ?
has the file actually been uploaded ?
0
 
miloudiAuthor Commented:
that is a good question.
The only access i have is my home directory...
Do you know how to check it on as UNIX machine??
0
 
AndyAelbrechtCommented:
ls -l / (search for the permissions on /tmp)
or
ls -al /tmp (search for the permissions on .)
or
touch /tmp/test.file (see if it gives an error)

0
 
miloudiAuthor Commented:


I sent a question to the teacher and he will let me know about that directory.
Thanks for pointing that out AndyAelbrecht...
 I appreciate the comment
0
 
miloudiAuthor Commented:
Hello AndyAlbrecht,

I reset the code to a different one and i was able to upload the images to the DB and use them in the file however the problem that i have now that i get four pictures for each item::::

Here how it looks:

http://cs.metrostate.edu/~ics325sp0604/project4/cbashop.php

and here is the part of the code:

//show only Name, Price and Image
while ($row = mysqli_fetch_array($results)) {
      extract($row);
      $sql = "SELECT filename FROM names";
      $rs = mysqli_query($connect, $sql);
            while($row = mysqli_fetch_array($rs)){
                  echo "<tr><td align=\"center\">";
                  echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
                   echo "<a href=uploads/".$row["filename"] .
                  " border=0><img src=uploads/".$row["filename"] .
                  " width=100 height=80 /></a><p />";
                        
                  echo "<td>";      
                  echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
                  echo $products_name;
                  echo "</td></a>";
                  echo "<td align=\"right\">";
                  echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
                  echo "$" . $products_price;
                  echo "</a></td></tr>";

            
            }
}


?>


and there is only four pics in the uploads folder....
Any final thoughts...




0
 
AndyAelbrechtCommented:
ok, here's the thing:

first you select all the stuff in the first table and you want to run thru it:

//show only Name, Price and Image
while ($row = mysqli_fetch_array($results)) {

that's already correct
BUT then you want to show the picture associated with THIS product, but your sql statement is:
$sql = "SELECT filename FROM names";
whilst is should probably be "SELECT filename FROM names WHERE id = $id";

this $id variable comes from your first $row; i don't know what is in there, but you should have a column with the ID of this certain product, and in your "names" table, you need a link to this id aswell.

i hope you know what i mean ? if not, don't hesitate to ask me !

cheers
Andy
0
 
miloudiAuthor Commented:


Andy,

Here is what i did:

names is the DB table.

+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| description | varchar(50)  | YES  |     | NULL    |                |
| filename    | varchar(100) | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

the code is the following:

$sql = "SELECT filename FROM names";
$rs = $connect->query($sql);
while ($row = mysqli_fetch_array($rs)) {
      extract($row);
      
            while($row1 = mysqli_fetch_array($results)) {
                  extract($row1);
                  echo "<tr><td align=\"center\">";
                  echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
                   echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">
                  <img src=uploads/".$row["filename"] .
                  " width=100 height=80 /></a><p />";
                        
                  echo "<td>";      
                  echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
                  echo $products_name;
                  echo "</td></a>";
                  echo "<td align=\"right\">";
                  echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
                  echo "$" . $products_price;
                  echo "</a></td></tr>";
            }
            
            
}


i am able to view only one picture :
http://cs.metrostate.edu/~ics325sp0604/project4/cbashop.php
when i add:
SELECT filename FROM names WHERE id = $id";
  It gives me the error
   Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given

Any thoughts.....
Thanks
 




0
 
AndyAelbrechtCommented:
hey miloudi,

you are doing 2 sql statements (as you have $row and $row1)
could you please elaborate on the contents of the 1st query and database ?

i'll be able to help you out alot faster this way ;-)
0
 
miloudiAuthor Commented:
Sorry Andy,

Here is the entire for that page:

<?php
//connect to the DB

$connect = new mysqli("localhost","ics325sp0604", "13855", "ics325sp0604" );
$query = "select * from products";
$results = $connect->query($query);

?>

<html>
<head>
<title>Shopping Cart Experience</title>
<style type="text/css">
      @import url(style.css);
</style>
</head>

<body>

<div align="center">
Thanks for visiting my site! Please see the list of awesome
products below, and click on the link for more information:
<br><br>
<table width="300">

<?php

//show only Name, Price and Image
$sql = "SELECT filename FROM names";
$rs = $connect->query($sql);
while ($row = mysqli_fetch_array($rs)) {
      extract($row);
      
            while($row1 = mysqli_fetch_array($results)) {
                  extract($row1);
                  echo "<tr><td align=\"center\">";
                  echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
                   echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">
                  <img src=uploads/".$row["filename"] .
                  " width=100 height=80 /></a><p />";
                        
                  echo "<td>";      
                  echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
                  echo $products_name;
                  echo "</td></a>";
                  echo "<td align=\"right\">";
                  echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
                  echo "$" . $products_price;
                  echo "</a></td></tr>";
            }
            
            
}


?>

</table>
</div>
</body>
</html>
 and the products table has the following:
  +--------------------+--------------+------+-----+---------+-------+
| Field              | Type         | Null | Key | Default | Extra |
+--------------------+--------------+------+-----+---------+-------+
| products_prodnum   | char(5)      | NO   | PRI |         |       |
| products_name      | varchar(20)  | NO   |     |         |       |
| products_proddsec  | text         | NO   |     |         |       |
| products_price     | decimal(6,2) | NO   |     |         |       |
| products_dateadded | date         | NO   |     |         |       |
+--------------------+--------------+------+-----+---------+-------+
Thanks for the help again.



0
 
AndyAelbrechtCommented:
ok, now it's all clear ;-)
you basically switches your switch statements, this is how it should look:

//show only Name, Price and Image
while ($row = mysqli_fetch_array($results)) {
     extract($row);
     $sql = "SELECT filename FROM names WHERE id = $products_prodnum";
     $rs = $connect->query($sql);
     
          while($row1 = mysqli_fetch_array($rs)) {
               extract($row1);
               echo "<tr><td align=\"center\">";
                echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">
               <img src=uploads/".$row["filename"] .
               " width=100 height=80 /></a><p />";
                   
               echo "<td>";    
               echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
               echo $products_name;
               echo "</td></a>";
               echo "<td align=\"right\">";
               echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
               echo "$" . $products_price;
               echo "</a></td></tr>";
          }
         
         
}

i also cleaned up the code in the loop a bit and ofcourse added the id parameter in the 2nd query. I moved this second query inside the first loop again, as $products_prodnum will (and should) have another number for every product!

your products_prodnum in the first table should be the same as the id in the 2nd table. if this is not the case, you need to make a link. i hope you understand that if you don't have a "link" between two tables (relation) then you can not get the appropriate data.

ps: at the moment, i'm actually guessing you don't have something that links these two together. I say this because you (judging by the fact that you have a second loop) seem to have multiple pictures per product.
if this is not the case (if you don't have multiple pictures per product), you can drop the 2nd while loop and just replace the 2nd while with $row1 = mysqli_fetch_array($rs);

this should work for you now, i hope :-)
0
 
miloudiAuthor Commented:
the tables are not linked,

I just pasted your code and it doesn';t return anything. Does not select no images nor pics..
If i don't use the while statement i get an error about the mysqli_fetch_array(missing statement).
I honestly don't know what to do next but i wil keep digging...
Thanks for the help.
0
 
AndyAelbrechtCommented:
ok, when uploading pictures, you have to select what product they belong to, otherwise (what you were originally doing) you will just display *all* the pictures for every product you have.

your images(files) table needs to look like this:

id
filename
description (you are not using this though)
prod_id (<<<< here you have to put the id of the product this picture you just uploaded belongs to)

to accomplish this, in your upload form, make a selectbox and fill it with product ids like this:
<select name="prod_id">
<?
$sql = "SELECT * from products ORDER BY products_name ASC";
$rs = mysqli_query($sql);
while ($row = mysqli_fetch_array($rs)){
  echo "<option value=\"".$row["products_prodnum"]."\">".$row["products_name"]."\n";
}
?>
</select>

in the receiving end of the upload script, you have a sql statement, you should adjust this to:
$sql = "INSERT INTO files (filename, description, prod_id) VALUES (\"$filename\", \"$description\", ".$_POST["prod_id"].");";

now, you have a link between the two tables.

your new output script should then look like this:

$connect = new mysqli("localhost","ics325sp0604", "13855", "ics325sp0604" );
$query = "select * from products";
$results = $connect->query($query);
//show only Name, Price and Image
while ($row = mysqli_fetch_array($results)) {
     extract($row);
     $sql = "SELECT filename FROM names WHERE prod_id = $products_prodnum";
     $rs = $connect->query($sql);
     
          $row1 = mysqli_fetch_array($rs);
               extract($row1);
               echo "<tr><td align=\"center\">";
                echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\"><img src=uploads/".$row["filename"] ." width=100 height=80 /></a><p />";
                   
               echo "<td>";    
               echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
               echo $products_name;
               echo "</td></a>";
               echo "<td align=\"right\">";
               echo "<a href=\"getprod.php?prodid=" . $products_prodnum . "\">";
               echo "$" . $products_price;
               echo "</a></td></tr>";
}
0
 
miloudiAuthor Commented:
i iwll do that Andy thanks...
0
 
miloudiAuthor Commented:
Hello Andy,

I have this question which is # than the imaging problem::::
I have an if statement that deosn't work very well:

Could you tell me what i am doing wrong ?
 <?php
session_start();


if(isset($_POST['username']) && isset($_POST['password'])){

      //if the user has just tried to login

      $username = trim ($_POST['username']);
      $password = trim ($_POST['password']);

      $dbcn = new mysqli             
                  ("localhost","ics325sp0604", "13855",  "ics325sp0604" );
      if(mysqli_connect_errno())      {
                    echo "<p>Error creating database connection: </p>";
                exit;
        }

      $sql = "SELECT username, password FROM user_info ";
      $sql = $sql . "WHERE username='$username' AND password=sha1('$password');";

      $result = $dbcn->query( $sql );
        if(!$result){
                 echo( "<p>Unable to query database at this time.</p>" );
                 exit();
        }
        $numRows = $result->num_rows;
        if($numRows > 0){
      
                // if they are in the database, register the username
            $_SESSION['valid_user'] = $username;
      }
            

}


?>


<?php
if (isset($_SESSION['valid_user'])) {

      echo 'You are logged in as: '.$_SESSION['valid_user'].'<br />';
      echo '<a href="password.php">Please follow this link to change your password</a><br />';
}
else
{
      if (isset($username)) ///this doesn't work......
      {
      // tried but failed
            echo 'Could not log you in.<br />';
      }
      else
      {
      //users have not tried to login yet or have logged out
            echo 'you are not logged in.<br />';
      }
      
      }
?>


the form allows you even if the username and passwords are blank.....
0
 
miloudiAuthor Commented:
Hello Andy,

Sorry i didn't get back to you. Thanks for all your help.

Amine
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 10
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now