|
 |
|
 |
02-06-2007, 12:04 PM
|
#1 (permalink)
|
|
Salchester
Join Date: Jul 2005
Location: In a house
Posts: 230
|
PHP Photo Gallery
Howdy Partners,
I am currently in the progress of building a simple online Photo Gallery using PHP, only how do you store the images in a database, and then display them on the screen?
Many Thanks,
__________________
Many Thanks, in advance!
Salchester.
The Future Is Here - Are You Ready?
|
|
|
02-06-2007, 12:14 PM
|
#2 (permalink)
|
|
Moderator
Join Date: May 2002
Location: us.ca
Posts: 4,475
|
salch, are you sure you want to do that? storing images in the database is more hassle than it is worth.
i'd recommend making a database table for the images.. set an auto increment field, and then either name your images with the image ID, .. or store the file name of the image in the database if you need to retain the original image name on the file itself.
i've always stayed away from this method so i can't be much help otherwise.
__________________
Mike
|
|
|
02-06-2007, 12:28 PM
|
#3 (permalink)
|
|
Salchester
Join Date: Jul 2005
Location: In a house
Posts: 230
|
PHP Photo Gallery
Hi SDE,
So out of those two options, which would you say is the better one?
How would you go about storing the path of the upload image into the database, and how would you go about loading the image onto the page afterwords?
Is there any other way this can be done, what method would the current Photo Gallery's on the Internet use?
Many Thanks, much appreciated!!!
__________________
Many Thanks, in advance!
Salchester.
The Future Is Here - Are You Ready?
|
|
|
02-06-2007, 12:41 PM
|
#4 (permalink)
|
|
Senior Contributor
Join Date: Mar 2005
Posts: 661
|
Quote:
Originally Posted by Salchester
Is there any other way this can be done, what method would the current Photo Gallery's on the Internet use?
|
Upload/View Images and Captions
Quote:
Originally Posted by DJMaze
i advice you to learn something or use one of the better galleries instead (coppermine or menalto egallery).
|
Both store images on the hdd and put upload details into a database. They even support EXIF data. And have taken many years of development.
Quote:
Originally Posted by Salchester
This Back Office will also need to be password protected!!
|
You mean an administration interface. This definitely should be a seperate project.
http://phpsec.org/projects/guide/
http://www.google.nl/search?q=php+upload+security
I'm sorry but upload scripts and SQL injections are the most high traffic attacks to compromise servers of clueless people.
The information i provide are not to downgrade your skills, but are aimed to learn it the right way, including me not seeing the 1 millionth forum topic "help my site is hacked"
http://www.google.nl/search?q=help+my+site+hacked
At the end you will appreciate the warning and information and then pass it on to the next newbie who tries to write a PHP driven website.
__________________

