Code for Creating a PHP Photo Gallery
So why might anyone want to learn to make a PHP photo gallery when there are plenty of freebies out there and in control panels of websites? Because learning is fun, and you might try using this as a stepping stone for writing your own PHP gallery script. And if you don't want to learn PHP, we have a JavaScript photo gallery that we teach you about. These scripts are fun to tinker with, modify, and learn from.
For more on viewing and creating a PHP photo gallery, simply go to code-for-php-photo-gallery.html
Here are the tutorial files for all the photo gallery functions:
View Gallery
Create Gallery
Add Category
Delete Category
Add Photo
Delete Photo
So, on to the code. We define the CSS, then run browser sniffers and finetune the display with the fix() function, run by the onload in the body tag. Next, there's the PHP. The PHP code starts as so many PHP codes start: by getting the db connection data from a config file. It shows the password, username, and database name. Then we create the categories and photos db tables.
The instructions say: "Use letters, numbers, hyphens, dots and underscores only in photos. Use letters, numbers, and underscores only in categories. Categories and photos must be separated by commas with NO SPACES ANYWHERE and each category or photo must be under 30 characters long, e.g.: fish,birds,mammals,insects. Submit comma-separated categories first, then submit comma-separated photos, selecting category from the dropdown." And you can see in the replacement patterns for categories and photos that any character not conforming to these specifications is dumped. Note that the strip_tags() function is used before the replacements happen. Otherwise, if just tag brackets get dumped—in the preg_replace() replacement routines, the tag contents will stay around as residue. Of course, you're not silly enough to try to put tags in picture names, but tag stripping is a good habit to get into when you'll be writing to a MySQL db, and so is mysql_real_escape_string() a great habit, so we do that as well.
If no serious input has occurred (strlen($P)<5 && strlen($C)<5) then we echo the HTML category input form to the screen. Its action is reloading itself—cms-write-photo-gallery.php—so it can POST the inputted data to the PHP script. If serious category input has happened, then $ct = explode(",", $C);$n=count($ct); is run to take the comma-separated string full of categories and "explode" it into an array of categories—just what the doctor ordered. This $ct[] array is inserted into the categories table from a FOR loop that INSERTs them one at a time. Then the table gets read and its contents pushed into a $cat[] array. Next, if serious input has been entered, a form for entering photos is echoed to the screen. Note the way one can stick PHP array values into an HTML form: echo "<option value='".$cat[$i]."'>".$cat[$i]."</option>"; as options in a dropdown list. Finally, if serious photo string entry has occurred, the comma-separated string is exploded and INSERTed into the photos table.
There's a JavaScript function at the bottom of the page that simply makes the categories entry form cease to exist once the form is submitted. It uses the form's CSS display property, giving it the value "none". The form makes itself go away with the onSubmit() in the form tag. This disappearing act is to get the no-longer-needed form out of the way and direct attention to the photos entry form.
TERMS OF USE: You must put a link on your site's home page to:
<a HREF="http://www.css-resources.com">css-resources.com</a> and it must NOT be a "nofollow" link, now or ever, and the link must stay live and unbroken for as long as you use the photo gallery script you'll find on this page, and you may not edit any part of the link, which must say "css-resources.com". Your site must NOT, now or ever, be about violence or hate or crime or treason or porn or terrorism, and your photo gallery script site/page must not have photos involving violence or hate or crime or treason or porn or terrorism. Do not use the sample photos in our sample JavaScript photo gallery for anything: they're copyrighted by © Focus Multimedia Ltd., Serif (Europe) Ltd., and Hemera Technologies Inc. If you cannot accept these terms, please do not use our script. We reserve the right to deny our script use to anyone with an unacceptable website. Our script is copyrighted by us, at MCS Investments, Inc. All these codes work—we have a working version we use here using this same code.
SAVE THIS PAGE AS: cms-write-photo-gallery.php
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>Creating Photo Gallery—Content Management System (CMS)</TITLE>
<meta name="description" content="Creating Photo Gallery—Content Management System (CMS)">
<meta name="keywords" content="Creating Photo Gallery,Creating Photo Galleries,Content Management System,Content Management System Articles,php,CMS,javascript, dhtml, DHTML">
<script language="javascript">
var cat=new Array();
mactest=(navigator.userAgent.indexOf("Mac")!=-1) //My browser sniffers
is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1
Netscape=(navigator.appName.indexOf("Netscape") != -1)
msafari=(navigator.userAgent.indexOf("Safari")!= -1)
wsafari=0; if(!mactest&&msafari){wsafari=1;msafari=0}
is_opera = 0; if(window.opera){is_opera=1}
is_ie_mac = 0; is_ie=0;if(document.all){is_ie=1}
if(is_ie&&mactest){is_ie_mac=1}
function fix(){if(Netscape||is_opera){e=document.getElementById('top');e.style.marginTop='1px';e=document.getElementById('info');e.style.marginTop='1px';}}
</script>
<style type="text/css">
BODY {margin-left:0; margin-right:0; margin-top:0;text-align:left;background-color:#ddd}
p, li {font:13px Verdana; color:black;text-align:left}
h1 {font:bold 20px Verdana; color:black;text-align:center}
h2 {font:bold 24px Verdana;text-align:center}
h3 {font:bold 15px Verdana;}
.url {position:absolute;top:0px;left:10px;width:989px}
.form {position:absolute;top:200px;left:200px;width:700px}
.form2 {position:absolute;top:200px;left:200px;width:700px}
.info {position:absolute;top:80px;left:45px;width:900px;border:1px solid blue;padding:6px;background-color:#bbb}
.side {position:absolute;top:160px;left:715px;width:277px;padding:6px;background-color:#bbb;border:1px solid blue}
</style>
</head>
<body onload='fix()'>
<?php
include_once"config.php";
$sql = "CREATE TABLE IF NOT EXISTS categories_ (
id int(11) NOT NULL auto_increment,
category varchar(30) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1";
// Execute query
mysql_query($sql);
$sql = "CREATE TABLE IF NOT EXISTS photos (
id int(11) NOT NULL auto_increment,
photo varchar(255) NOT NULL,
category varchar(30) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1";
// Execute query
mysql_query($sql);
$pattern1 = '/[^a-zA-Z0-9\\_\\,]/i';
$pattern2 = '/[^a-zA-Z0-9\\.\\,\\-\\_]/i';
$replacement = '';
$P=$_POST['photo'];
$C=$_POST['category'];
$CY=$_POST['cy'];
$P=strip_tags($P);
$C=strip_tags($C);
$P=preg_replace($pattern2, $replacement, $P);
$C=preg_replace($pattern1, $replacement, $C);
$C=mysql_real_escape_string($C);
$P=mysql_real_escape_string($P);
if (strlen($P)<5 && strlen($C)<5) { unset($P);unset($C);
echo "<div id='form' class='form'>
<form name='myform' method='post' action='cms-write-photo-gallery.php' onsubmit='bye()'>
<table width='700' border='0' cellpadding='2' cellspacing='2' align='center'>
<tr>
<td width='60'>Categories separated by commas, e.g.: fish,birds,mammals,insects</td><br>
<td><textarea name='category' cols='50' rows='11'></textarea></td>
</tr>
<tr>
<td> </td><td><input name='save' type='submit' value='Save Categories to DB'>
<input name='reset' type='reset' value='Reset'></td></tr>
</table>
</form>
</div>";
}
if (strlen($C)>4){
$ct = explode(",", $C);$n=count($ct);
for ($i=0;$i<$n;$i++) {
mysql_query("INSERT INTO categories_ (id, category)
VALUES ('','".$ct[$i]."')") or die('Error ,saving failed');}
$rc = mysql_affected_rows();
if ($rc>0){echo '<script language="javascript">alert("The saving was successfully accomplished.");</script>';}
else{echo '<script language="javascript">alert("The saving was unsuccessful.");</script>';}
}
$cat=array();
$res = mysql_query("SELECT category FROM categories_ order by category") or die(mysql_error());
while ($row = mysql_fetch_row($res)) {
array_push ($cat, $row[0]);
}
$num_cats_in_table=mysql_num_rows($res);
if (strlen($P)>4||strlen($C)>4){unset($C);
echo "<div class='form2'><form name='myform2' method='post' action='cms-write-photo-gallery.php'><table width='700' border='0' cellpadding='2' cellspacing='2' align='center'><tr><td width='60'>Photos separated by commas, e.g.: bear.jpg,horse.jpg,cow.jpg</td><td><textarea name='photo' cols='50' rows='11'></textarea></td></tr><tr><td>Category</td><td><select name='cy'>";
for ($i=0;$i<$num_cats_in_table;$i++) {
echo "<option value='".$cat[$i]."'>".$cat[$i]."</option>";}
echo "</select></td></tr><tr><td> </td><td><input name='save2' type='submit' value='Save Photos to DB'>
<input name='reset2' type='reset' value='Reset'></td></tr></table></form></div>";
}
if (strlen($P)>4){
$ph = explode(",", $P);$nn=count($ph);
for ($i=0;$i<$nn;$i++) {
mysql_query("INSERT INTO photos (id, photo, category)
VALUES ('','".$ph[$i]."','$CY')") or die('Error ,saving failed');}
$rc = mysql_affected_rows();
if ($rc>0){unset($P);unset($CY);
echo '<script language="javascript">alert("The saving was successfully accomplished.");</script>';}
else{echo '<script language="javascript">alert("The saving was unsuccessful.");</script>';}
}
mysql_close();
?>
<div id='top' class='url'>
<h1>Creating Photo Gallery—Content Management System (CMS)</h1>
<div id='info' class='info'>Use letters, numbers, hyphens, dots and underscores only in photos. Use letters, numbers, and underscores only in categories. Categories and photos must be separated by commas with NO SPACES ANYWHERE and each category or photo must be under 30 characters long, e.g.: <b>fish,birds,mammals,insects</b>. Submit comma-separated categories first, then submit comma-separated photos, selecting category from the dropdown.<br></div>
</div>
<script language="javascript">
function bye(){e=document.getElementById('form');e.style.display='none';}
</script>
<?php include("navi.html"); ?>
</body>
</html>