Photo Gallery CMS Tutorial

Published :
Author :
Adam Khoury
Learn PHP and Ajax photo gallery programming within your social network website software. This is not a completed or polished photo gallery viewing system, it must be redesigned by you to make things pretty and unique, and it must enhanced in its programming by you. The initial gallery thumbnails are loaded using PHP, everything else is brought into view using Ajax that requests images from PHP and MySQL. It also contains a simple file upload script so that your users can populate their galleries with pictures. We render a delete link only for the photo owners when they view any images that they uploaded. photos.php <?php include_once("php_includes/check_login_status.php"); // Make sure the _GET "u" is set, and sanitize it $u = ""; if(isset($_GET["u"])){ $u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']); } else { header("location: http://www.webintersect.com"); exit(); } $photo_form = ""; // Check to see if the viewer is the account owner $isOwner = "no"; if($u == $log_username && $user_ok == true){ $isOwner = "yes"; $photo_form = '<form id="photo_form" enctype="multipart/form-data" method="post" action="php_parsers/photo_system.php">'; $photo_form .= '<h3>Hi '.$u.', add a new photo into one of your galleries</h3>'; $photo_form .= '<b>Choose Gallery:</b> '; $photo_form .= '<select name="gallery" required>'; $photo_form .= '<option value=""></option>'; $photo_form .= '<option value="Myself">Myself</option>'; $photo_form .= '<option value="Family">Family</option>'; $photo_form .= '<option value="Pets">Pets</option>'; $photo_form .= '<option value="Friends">Friends</option>'; $photo_form .= '<option value="Random">Random</option>'; $photo_form .= '</select>'; $photo_form .= ' &nbsp; &nbsp; &nbsp; <b>Choose Photo:</b> '; $photo_form .= '<input type="file" name="photo" accept="image/*" required>'; $photo_form .= '<p><input type="submit" value="Upload Photo Now"></p>'; $photo_form .= '</form>'; } // Select the user galleries $gallery_list = ""; $sql = "SELECT DISTINCT gallery FROM photos WHERE user='$u'"; $query = mysqli_query($db_conx, $sql); if(mysqli_num_rows($query) < 1){ $gallery_list = "This user has not uploaded any photos yet."; } else { while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { $gallery = $row["gallery"]; $countquery = mysqli_query($db_conx, "SELECT COUNT(id) FROM photos WHERE user='$u' AND gallery='$gallery'"); $countrow = mysqli_fetch_row($countquery); $count = $countrow[0]; $filequery = mysqli_query($db_conx, "SELECT filename FROM photos WHERE user='$u' AND gallery='$gallery' ORDER BY RAND() LIMIT 1"); $filerow = mysqli_fetch_row($filequery); $file = $filerow[0]; $gallery_list .= '<div>'; $gallery_list .= '<div onclick="showGallery(\''.$gallery.'\',\''.$u.'\')">'; $gallery_list .= '<img src="user/'.$u.'/'.$file.'" alt="cover photo">'; $gallery_list .= '</div>'; $gallery_list .= '<b>'.$gallery.'</b> ('.$count.')'; $gallery_list .= '</div>'; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title><?php echo $u; ?> Photos</title> <link rel="icon" href="favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="style/style.css"> <style type="text/css"> form#photo_form{background:#F3FDD0; border:#AFD80E 1px solid; padding:20px;} div#galleries{} div#galleries > div{float:left; margin:20px; text-align:center; cursor:pointer;} div#galleries > div > div {height:100px; overflow:hidden;} div#galleries > div > div > img{width:150px; cursor:pointer;} div#photos{display:none; border:#666 1px solid; padding:20px;} div#photos > div{float:left; width:125px; height:80px; overflow:hidden; margin:20px;} div#photos > div > img{width:125px; cursor:pointer;} div#picbox{display:none; padding-top:36px;} div#picbox > img{max-width:800px; display:block; margin:0px auto;} div#picbox > button{ display:block; float:right; font-size:36px; padding:3px 16px;} </style> <script src="js/main.js"></script> <script src="js/ajax.js"></script> <script> function showGallery(gallery,user){ _("galleries").style.display = "none"; _("section_title").innerHTML = user+'&#39;s '+gallery+' Gallery &nbsp; <button onclick="backToGalleries()">Go back to all galleries</button>'; _("photos").style.display = "block"; _("photos").innerHTML = 'loading photos ...'; var ajax = ajaxObj("POST", "php_parsers/photo_system.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { _("photos").innerHTML = ''; var pics = ajax.responseText.split("|||"); for (var i = 0; i < pics.length; i++){ var pic = pics[i].split("|"); _("photos").innerHTML += '<div><img onclick="photoShowcase(\''+pics[i]+'\')" src="user/'+user+'/'+pic[1]+'" alt="pic"><div>'; } _("photos").innerHTML += '<p style="clear:left;"></p>'; } } ajax.send("show=galpics&gallery="+gallery+"&user="+user); } function backToGalleries(){ _("photos").style.display = "none"; _("section_title").innerHTML = "<?php echo $u; ?>&#39;s Photo Galleries"; _("galleries").style.display = "block"; } function photoShowcase(picdata){ var data = picdata.split("|"); _("section_title").style.display = "none"; _("photos").style.display = "none"; _("picbox").style.display = "block"; _("picbox").innerHTML = '<button onclick="closePhoto()">x</button>'; _("picbox").innerHTML += '<img src="user/<?php echo $u; ?>/'+data[1]+'" alt="photo">'; if("<?php echo $isOwner ?>" == "yes"){ _("picbox").innerHTML += '<p id="deletelink"><a href="#" onclick="return false;" onmousedown="deletePhoto(\''+data[0]+'\')">Delete this Photo <?php echo $u; ?></a></p>'; } } function closePhoto(){ _("picbox").innerHTML = ''; _("picbox").style.display = "none"; _("photos").style.display = "block"; _("section_title").style.display = "block"; } function deletePhoto(id){ var conf = confirm("Press OK to confirm the delete action on this photo."); if(conf != true){ return false; } _("deletelink").style.visibility = "hidden"; var ajax = ajaxObj("POST", "php_parsers/photo_system.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText == "deleted_ok"){ alert("This picture has been deleted successfully. We will now refresh the page for you."); window.location = "photos.php?u=<?php echo $u; ?>"; } } } ajax.send("delete=photo&id="+id); } </script> </head> <body> <?php include_once("template_pageTop.php"); ?> <div id="pageMiddle"> <div id="photo_form"><?php echo $photo_form; ?></div> <h2 id="section_title"><?php echo $u; ?>&#39;s Photo Galleries</h2> <div id="galleries"><?php echo $gallery_list; ?></div> <div id="photos"></div> <div id="picbox"></div> <p style="clear:left;">These photos belong to <a href="user.php?u=<?php echo $u; ?>"><?php echo $u; ?></a></p> </div> <?php include_once("template_pageBottom.php"); ?> </body> </html> photo_system.php <?php include_once("../php_includes/check_login_status.php"); ?><?php if (isset($_POST["show"]) && $_POST["show"] == "galpics"){ $picstring = ""; $gallery = preg_replace('#[^a-z 0-9,]#i', '', $_POST["gallery"]); $user = preg_replace('#[^a-z0-9]#i', '', $_POST["user"]); $sql = "SELECT * FROM photos WHERE user='$user' AND gallery='$gallery' ORDER BY uploaddate ASC"; $query = mysqli_query($db_conx, $sql); while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { $id = $row["id"]; $filename = $row["filename"]; $description = $row["description"]; $uploaddate = $row["uploaddate"]; $picstring .= "$id|$filename|$description|$uploaddate|||"; } mysqli_close($db_conx); $picstring = trim($picstring, "|||"); echo $picstring; exit(); } ?><?php if($user_ok != true || $log_username == "") { exit(); } ?><?php if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){ $fileName = $_FILES["avatar"]["name"]; $fileTmpLoc = $_FILES["avatar"]["tmp_name"]; $fileType = $_FILES["avatar"]["type"]; $fileSize = $_FILES["avatar"]["size"]; $fileErrorMsg = $_FILES["avatar"]["error"]; $kaboom = explode(".", $fileName); $fileExt = end($kaboom); list($width, $height) = getimagesize($fileTmpLoc); if($width < 10 || $height < 10){ header("location: ../message.php?msg=ERROR: That image has no dimensions"); exit(); } $db_file_name = rand(100000000000,999999999999).".".$fileExt; if($fileSize > 1048576) { header("location: ../message.php?msg=ERROR: Your image file was larger than 1mb"); exit(); } else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) { header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type"); exit(); } else if ($fileErrorMsg == 1) { header("location: ../message.php?msg=ERROR: An unknown error occurred"); exit(); } $sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $row = mysqli_fetch_row($query); $avatar = $row[0]; if($avatar != ""){ $picurl = "../user/$log_username/$avatar"; if (file_exists($picurl)) { unlink($picurl); } } $moveResult = move_uploaded_file($fileTmpLoc, "../user/$log_username/$db_file_name"); if ($moveResult != true) { header("location: ../message.php?msg=ERROR: File upload failed"); exit(); } include_once("../php_includes/image_resize.php"); $target_file = "../user/$log_username/$db_file_name"; $resized_file = "../user/$log_username/$db_file_name"; $wmax = 200; $hmax = 300; img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt); $sql = "UPDATE users SET avatar='$db_file_name' WHERE username='$log_username' LIMIT 1"; $query = mysqli_query($db_conx, $sql); mysqli_close($db_conx); header("location: ../user.php?u=$log_username"); exit(); } ?><?php if (isset($_FILES["photo"]["name"]) && isset($_POST["gallery"])){ $sql = "SELECT COUNT(id) FROM photos WHERE user='$log_username'"; $query = mysqli_query($db_conx, $sql); $row = mysqli_fetch_row($query); if($row[0] > 14){ header("location: ../message.php?msg=The demo system allows only 15 pictures total"); exit(); } $gallery = preg_replace('#[^a-z 0-9,]#i', '', $_POST["gallery"]); $fileName = $_FILES["photo"]["name"]; $fileTmpLoc = $_FILES["photo"]["tmp_name"]; $fileType = $_FILES["photo"]["type"]; $fileSize = $_FILES["photo"]["size"]; $fileErrorMsg = $_FILES["photo"]["error"]; $kaboom = explode(".", $fileName); $fileExt = end($kaboom); $db_file_name = date("DMjGisY")."".rand(1000,9999).".".$fileExt; // WedFeb272120452013RAND.jpg list($width, $height) = getimagesize($fileTmpLoc); if($width < 10 || $height < 10){ header("location: ../message.php?msg=ERROR: That image has no dimensions"); exit(); } if($fileSize > 1048576) { header("location: ../message.php?msg=ERROR: Your image file was larger than 1mb"); exit(); } else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) { header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type"); exit(); } else if ($fileErrorMsg == 1) { header("location: ../message.php?msg=ERROR: An unknown error occurred"); exit(); } $moveResult = move_uploaded_file($fileTmpLoc, "../user/$log_username/$db_file_name"); if ($moveResult != true) { header("location: ../message.php?msg=ERROR: File upload failed"); exit(); } include_once("../php_includes/image_resize.php"); $wmax = 800; $hmax = 600; if($width > $wmax || $height > $hmax){ $target_file = "../user/$log_username/$db_file_name"; $resized_file = "../user/$log_username/$db_file_name"; img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt); } $sql = "INSERT INTO photos(user, gallery, filename, uploaddate) VALUES ('$log_username','$gallery','$db_file_name',now())"; $query = mysqli_query($db_conx, $sql); mysqli_close($db_conx); header("location: ../photos.php?u=$log_username"); exit(); } ?><?php if (isset($_POST["delete"]) && $_POST["id"] != ""){ $id = preg_replace('#[^0-9]#', '', $_POST["id"]); $query = mysqli_query($db_conx, "SELECT user, filename FROM photos WHERE id='$id' LIMIT 1"); $row = mysqli_fetch_row($query); $user = $row[0]; $filename = $row[1]; if($user == $log_username){ $picurl = "../user/$log_username/$filename"; if (file_exists($picurl)) { unlink($picurl); $sql = "DELETE FROM photos WHERE id='$id' LIMIT 1"; $query = mysqli_query($db_conx, $sql); } } mysqli_close($db_conx); echo "deleted_ok"; exit(); } ?> user.php <?php include_once("php_includes/check_login_status.php"); // Initialize any variables that the page might echo $u = ""; $sex = "Male"; $userlevel = ""; $profile_pic = ""; $profile_pic_btn = ""; $avatar_form = ""; $country = ""; $joindate = ""; $lastsession = ""; // Make sure the _GET username is set, and sanitize it if(isset($_GET["u"])){ $u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']); } else { header("location: http://www.webintersect.com"); exit(); } // Select the member from the users table $sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1"; $user_query = mysqli_query($db_conx, $sql); // Now make sure that user exists in the table $numrows = mysqli_num_rows($user_query); if($numrows < 1){ echo "That user does not exist or is not yet activated, press back"; exit(); } // Check to see if the viewer is the account owner $isOwner = "no"; if($u == $log_username && $user_ok == true){ $isOwner = "yes"; $profile_pic_btn = '<a href="#" onclick="return false;" onmousedown="toggleElement(\'avatar_form\')">Toggle Avatar Form</a>'; $avatar_form = '<form id="avatar_form" enctype="multipart/form-data" method="post" action="php_parsers/photo_system.php">'; $avatar_form .= '<h4>Change your avatar</h4>'; $avatar_form .= '<input type="file" name="avatar" required>'; $avatar_form .= '<p><input type="submit" value="Upload"></p>'; $avatar_form .= '</form>'; } // Fetch the user row from the query above while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) { $profile_id = $row["id"]; $gender = $row["gender"]; $country = $row["country"]; $userlevel = $row["userlevel"]; $avatar = $row["avatar"]; $signup = $row["signup"]; $lastlogin = $row["lastlogin"]; $joindate = strftime("%b %d, %Y", strtotime($signup)); $lastsession = strftime("%b %d, %Y", strtotime($lastlogin)); } if($gender == "f"){ $sex = "Female"; } $profile_pic = '<img src="user/'.$u.'/'.$avatar.'" alt="'.$u.'">'; if($avatar == NULL){ $profile_pic = '<img src="images/avatardefault.jpg" alt="'.$user1.'">'; } ?><?php $isFriend = false; $ownerBlockViewer = false; $viewerBlockOwner = false; if($u != $log_username && $user_ok == true){ $friend_check = "SELECT id FROM friends WHERE user1='$log_username' AND user2='$u' AND accepted='1' OR user1='$u' AND user2='$log_username' AND accepted='1' LIMIT 1"; if(mysqli_num_rows(mysqli_query($db_conx, $friend_check)) > 0){ $isFriend = true; } $block_check1 = "SELECT id FROM blockedusers WHERE blocker='$u' AND blockee='$log_username' LIMIT 1"; if(mysqli_num_rows(mysqli_query($db_conx, $block_check1)) > 0){ $ownerBlockViewer = true; } $block_check2 = "SELECT id FROM blockedusers WHERE blocker='$log_username' AND blockee='$u' LIMIT 1"; if(mysqli_num_rows(mysqli_query($db_conx, $block_check2)) > 0){ $viewerBlockOwner = true; } } ?><?php $friend_button = '<button disabled>Request As Friend</button>'; $block_button = '<button disabled>Block User</button>'; // LOGIC FOR FRIEND BUTTON if($isFriend == true){ $friend_button = '<button onclick="friendToggle(\'unfriend\',\''.$u.'\',\'friendBtn\')">Unfriend</button>'; } else if($user_ok == true && $u != $log_username && $ownerBlockViewer == false){ $friend_button = '<button onclick="friendToggle(\'friend\',\''.$u.'\',\'friendBtn\')">Request As Friend</button>'; } // LOGIC FOR BLOCK BUTTON if($viewerBlockOwner == true){ $block_button = '<button onclick="blockToggle(\'unblock\',\''.$u.'\',\'blockBtn\')">Unblock User</button>'; } else if($user_ok == true && $u != $log_username){ $block_button = '<button onclick="blockToggle(\'block\',\''.$u.'\',\'blockBtn\')">Block User</button>'; } ?><?php $friendsHTML = ''; $friends_view_all_link = ''; $sql = "SELECT COUNT(id) FROM friends WHERE user1='$u' AND accepted='1' OR user2='$u' AND accepted='1'"; $query = mysqli_query($db_conx, $sql); $query_count = mysqli_fetch_row($query); $friend_count = $query_count[0]; if($friend_count < 1){ $friendsHTML = $u." has no friends yet"; } else { $max = 18; $all_friends = array(); $sql = "SELECT user1 FROM friends WHERE user2='$u' AND accepted='1' ORDER BY RAND() LIMIT $max"; $query = mysqli_query($db_conx, $sql); while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($all_friends, $row["user1"]); } $sql = "SELECT user2 FROM friends WHERE user1='$u' AND accepted='1' ORDER BY RAND() LIMIT $max"; $query = mysqli_query($db_conx, $sql); while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($all_friends, $row["user2"]); } $friendArrayCount = count($all_friends); if($friendArrayCount > $max){ array_splice($all_friends, $max); } if($friend_count > $max){ $friends_view_all_link = '<a href="view_friends.php?u='.$u.'">view all</a>'; } $orLogic = ''; foreach($all_friends as $key => $user){ $orLogic .= "username='$user' OR "; } $orLogic = chop($orLogic, "OR "); $sql = "SELECT username, avatar FROM users WHERE $orLogic"; $query = mysqli_query($db_conx, $sql); while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { $friend_username = $row["username"]; $friend_avatar = $row["avatar"]; if($friend_avatar != ""){ $friend_pic = 'user/'.$friend_username.'/'.$friend_avatar.''; } else { $friend_pic = 'images/avatardefault.jpg'; } $friendsHTML .= '<a href="user.php?u='.$friend_username.'"><img class="friendpics" src="'.$friend_pic.'" alt="'.$friend_username.'" title="'.$friend_username.'"></a>'; } } ?><?php $coverpic = ""; $sql = "SELECT filename FROM photos WHERE user='$u' ORDER BY RAND() LIMIT 1"; $query = mysqli_query($db_conx, $sql); if(mysqli_num_rows($query) > 0){ $row = mysqli_fetch_row($query); $filename = $row[0]; $coverpic = '<img src="user/'.$u.'/'.$filename.'" alt="pic">'; } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title><?php echo $u; ?></title> <link rel="icon" href="favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="style/style.css"> <style type="text/css"> div#profile_pic_box{float:right; border:#999 2px solid; width:200px; height:200px; margin:20px 30px 0px 0px; overflow-y:hidden;} div#profile_pic_box > img{z-index:2000; width:200px;} div#profile_pic_box > a { display: none; position:absolute; margin:140px 0px 0px 120px; z-index:4000; background:#D8F08E; border:#81A332 1px solid; border-radius:3px; padding:5px; font-size:12px; text-decoration:none; color:#60750B; } div#profile_pic_box > form{ display:none; position:absolute; z-index:3000; padding:10px; opacity:.8; background:#F0FEC2; width:180px; height:180px; } div#profile_pic_box:hover a { display: block; } div#photo_showcase{float:right; background:url(style/photo_showcase_bg.jpg) no-repeat; width:136px; height:127px; margin:20px 30px 0px 0px; cursor:pointer;} div#photo_showcase > img{width:74px; height:74px; margin:37px 0px 0px 9px;} img.friendpics{border:#000 1px solid; width:40px; height:40px; margin:2px;} </style> <script src="js/main.js"></script> <script src="js/ajax.js"></script> <script type="text/javascript"> function friendToggle(type,user,elem){ var conf = confirm("Press OK to confirm the '"+type+"' action for user <?php echo $u; ?>."); if(conf != true){ return false; } _(elem).innerHTML = 'please wait ...'; var ajax = ajaxObj("POST", "php_parsers/friend_system.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText == "friend_request_sent"){ _(elem).innerHTML = 'OK Friend Request Sent'; } else if(ajax.responseText == "unfriend_ok"){ _(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $u; ?>\',\'friendBtn\')">Request As Friend</button>'; } else { alert(ajax.responseText); _(elem).innerHTML = 'Try again later'; } } } ajax.send("type="+type+"&user="+user); } function blockToggle(type,blockee,elem){ var conf = confirm("Press OK to confirm the '"+type+"' action on user <?php echo $u; ?>."); if(conf != true){ return false; } var elem = document.getElementById(elem); elem.innerHTML = 'please wait ...'; var ajax = ajaxObj("POST", "php_parsers/block_system.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText == "blocked_ok"){ elem.innerHTML = '<button onclick="blockToggle(\'unblock\',\'<?php echo $u; ?>\',\'blockBtn\')">Unblock User</button>'; } else if(ajax.responseText == "unblocked_ok"){ elem.innerHTML = '<button onclick="blockToggle(\'block\',\'<?php echo $u; ?>\',\'blockBtn\')">Block User</button>'; } else { alert(ajax.responseText); elem.innerHTML = 'Try again later'; } } } ajax.send("type="+type+"&blockee="+blockee); } </script> </head> <body> <?php include_once("template_pageTop.php"); ?> <div id="pageMiddle"> <div id="profile_pic_box" ><?php echo $profile_pic_btn; ?><?php echo $avatar_form; ?><?php echo $profile_pic; ?></div> <div id="photo_showcase" onclick="window.location = 'photos.php?u=<?php echo $u; ?>';" title="view <?php echo $u; ?>&#39;s photo galleries"> <?php echo $coverpic; ?> </div> <h2><?php echo $u; ?></h2> <p>Is the viewer the page owner, logged in and verified? <b><?php echo $isOwner; ?></b></p> <p>Gender: <?php echo $sex; ?></p> <p>Country: <?php echo $country; ?></p> <p>User Level: <?php echo $userlevel; ?></p> <p>Join Date: <?php echo $joindate; ?></p> <p>Last Session: <?php echo $lastsession; ?></p> <hr /> <p>Friend Button: <span id="friendBtn"><?php echo $friend_button; ?></span> <?php echo $u." has ".$friend_count." friends"; ?> <?php echo $friends_view_all_link; ?></p> <p>Block Button: <span id="blockBtn"><?php echo $block_button; ?></span></p> <hr /> <p><?php echo $friendsHTML; ?></p> <hr /> <p><?php //include_once("template_status.php"); ?></p> </div> <?php include_once("template_pageBottom.php"); ?> </body> </html>