UT: Ultra-kill... God like!
|
|
|
02-06-2007, 12:45 PM
|
#5 (permalink)
|
|
Salchester
Join Date: Jul 2005
Location: In a house
Posts: 230
|
Yes but as long as you provide enough validation, within forms etc, couldn't you prevent the presence of SQL injections?
Many Thanks,
__________________
Many Thanks, in advance!
Salchester.
The Future Is Here - Are You Ready?
|
|
|
02-06-2007, 12:55 PM
|
#6 (permalink)
|
|
Salchester
Join Date: Jul 2005
Location: In a house
Posts: 230
|
Could you give me an insight on how it would be done anyway, as the server i am currently using is not live, it doesn't even have a domain name to access it.
It would be nice to just play around with it to see how it would kind of work.
YOU LEARN MORE BY PLAYING AND TRYING, THAN JUST READING!!!
Many Thanks, much appreciated!!!
__________________
Many Thanks, in advance!
Salchester.
The Future Is Here - Are You Ready?
|
|
|
02-06-2007, 01:22 PM
|
#7 (permalink)
|
|
Senior Contributor
Join Date: Mar 2005
Posts: 661
|
Before you can realy upload files you must setup the server properly.
This means the following
php.ini
Code:
;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;
; Whether to allow HTTP file uploads.
file_uploads = On
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
;upload_tmp_dir = "c:\php52\uploadtemp"
; Maximum allowed size for uploaded files.
upload_max_filesize = 2M
When it isn't turned on there is no uploaded file.
When the system default temp dir or upload_tmp_dir is not writable by the correct user (where Apache+PHP-mod or PHP-CGI/suexec) there is no uploaded file.
So first you must find out a few things:
- IIS or Apache
- PHP as httpd module or as cgi
- has the UID, which php uses, write access to the temp dir
- is PHP safe_mode turned on and configured properly using suexec
- is PHP open_basedir turned on and configured properly
When safe_mode and open_basedir are turned off you have a high change that the script may work. However when the server is using IIS and you have no clue how to manage IIS the script won't work either, since you don't have write access to public folders.
Linux+Apache would be the easiest to configure and then you can write and test upload scripts.
For Apache make sure that only .php is allowed for script execution and not .php* which some servers do.
For example it has .php.jpg then the file may be executed by the server (like include() and require() do)
include() and require() provide another big security hole here so never use these and related functionality to "open" an upload.
As example, i could write
PHP Code:
<?php phpinfo() ?>
inside a gif file and voilą.
Now when all is configured correctly, you can upload files.
These files will have a temporary name inside the temporary directory.
If your form field is named "fn" you must do some checks before actualy moving the uploaded file.
PHP Code:
if (empty($_FILES['fn'])) { die('no file uploaded'); } if (!is_uploaded_file($_FILES['fn']['tmp_name'])) { die('Possible file upload attack'); }
switch ($_FILES['fn']['error']) { case UPLOAD_ERR_INI_SIZE: die('The uploaded file exceeds the upload_max_filesize directive in php.ini');
case UPLOAD_ERR_FORM_SIZE: die('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.');
case UPLOAD_ERR_PARTIAL: die('The uploaded file was only partially uploaded.');
case UPLOAD_ERR_NO_FILE: die('No file was uploaded.');
case UPLOAD_ERR_NO_TMP_DIR: die('Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.'); case UPLOAD_ERR_CANT_WRITE: die('Failed to write file to disk. Introduced in PHP 5.1.0.');
case UPLOAD_ERR_EXTENSION: die('File upload stopped by extension. Introduced in PHP 5.2.0.'); } /* UPLOAD_ERR_OK so we now check the content using http://php.net/getimgsize of http://php.net/fileinfo But this depends on the type of accepted upload */
In your case we can use getimgsize since you only want to allow images.
If getimgsize succeeded on the $_FILES['fn']['tmp_name'] you're save to finally move_uploaded_file.
As you can see a file extension is never a safe guess for a correct file uploaded and that the file does contain what the extension says.
For example rename an php file to jpg and see for yourself
If getimgsize failed then either safe_mode, open_basedir or a bad file is the case.
__________________

UT: Ultra-kill... God like!
|
|
|
02-06-2007, 01:31 PM
|
#8 (permalink)
|
|
Senior Contributor
Join Date: Mar 2005
Posts: 661
|
If you understand it all, you should be going the right way.
I never explain this because most didn't care anyway, so i mostly only explained it to the junior programmers at work and to my friends at Dragonfly CMS.
Afterall, this is only the basics regarding file uploading and its security.
You will eventually notice there is loads more to learn and then your "LEARN MORE BY PLAYING AND TRYING" will come in place after someone compromised your serverspace.
__________________

