Home     Articles & Projects     Products & Web Services     Forum

uploading images and populating a database with the URL

Hi David,

I have been building a form to allow a user to add information on to a database. As part of that form I would really like the user to be able to select an image from their computer and be able to upload it to a directory on the site. The image would be given a unique file name and copied to a folder on the website.

When the form is submitted i’d like it so that the inserted record captures the URL of the uploaded file.

I would really appreciate any pointers of how to do this.

Many thanks

Simon

Hi Simon, The key function

Hi Simon,

The key function in the implementation of this would be the move_uploaded_file() function.

In your upload form handler script; it would be a case of generating the required unique name, and then moving the image file to that location; the URL of which is therefore known and you can insert into your database.

A key aspect is to make sure that PHP has WRITE access to the directory into which you want to move the uploaded file. This is easily done using your FTP program. On your site, create the folder into which you want uploaded files to be moved, and Right-Click. Look for either Permissions, or maybe Properties... and then Permissions, and give the folder WRITE access to all users (owner, group, world).

The 2 things you now need to know are;

a) the actual path to that folder on your server
b) the HTTP URL to that folder

If you're not sure of a), you can establish it using a simple script as follows:

whereami.php

<?php
  $path
= $_SERVER["SCRIPT_FILENAME"];
 
$path = str_replace("whereami.php","",$path);
  print
$path;
?>

Upload the above script to the folder into which you wish to store your uploaded images, and then browse to www.example.com/path/to/whereami.php

The actual server path will then be displayed.

In your upload form handler script, this is what you will need to prefix to your derived filename for the uploaded image as the destination parameter in your call to move_uploaded_file().

Regarding the derived image filename, I'm assuming that you will have some kind of ID relating to the user, maybe from a database so you could use something like userid.jpg, but that depends on your application of course.

Let me know if you need any further pointers!