PDA

View Full Version : PHP MySQL - insert images



imagined
April 19th, 2004, 05:25 PM
I'm relatively new and I'm programming this CMS. I already able to add, edit and remove pages with text that is stored in a MySQL database. Now, I want to be able to give the user the option of Inserting Images on the page.

How can I do this? I was looking at some forums and found this:


Should I store images in MySQL?
One word: No!
Storing images in a database is at least 10 times slower when retrieving than storing just a filename which then get's delivered by the webserver.<BR> Ok, Step one: For every image, you'll need an additional query. It will have to be read of the mysql server, transported to your webservers memory, pushed out to the user's browser and then thrown away in your webserver memory. Repeat ad nausaum.
Now, if it's stored as a file, it's faster to begin with (no database queries, and filesystems are really really fast, nowadays), plus it will also be cached in your webservers memory if it's asked for a lot making it as fast as the line will take it.
from http://www.ozoneasylum.com/5704



so, how can i upload images and then display them in the page dynamically?

Thanks!

Leo :jail:

APDesign
April 19th, 2004, 06:20 PM
so, how can i upload images and then display them in the page dynamically?

Youch, thats a whopper of a question... Since I pretty much just tackled that yesterday, I might be able to help. Real quick and real basically though you need a form that looks like this:
the enctype is important because it lets it know some sort of file will be used (like an uploaded file!)



<form method="post" enctype="multipart/form-data" action="yourscript.php">
<input type="file" name="up_handle" />
</form>