UT: Ultra-kill... God like!
|
|
|
02-06-2007, 01:52 PM
|
#9 (permalink)
|
|
Salchester
Join Date: Jul 2005
Location: In a house
Posts: 230
|
PHP Photo Gallery
Howdy DJMaze,
I have come up with the following upload code to play with, sure it not perfect and probably has lots of security holes in it, but it's a start.....
How do i store the upload image path inside a database, and then retrieve the paths from the database on a separate page, and display the appropriate images?
Code:
<html>
<body>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Code:
<?php
if (($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
Many Thanks,
__________________
Many Thanks, in advance!
Salchester.
The Future Is Here - Are You Ready?
|
|
|
02-06-2007, 02:12 PM
|
#10 (permalink)
|
|
Senior Contributor
Join Date: Mar 2005
Posts: 661
|
Your code definitely is a security risk so keep my things in mind
As for database:
PHP Code:
mysql_query('INSERT INTO tablename (id, path, filename) VALUES (NULL, \'' . mysql_real_escape_string($path) . '\', \'' . mysql_real_escape_string($filename) .')');
__________________

UT: Ultra-kill... God like!
|
|
|
02-06-2007, 02:18 PM
|
#11 (permalink)
|
|
Salchester
Join Date: Jul 2005
Location: In a house
Posts: 230
|
PHP Photo Gallery
DJMaze,
What do i do with that?
The following, is the code i use to create the database:
Code:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE photos",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table in photos database
mysql_select_db("photos", $con);
$sql = "CREATE TABLE image
(
path text
)";
mysql_query($sql,$con);
mysql_close($con);
?>
Many Thanks,
__________________
Many Thanks, in advance!
Salchester.
The Future Is Here - Are You Ready?
|
|
|
02-07-2007, 04:24 AM
|
#12 (permalink)
|
|
Salchester
Join Date: Jul 2005
Location: In a house
Posts: 230
|
PHP Photo Gallery
DJMaze,
OK, the image now uploads to the server, and the image path gets inserted into the database. How do i now read the path(s) from the database, and display the image(s) on a page?
Many Thanks, much appreciated!!!
__________________
Many Thanks, in advance!
Salchester.
The Future Is Here - Are You Ready?
|
|
|
02-07-2007, 05:50 AM
|
#13 (permalink)
|
|
Moderator
Join Date: May 2002
Location: us.ca
Posts: 4,475
|
with your code example above, you're not uploading any text data so there would really be no need to use a database. you could simply read the file system.
let's say you wanted to store a caption or other info associated with the image. create a database table with 2 fields, filename and caption.
in your form, add a text field for caption.
let's put it all together. (djm's validation suggestions, your upload logic, and store the record in the datbase with a caption)
PHP Code:
<?php $errors = array();
// error checking if (empty($_FILES['file'])) { $errors[] = 'no file uploaded'; } if (!is_uploaded_file($_FILES['file']['tmp_name'])) { $errors[] = 'Possible file upload attack'; }
switch ($_FILES['file']['error']) { case UPLOAD_ERR_INI_SIZE: $errors[] = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE: $errors[] = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
case UPLOAD_ERR_PARTIAL: $errors[] = 'The uploaded file was only partially uploaded.';
case UPLOAD_ERR_NO_FILE: $errors[] = 'No file was uploaded.';
case UPLOAD_ERR_NO_TMP_DIR: $errors[] = 'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.'; case UPLOAD_ERR_CANT_WRITE: $errors[] = 'Failed to write file to disk. Introduced in PHP 5.1.0.';
case UPLOAD_ERR_EXTENSION: $errors[] = 'File upload stopped by extension. Introduced in PHP 5.2.0.'; }
// your error checking if ($_FILES["file"]["type"] != "image/gif" || $_FILES["file"]["type"] != "image/jpeg")) { $errors[] = 'Wrong image format.'; }
if ($_FILES["file"]["size"] > 20000) { $errors[] = 'File is too large.'; }
if ($count($errors)==0) { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { // add record to database $result = mysql_query("insert into images (filename, caption) values('".$_FILES["file"]["name"]."',mysql_real_escape_string($_POST['caption'])"); move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } else {
echo "<b>Errors</b><br />"; foreach ($errors as $each) { echo $each."<br />"; } } ?>
now to display the images.. just read the image table you are writing to and generate the html.
PHP Code:
<?php // query db for image filenames and captions $result = mysql_query("select * from images"); while ($row = mysql_fetch_assoc($result)) { // print an HTML image tag echo "<img src='upload/".$row['filename']."' alt='".htmlentities($row['caption'])."' title='".htmlentities($row['caption'])."'>"; // print the caption and 2 line breaks echo "<br />".$row['caption']."<br /><br />"; } ?>
__________________
Mike
|
|
|
02-07-2007, 09:53 AM
|
#14 (permalink)
|
|
Salchester
Join Date: Jul 2005
Location: In a house
Posts: 230
|
PHP Photo Gallery
SDE,
Do you have the code to create the database and tables? Similar to the code below?
Code:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table in my_db database
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Person
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);
mysql_close($con);
?>
Many Thanks,
__________________
Many Thanks, in advance!
Salchester.
The Future Is Here - Are You Ready?
|
|
|
02-07-2007, 01:17 PM
|
#15 (permalink)
|
|
Moderator
Join Date: May 2002
Location: us.ca
Posts: 4,475
|
keep in mind, i'm not testing this code.. just use it for a logic reference.. most of it should work though.
Code:
$sql = "CREATE TABLE images (
`imageid` int(10) unsigned NOT NULL auto_increment,
`filename` varchar(32) NOT NULL default '',
`caption` varchar(64) NOT NULL default '',
PRIMARY KEY (`imageid`),
UNIQUE KEY `filename` (`filename`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";
this table will automatically increment the ID so you don't have to insert the id when you add an image. it's not necessary to have that field but i prefer to handle individual elements of a table with an integer.
the filename is unique, so you won't be able to have duplicate entries for a filename. since all your files are in the same upload directory, that's probably best.
keep in mind, there's a lot of ways to do what you're doing .. i'm just posting one way to help you get something up so you can tweak it to your needs.
__________________
Mike
|
|
|
| | |