Image Handling

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Can anybody suggest to me a good tutorial on how to upload images in php and
have their location put into a MySQL database?

I know that this is really basic but so are my PHP skills at the moment.


Re: Image Handling

On Sat, 13 Oct 2007 08:30:54 +0000, Kye wrote:

Quoted text here. Click to load it

some code to help figure the process out

include 'config.php';    // hold database name, location, user, pass etc

// we only upload jpg

$mimetypes = array("image/jpg", "image/jpeg", "image/jpe", "image/pjpeg");
$code = "";

// process post data

if (isset($_POST['filesubmitted'])) {

    $tmp_name = $_FILES['file']['tmp_name'];

    if (!is_uploaded_file($tmp_name))
        $code = "filenotfounderror";

    $file_size = $_FILES['file']['size'];

    if ($file_size > $upload_file_size)
        $code = "filesizeerror";

    $mime_type = $_FILES['file']['type'];
    if (!in_array($mime_type, $mimetypes))
        $code = "filetypeerror";

} else
    $code = "resubmit";

if ($code != "") {
    // deal with error

    $_SESSION = array();
    $_SESSION['formdata'] = $_POST;
    header("Location: add.php?code=$code");
} else {
    $document_root = $_SERVER['DOCUMENT_ROOT'];
    $destination = $document_root . "/images/";

    $file_name = $_FILES['file']['name'];

    move_uploaded_file($tmp_name, $destination . $file_name);

    if (is_file($destination . $file_name)) {
      $oldumask = umask(0);
      chmod($destination . $file_name, 0644);
    } else
        die("Er... what the fuck happened?");
    // insert new record in database
    $file_name = $_FILES['file']['name'];
    mysql_connect($db['host'], $db['user'], $db['password'])
    or die (mysql_error());

    mysql_select_db($db['name']) or die(mysql_error());
    $query = "INSERT INTO $table (file_name) VALUES ('$file_name')";
    $result = mysql_query($query);
    if (!$result) {
        $msg  = 'Invalid query:' . mysql_error() . '<br>' . $query . '<br>';


    header("Location: done.php?");


Re: Image Handling

Kye wrote:
Quoted text here. Click to load it
Here are some snippets from code that actually works. I Actually shove  
the files iN the database. Not references to them.

// Yawn bugger, Files. File data should be stored in the $_FILES[]  
array, so let's start with the the new ones..
      for ($i=0;$i<10;$i++)
        $filename= $_FILES[$index]["name"]; //orig filename
        $filesize= $_FILES[$index]["size"];     // the size in bytes of the  
uploaded file
         $tmpname=$_FILES[$index]["tmp_name"]; // the name of the temporary  
copy of the file stored on the server
         $index="new_description".$i; // where new file decscriptors are stored

         if ($filename=="" || $filesize==0) // skip emptiness.
         // one supposes one has a file at this point..massage the name  
into just the filename without the slashes
         $query=sprintf("insert into project_files set  
project_id='%s',current='yes', date='%s' ,user='%d', size='%d',  
description='%s', name='%s', content=LOAD_FILE('%s') ",
    } // end if update..

Note the use of the copy command to sidestep a 'feature' of PHP5that it  
doesn't in fact create aan actual disk file that Mysql can LOAD until it  
exits, unless you COPY it.

The form section that allows te user to upload files is this..

// Ok lets put up 12 new file boxes for upload
?><B>Add new files:</B><Br>
<TABLE width="50%" border="0" align="center"> <tr>
<TD align="left"><B>Select file to upload</b></TD><TD  
align="left"><b>Enter Brief Description</b></td></TR>
    ?><TR><TD align="left"><INPUT size="50" TYPE="file"  
name="new_file<?echo $i;?>" ></td>
    <TD align="left"><INPUT type="text" size="50" value=""  
name="new_description<?echo $i;?>"  maxlength="64" >

And to retrieve the file for download, I simply use a URL pointing at  
this code, with the file ID as a get variable.

open_database(); // ready to check
// get file id..use GET rather than POST as there is adequate security  
// and it makes clickable download URLS easier to generate.
// i.e. <A HREF="filesend.php?id=XXXX"> Download the file here</A> will work
// if you know the file iD in the database. And have permissions to  
access the project it's in.
// first check whether the user exists on the database.  If they have  
got this far this should never fail
// unless someone manually deletes a database entry or corrupts it.
$query="Select id, privilege_level from employees where login_name =  
if(($result>0) && (($rows=mysql_numrows($result)) == 1)) //got some data
        $employee_id=mysql_result($result,0,"id"); // id in employees table
        $privilege=mysql_result($result,0,"privilege_level"); // and get their  
privilege Power users can access any project
else abort_session(" this user is unkown - Access denied!\r\n");
if ($privilege < $privilege_level) // can access the file only if matches project creator
    $query="select employee from projects, project_files where'".$file_id."' and";
    if(($result>0) && (($rows=mysql_numrows($result)) == 1)) //got some data
        if($employee_id!=mysql_result($result,0,'employee')) // user doesn't  
have access rights to this project
            abort_session("you have insufficient privileges to access this  
             //which begs the question of how they got to start trying to  
download it,. Hmm..bug elsewhere?
//ok we can access the file about actually?
$query="select name, content, size  from project_files where  
if(($result>0) && (($rows=mysql_numrows($result)) == 1)) //got some data
else abort_session ("the file ID you requested cannot be found\r\n"); //  
no such file/project in the database    
//spit out standard header stuff
header("Pragma: public");

header("Expires: 0");

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

header("Cache-Control: public");

header("Content-Description: File Transfer");

header("Content-Type: ".$mtype);

header("Content-Disposition: attachment; filename=\"".$name."\"");

header("Content-Transfer-Encoding: binary");
print $content;

Note that there are lots of calls to library stuff I have written but  
you should be able to get the gist of what is going on.

In practice this is working very well. We use it to exchange working  
documents with a database server.  The code is npot elegant, but them I  
am fairly new to PHP.

It does, however work.

Re: Image Handling

<Sat, 13 Oct 2007 08:30:54 GMT>

Quoted text here. Click to load it and have a look at 'upload' webpages .

Just tack on some php code onto the end of the routine to put the image  
location into your database .


Site Timeline