uphandle can be whatever you want to refer to the file in the $_FILES array (which I'll get to right now..)

So in "yourscript.php" (whatever that may be) you will now have access to a $_FILES array. So if you want to refer to the uploaded file "up_handle" you can do it like this: $_FILES['up_handle']. Now, you'll get a whole ton of extra stuff in that array that has to do with the uploaded file, so you can get its name, it's file size etc.. etc.. you can do that like this: $_FILES['up_handle']['name']; Pretty cool eh?? Here are a bunch more (taken from php.net)(link) (http://us3.php.net/features.file-upload)



$_FILES['userfile']['name'];
The original name of the file on the client machine.

$_FILES['userfile']['type'];
The mime type of the file, if the browser provided this information. An example would be "image/gif".

$_FILES['userfile']['size'];
The size, in bytes, of the uploaded file.

$_FILES['userfile']['tmp_name'];
The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error'];


ok, now once the file is uploaded, it stays in a temporary directory (defined by your server) and it has a temporary name (which you have access too via $_FILES['up_handle']['tmp_name']) So how do you move the file from the temporary directory to somewhere in your server? Enter: move_uploaded_file() (http://us3.php.net/manual/en/function.move-uploaded-file.php)! This accepts two arguments, "string filename, string destination" and returns "true" if it was a success and "false" if it was a failure, so here is what you would do in your "yourscript.php" to move the files.



<?php
$do_db = FALSE;
if(move_uploaded_file($_FILES['up_handle']['tmp_name'], "./destination/folder/{$_FILES['up_handle']['name']}")){
echo '<p>Full image upload success!</p>';
$do_db = TRUE;
} else {
echo '<p>Uh oh, failure!</p>';
}

if($do_db){
/* This is where you would want to insert the $_FILES['up_handle']['name'] into the database,
but beware of what I mention below. After you have it inserted, its just a matter of pulling the
filename and you are set! */

}
?>


now beware the $_FILE['up_handle']['name'] is the name of the file on the clients machine, meaning they might have all sorts of spaces and crap in it, so you might want run the filename through some functions to clear out the the stuff you don't want and save it as $thefilename and pass that to the destination instead of using $_FILE['up_handle']['name'];

Well, thats my quick "tutorial" on uploading files and storing the name in a database, anyone more knowledgeable than me feel free to correct my mistakes and improve on it. Hope it helps.

Freddythunder
April 20th, 2004, 05:14 AM
Just for the sake of saying too, most PHP servers in my exp. will tell you few things about filetype. If you want to allow zips, your gonna allow a lot of other things you may not want to open up on your home computer. I was playing with this today for a client of mine. If you want to limit the types of files uploaded to your server, you can find its extention and limit from there with this (before you move_uploaded_file()):


$file = $_FILES['up_handle']['name'];
$ext = strstr($file,"."); //returns the . and what's behind it
if($ext != ".jpg" && $ext != ".jpeg" && $ext != ".gif"){
//you wont accept anything besides jpegs and gifs
echo "You moron! You can't put that here!";
} else {
$success = move_uploaded_file($_FILES['up_handle']['tmp_name'], "destination/".$file);
if($success){
echo "Hooray! Your picture is on my server!! Wee!";
} else {
echo "There was an error!";
}
}


Just a little extra for you! By the way, on the end of those $_FILES array examples above, don't forget the semicolon (;) at the end to avoid parse errors!

APDesign
April 20th, 2004, 09:26 AM
Do you know if using the $_FILES['userfile']['type']; would be as secure as checking the actual extension or not?

(I added the semicolons ;) )

imagined
April 20th, 2004, 12:17 PM
Man! this is awesome! thanks guys! I had read and tried a whole buncha tutorials about this before but they never worked (or i did it wrong) and could never understand them. This quick tutorial is AWESOME and very, very easy to understand.

I just have some comments:

The tutorial works great, but i just didn't get this part:


if($do_db){ <BR>/* This is where you would want to insert the $_FILES['up_handle']['name'] into the database, <BR>but beware of what I mention below. After you have it inserted, its just a matter of pulling the <BR>filename and you are set! */

the file is already saved in a folder in my webserver. do i still need to save it into a MySQL database?


and about the file types. i had some trouble with it, but already solved it. there was a jpg that the script wouldn't accept. so i looked at it and found out that the script only accepts extensions in LOWERCASE. so i just had to add this to the script:

&& $extension != ".JPG" && $extension != ".JPEG" && $extension != ".GIF"

and it also works with UPPERCASE extensions.

Now, I have a question...

How do you check if there is a file with the same filename and prompt the user to replace the file or cancel the action? how would you delete one of the files?

THANKS!

:azn:

ScriptFlipper
April 20th, 2004, 02:25 PM
Instead of adding extra extension-checks, just add this row below the row where $ext is assigned:

$ext = strtolower($ext);

APDesign
April 20th, 2004, 02:57 PM
the file is already saved in a folder in my webserver. do i still need to save it into a MySQL database?
Nope, you don't have to, I was under the assumption that thats what you wanted to do, but if it isn't, then just skip that step.


How do you check if there is a file with the same filename and prompt the user to replace the file or cancel the action? how would you delete one of the files?

Hmm, maybe I'll figure out how to do this later if no one else does, but it should just be a matter of looping through the files in the folder and checking the file name of the existing images against that of the one wanting to be saved. Youd do that before you actually moved the file. There might even be a function to check if a file exists... just checked php.net, and there is one (http://us3.php.net/manual/en/function.file-exists.php) so with that function it would be even easier... I'll look at it later if you still want me to or if no one else does.

Maybe I should make my first REAL tutorial, eh?

ScriptFlipper
April 20th, 2004, 03:21 PM
Yeah, make a tutorial on this, APDesign! You seem skilled enough
(naaaahhh, really?? ;) )

And thank you for this!

imagined
April 20th, 2004, 04:20 PM
hey! thanks! ALL this have been really helpful.

another question (and i hope i dont bother you guys anymore):

when i upload the image file, it gets uploaded to a certain folder.

what if i want only 3 images to be in the folder, and if I already have 3 images, and there is another file that wants to get uploaded, it will prompt you to delete one image so you can upload another one?

Freddythunder
April 21st, 2004, 04:49 AM
Do you know if using the $_FILES['userfile']['type']; would be as secure as checking the actual extension or not?


I think it would be easier just checking the extention of the file because that if you check the variable in the $_FILES array, you could get an octet/stream, text/plain, text/html, and sometimes - nothing at all (spooky!!). All that array shows is the mime type of the file. If you don't have your script setup to check any/all possible answers for mime type, someone could load something you may not want on your server. However, with my way, checking extentions, someone just needs to change the extention from say .exe to .jpg and have me open it on my home computer. Depending on my settings, Windows my decide to open and run it as a program instead of a picture. It all depends on what you want to do and what kind of files you want to accept with the upload. And also your level of security.

That's pretty much what I know of it. :)

ScriptFlipper
April 21st, 2004, 09:12 AM
Hey, guys...
I did a function of the script above, and the function looks like this:


function addImage ($postid) {
$file = $_FILES[$postid]['name'];
$ext = strstr(strtolower($file),"."); //returns the . and what's behind it
if($ext != ".jpg" && $ext != ".jpeg"){
//you wont accept anything besides jpegs and gifs
echo "You can only upload JPEG files.\r\n";
echo ($_FILES[$postid]['name']."\r\n");
echo ($file."\r\n\r\n");
} else {
// etc..


But when I call the function like this:
addImage('image1');
where image1 is the name of the file-field in the form, it doesn't work. However, if I don't use the function and just typ $_FILES['image1']['name'] it works!
How can this be?

Cheers and thanx again