PHP - Outputting Thumbnail Image Links Gallery
Hi, I am trying to make a simple thumbnail gallery where you upload an image, the image gets resized, a thumbnail is created in the "images/small/" directory, and the main images are in the "images/" directory.
I need to somehow read from both directories, and do an image link with the thumbnail linking to the larger image. I think that means displaying from two directories, I don't know how to do that, please any help greatly appreciated. Thank you. here is my code so far Code: [Select] <?php error_reporting(0); $change=""; $abc=""; define ("MAX_SIZE","400"); function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $errors=0; if($_SERVER["REQUEST_METHOD"] == "POST") { $image =$_FILES["file"]["name"]; $uploadedfile = $_FILES['file']['tmp_name']; if ($image) { $filename = stripslashes($_FILES['file']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $change='<div class="msgdiv">Unknown Image extension </div> '; $errors=1; } else { $size=filesize($_FILES['file']['tmp_name']); if ($size > MAX_SIZE*1024) { $change='<div class="msgdiv">You have exceeded the size limit!</div> '; $errors=1; } if($extension=="jpg" || $extension=="jpeg" ) { $uploadedfile = $_FILES['file']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); } else if($extension=="png") { $uploadedfile = $_FILES['file']['tmp_name']; $src = imagecreatefrompng($uploadedfile); } else { $src = imagecreatefromgif($uploadedfile); } echo $scr; list($width,$height)=getimagesize($uploadedfile); //**Original**// //$newwidth=60; //$newheight=($height/$width)*$newwidth; //**Modified to use height instead of width**// //$newheight=350; //$newwidth=($width/$height)*$newheight; // **IF NOT resizing full image then just pass variables.**// $newheight=$height; $newwidth=$width; //***adjust tmp***// $tmp=imagecreatetruecolor($newwidth,$newheight); //Thumbs $newheight1=180; $newwidth1=($width/$height)*$newheight1; //**Original**// //$newwidth1=25; //$newheight1=($height/$width)*$newwidth1; $tmp1=imagecreatetruecolor($newwidth1,$newheight1); imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height); $filename = "images/". $_FILES['file']['name']; $filename1 = "images/small/". $_FILES['file']['name']; imagejpeg($tmp,$filename,100); imagejpeg($tmp1,$filename1,100); imagedestroy($src); imagedestroy($tmp); imagedestroy($tmp1); }} } //If no errors registred, print the success message if(isset($_POST['Submit']) && !$errors) { // mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'"); $change=' <div class="msgdiv">Image Uploaded Successfully!</div>'; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <meta content="en-us" http-equiv="Content-Language"> <title>picture demo</title> <link href=".css" media="screen, projection" rel="stylesheet" type="text/css"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" src="js/jquery_002.js"></script> <script type="text/javascript" src="js/displaymsg.js"></script> <script type="text/javascript" src="js/ajaxdelete.js"></script> <style type="text/css"> .help { font-size:11px; color:#006600; } body { color: #000000; background-color:#999999 ; background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left; font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; } .msgdiv{ width:759px; padding-top:8px; padding-bottom:8px; background-color: #fff; font-weight:bold; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px; } #container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF } </style> </head><body> <div align="center" id="err"> <?php echo $change; ?> </div> <div id="space"></div> <div id="container" > <div id="con"> <table width="502" cellpadding="0" cellspacing="0" id="main"> <tbody> <tr> <td width="500" height="238" valign="top" id="main_right"> <div id="posts"> <img src="<?php echo $filename; ?>" /> <img src="<?php echo $filename1; ?>" /> <form method="post" action="" enctype="multipart/form-data" name="form1"> <table width="500" border="0" align="center" cellpadding="0" cellspacing="0"> <tr><Td style="height:25px"> </Td></tr> <tr> <td width="150"><div align="right" class="titles">Picture : </div></td> <td width="350" align="left"> <div align="left"> <input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/> </div></td> </tr> <tr><Td></Td> <Td valign="top" height="35px" class="help">Image maximum size <b>400 </b>kb</span></Td> </tr> <tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value=" Upload " name="Submit"/></Td></tr> <tr> <td width="200"> </td> <td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="200" align="center"><div align="left"></div></td> <td width="100"> </td> </tr> </table></td> </tr> </table> </form> </div> </td> </tr> </tbody> </table> </div> </div> </body></html> Similar TutorialsHi I am trying to build a site which has an image gallery with links on it. I want to list the the images in different ways and I have successfully made it work with a "shuffle"-script like this: Code: [Select] <?php $links[] = Array("../r/ahlens.html", "k/k.jpg"); $links[] = Array("../r/brothers.html", "k/k.jpg"); $links[] = Array("../r/hm.html", "k/k.jpg"); $links[] = Array("../r/kappahl.html", "k/k.jpg"); $links[] = Array("../r/mq.html", "k/k.jpg"); $links[] = Array("sida1.php", "k/l.jpg"); $links[] = Array("../r/kappahl.html", "k/k.jpg"); $links[] = Array("../r/mq.html", "k/k.jpg"); $links[] = Array("../r/nk.html", "k/k.jpg"); shuffle($links); foreach($links as $link){ echo "<a href=\"${link[0]}\" ><img src=\"${link[1]}\" class=\"randomImage\" /></a> "; } ?> It works fine and opens a new page when clicked. Now I would like to make it listed by file name instead of shuffling. How do I do that without loosing the links? And can it be done with a Directory because there will be a lot more photos in the future? (I would also like the link to pages to be opened in a nice popup. Can I implement that?) Thanks in advance! The script for creating a new file name for the image:
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of imageThe script creates a new file like: f6c9b8d9db05366c3504210cded9ddb2.jpgand moves the file to the "uploads" folder. And then the script also creates a thumbnail with the same file name and moves the file to the "thumbs" folder. The issue I am having is that the same ID code could happen again for a different image in the database, thus I would be calling a different original sized image than the thumbnail image. My question is: How to avoid this issue of the same ID code has happened again for a different file. What is the proper way to reference the anchor tag of the thumbnail image to its actual original sized image? With the script I have the thumbnail image would be coming from the "thumbs" folder and the anchor tag would get referenced to the "uploads" folder to get the original sized image. Edited by glassfish, 12 October 2014 - 05:51 AM. Hi, It's been a while since I've been on here... I've got a script that takes an image url and resizes it, then outputs it to the screen (using image headers etc). I've then got a htaccess file that changes my nice url, such as: 'images/thumb/50-70/logo.jpg' to: 'incudes/resize.php?width=50&height=70&img=logo.jpg' Which is the resize script, so I can use a nice url in img tags. The width and height are just the maximum allowed, so sometime the image will be smaller. Now, this all works correctly, but I am now trying to find out the width and height of the thumbnailed image, from outside of the resize.php script. I thought that I could use getimagesize, but this doesn't seem to work... I first tried it using the 'nice' url: '/images/thumb/50-70/logo.jpg' Thinking that .htaccess would re-direct, but no. I then tried a direct link to the resize file: '/incudes/resize.php?width=50&height=70&img=logo.jpg' But that returns a file not found error... Although I can access the file directly. Trying the direct url without the get variables, however, successfully finds the file, but it doesn't seem to be able to detect the image dimensions. I just get a blank result.. Is PHP able to recognise htaccess re-directs? Is PHP able to parse a php file that outputs as an image? (I have all the correct headers etc set!) Thanks Hi! my code uploads an image and saves it to an upload folder, but I want to create a thumbnail of it. For example, if I upload a 1400x1000 JPG, I would like to resize the image and it has to respect the proportion given a maximum size. if I say the maximum width/height is 250px, the image should be thumbnailed according to the max height/width, and in proportion with the width/height Thanks in advance Fernando Help me I am getting Notice: Undefined index: extension Im trying to write an image upload script which checks various elements of the image and then saves it and and a thumbnail into a folder. At the moment I am getting a white screen which makes me think I have a syntax error so I have come here to find some fresh eyes to help me out. Can anyone see any reason why this wouldn't be working? Form Code: [Select] <form enctype='multipart/form-data' action='upload_image.php' method='POST'> <table class='uploads-form'> <tr> <td><input name='image' type='file' /><input type='hidden' name'MAX_FILE_SIZE' value='5000000' /></td> </tr> <tr> <td><input type='submit' name='upload_image' value='Upload' /></td> </tr> </table> </form> php <?php error_reporting(E_ALL); ini_set("display_errors", 1); $images_location = "project_files/"; $thumbs_location = "project_thumbs/"; $thumb_width = "100"; $maximum_size = "5000000"; //Auto Thumbnail Function function create_thumbnail($source,$destination, $thumb_width) { $size = getimagesize($source); $width = $size[0]; $height = $size[1]; $x = 0; $y = 0; if($width> $height) { $x = ceil(($width - $height) / 2 ); $width = $height; } elseif($height> $width) { $y = ceil(($height - $width) / 2); $height = $width; } $new_image = imagecreatetruecolor($thumb_width,$thumb_width) or die('Cannot initialize new GD image stream'); $extension = get_image_extension($source); if($extension=='jpg' || $extension=='jpeg') $image = imagecreatefromjpeg($source); if($extension=='gif') $image = imagecreatefromjpeg($source); if($extension=='png') $image = imagecreatefromjpeg($source); imagecopyresampled($new_image,$image,0,0,$x,$y,$thumb_width,$thumb_width,$width,$height); if($extension=='jpg' || $extension=='jpeg') imagejpeg($new_image,$destination); if($extension=='gif') $imagegif($new_image,$destination); if($extension=='png') imagepng($new_image,$destination); } //Get Extension Function function get_image_extension($name) { $name = strtolower($name); $i = strrpos($name,"."); if (!$i) { return ""; } $l = strlen($name) - $i; $extension = substr($name,$i+1,$l); return $extension; } //Random Name Function function random_name($length) { $characters = "abcdefghijklmnopqrstuvwxyz01234567890"; $name = ""; for ($i = 0; $i < $length; $i++) { $name .= $character[mt_rand(0, strlen($characters) - 1)]; } return "image-".$name; } //Check And Save Image if(isset($_POST['upload_image'])) { if($_FILES['image']['name'] == ""){ echo = "Please select the image you would like to upload by clicking browse"; } else{ $size=filesize($_FILES['image']['tap_name']); $filename = stripslashes($_FILES['image']['name']); $extension = get_image_extension($filename); if($size > $maximum_size) { echo = "Your file size exceeds the maximum file size!"; } else if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { echo = "Only the following extensions are allowed. 'jpg', 'jpeg', 'png', 'gif'."; } else { $image_random_name=random_name(15).".".$extension; $copy = @copy($_FILES['image']['tmp_name'], $images_location.$image_random_name); if (!$copy) { echo = "Error while uploadin your image! Please try again!"; } else{ create_thumbnail($images_location.$image_random_name,$thumbs_location.$image_random_name, $thumb_width); echo = "Your image has been uploaded!"; } } } } ?> Hi, I have a script that uploads an image to a directory and then saves the fill path to a field in a table for later use. The only problem is people are uploading huge images and then when I produce a catalogue of my listings it takes forever to load because the images are so big. What I am after is an add in script to create an ADDITIONAL image 100 x 75px, I don't really want to change my upload script. Any ideas? Thanks in advace. Here is what I have: Code: [Select] <?php $idir = "../fleet/"; // Path To Images Directory if (isset ($_FILES['fupload'])){ //upload the image to tmp directory $url = $_FILES['fupload']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload']['type'] == "image/jpg" || $_FILES['fupload']['type'] == "image/jpeg" || $_FILES['fupload']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload']['name'], '$account.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload']['tmp_name'], "$idir" . $_FILES['fupload']['name']); // Move Image From Temporary Location To Perm } } $fleetimage1 = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); //then insert sql code below... ?> I have a form where you can enter a image url and it's title. It calls display.php which displays the image as well as the title. But I want the image to be displayed as a thumbnail of size 150X100. Do i have to store it in directory before I convert it and display? If so, can somebody tell me how to convert the image into a thumbnail? Here is my code: Code: [Select] <table align="center" bgcolor="silver"> <form action="display.php" method ="post"> <tr> <td align="center"><b><font color="#214754" size="3">Reg</font></b></td> </tr> <tr> <td> Title: </td> <td><input type="text" size ="40" name="registry_title1" /></td> </tr> <tr> <td> Image URL: </td> <td><input type="text" size ="40" name="registry_img1" /></td> </tr> <tr> <td> <input type="submit" name="submit" value="submit" /> </td> </tr> </form> </table> </div> here is the code for display.php Code: [Select] <? /* Get Registry details */ $registry_img1=$_POST['registry_img1']; $registry_title1=stripslashes($_POST['registry_title1']); ?> <html> <body> <table width='600' cellspacing='0' cellpadding='0' border='0' bgcolor='#ffffff' align='center'> <tr> <td style='padding-bottom:8px';><font style='font-size:18px;color:rgb(0, 0, 0);text-decoration:none'><a style='font-size:18px;color:rgb(0, 0, 0);text-decoration:none' href='#'><? echo ucfirst($url); ?> Registry</font></a></td> </tr> <tr> <td style='padding-bottom:10px;'> <a style='color:rgb(206, 0, 0);font-size:14px;font-weight:bold;line-height:18px;text-decoration:none' href='<? echo $registry_url1; ?>' target='_blank'><img style='padding-right:10px' border='0' align='left' alt='' src='<? echo $registry_img1; ?>'><? echo $registry_title1;?> </a> </td> </table> </body> </html> I am working on an uploader and slowly getting it working, I am uploading 3 images at once, and setting arrays for each one as keys, with an increment of ++1. I am wanting to resize the image before it gets copied to the thumbnail folder. I have this code.
Everything works with it. As you see, I started on getting the file info, but after that I am totally stuck on what to do after to resize the image proportionally with a maximum width of xPX and height to match it without looking distorted. Any help would be really appreciated. Thank You. I am working on a simple gallery. I want to have an option to download full scale image without users having to right click and "save as". Using this code you get a image preview: <a href="pictures/img-(1).jpg"><img src="thumbnails/img-(1).jpg"></a> How can I modify it so when user clicks on thumbnail of image 1 it will prompt him to save the image instead of viewing it. Thanks Greetings, What I'm trying to do is have users upload their event information into a database which would include a flyer. I don't want the image file to go into the database (other than the filename) rather I'd like it to be dropped into a directory. In the same script I'd like to dynamically generate a thumbnail. I have the two scripts and separately they work fine, but I can't get them to work together. I'm guessing the conflict because the thumbnail script is using $_POST and the mysql script is using $_SESSION. If so how can I modify them to both use $_SESSION? The thumbnail script is goes from line 1 - 146 and the mysql portion is the rest. The results of processing this look something like this. QUERY TEXT: INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) VALUES ('12', 'spooky times', 'Ironwood Stage & Grill', '2010-12-17 22:36:00', 'DNB', '5000', 'me', '174366-1.jpg') <?php $debug = FALSE; /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "../include/session_init.php"); $arVal = array(); require_once("../include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $conn = mysql_connect($_SESSION['MYSQL_SERVER1'],$_SESSION['MYSQL_LOGIN1'],$_SESSION['MYSQL_PASS1']) or die ('Error connecting to mysql'); mysql_select_db($_SESSION['MYSQL_DB1']) or die("Unable to select database"); $eventgenre_sel = addslashes($_REQUEST['eventgenre_sel']); $eventname = addslashes($_REQUEST['eventname']); $eventvenue = addslashes($_REQUEST['eventvenue']); $eventdate = addslashes($_REQUEST['eventdate']); $eventgenre = addslashes($_REQUEST['eventgenre']); $eventprice = addslashes($_REQUEST['eventprice']); $eventpromoter = addslashes($_REQUEST['eventpromoter']); $eventflyer = addslashes($_REQUEST['eventflyer']); $sqlquery = "INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) " ."VALUES ('$eventgenre_sel', '$eventname', '$eventvenue', '$eventdate', '$eventgenre', '$eventprice', '$eventpromoter', '$eventflyer')"; echo 'QUERY TEXT:<br />'.$sqlquery; $result = MYSQL_QUERY($sqlquery); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: /user_registration.php".$flags); exit; } mysql_close($conn); ?> Hi guys, Just after a bit of advice really. I want to create an image gallery. Currently, my images (which are sourced from a DB) are brought about in a loop and set in their own div, side by side. I was just thinking though: would it be better to do this with an array? Its a bit difficult coding for this just using the basic loop. Anyone have any suggestions to make this better? PS, here is my current code: $sql = "SELECT * FROM imagegal"; if ($result = mysql_query($sql)) { if (mysql_num_rows($result)) { while($row = mysql_fetch_array($result)){ echo '<span class="imagegal">'; echo '<span><img src="' . $row['image'] . '"</span>'; echo '</span>'; }}} Hi All, I am looking for a php script that i can use to create a php image gallery for a client. The script needs to allow the client to upload an image (any image type) jpg,gif,png etc and then a thumbnail needs to be created.So there will be two images the original and the thumbnail which should be stored in separate directories. I know that this has been done before and i did some google searches ,but cant find anything that i need. Thanks in advance. Kind Regards, Nathan how to create php gallery with pagination and also add new images that control by admin
hello experts ! im new to php script, hope u guys able to help. thanks in advance . I'm following a tutorial from this site: http://www.anyexample.com/programming/php/php_mysql_example__image_gallery_(blob_storage).xml and i run the code, error occur (i highlighted line 27) : Parse error: syntax error, unexpected T_STRING in C:\xampp\htdocs\testing.php on line 27 This is my php script: <?php $db_host = 'localhost'; // don't forget to change $db_user = 'root'; $db_pwd = '123456'; $database = 'test'; $table = 'ae_gallery'; // use the same name as SQL table $password = '123'; // simple upload restriction, // to disallow uploading to everyone ////create sql-table CREATE TABLE 'ae_gallery' ( 'id' int(11) NOT NULL AUTO_INCREMENT, 'title' varchar(64) character SET utf8 NOT NULL, 'ext' varchar( 8 ) character SET utf8 NOT NULL, 'image_time' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 'data' mediumblob NOT NULL, PRIMARY KEY (`id`) ); if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($ae_gallery)) die("Can't select database"); // This function makes usage of // $_GET, $_POST, etc... variables // completly safe in SQL queries function sql_safe($s) { if (get_magic_quotes_gpc()) $s = stripslashes($s); return mysql_real_escape_string($s); } // If user pressed submit in one of the forms if ($_SERVER['REQUEST_METHOD'] == 'POST') { // cleaning title field $title = trim(sql_safe($_POST['title'])); if ($title == '') // if title is not set $title = '(empty title)';// use (empty title) string if ($_POST['password'] != $password) // cheking passwors $msg = 'Error: wrong upload password'; else { if (isset($_FILES['photo'])) { @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']); // Get image type. // We use @ to omit errors if ($imtype == 3) // cheking image type $ext="png"; // to use it later in HTTP headers elseif ($imtype == 2) $ext="jpeg"; elseif ($imtype == 1) $ext="gif"; else $msg = 'Error: unknown file format'; if (!isset($msg)) // If there was no error { $data = file_get_contents($_FILES['photo']['tmp_name']); $data = mysql_real_escape_string($data); // Preparing data to be used in MySQL query mysql_query("INSERT INTO {$table} SET ext='$ext', title='$title', data='$data'"); $msg = 'Success: image uploaded'; } } elseif (isset($_GET['title'])) // isset(..title) needed $msg = 'Error: file not loaded';// to make sure we've using // upload form, not form // for deletion if (isset($_POST['del'])) // If used selected some photo to delete { // in 'uploaded images form'; $id = intval($_POST['del']); mysql_query("DELETE FROM {$table} WHERE id=$id"); $msg = 'Photo deleted'; } } } elseif (isset($_GET['show'])) { $id = intval($_GET['show']); $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(image_time), data FROM {$table} WHERE id=$id LIMIT 1"); if (mysql_num_rows($result) == 0) die('no image'); list($ext, $image_time, $data) = mysql_fetch_row($result); $send_304 = false; if (php_sapi_name() == 'apache') { // if our web server is apache // we get check HTTP // If-Modified-Since header // and do not send image // if there is a cached version $ar = apache_request_headers(); if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists ($ar['If-Modified-Since'] != '') && // not empty (strtotime($ar['If-Modified-Since']) >= $image_time)) // and grater than $send_304 = true; // image_time } if ($send_304) { // Sending 304 response to browser // "Browser, your cached version of image is OK // we're not sending anything new to you" header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304); exit(); // bye-bye } // outputing Last-Modified header header('Last-Modified: '.gmdate('D, d M Y H:i:s', $image_time).' GMT', true, 200); // Set expiration time +1 year // We do not have any photo re-uploading // so, browser may cache this photo for quite a long time header('Expires: '.gmdate('D, d M Y H:i:s', $image_time + 86400*365).' GMT', true, 200); // outputing HTTP headers header('Content-Length: '.strlen($data)); header("Content-type: image/{$ext}"); // outputing image echo $data; exit(); } ?> <html><head> <title>MySQL Image Gallery Example</title> </head> <body> <?php if (isset($msg)) // this is special section for // outputing message { ?> <p style="font-weight: bold;"><?=$msg?> <br> <a href="<?=$PHP_SELF?>">reload page</a> <!-- I've added reloading link, because refreshing POST queries is not good idea --> </p> <?php } ?> <h1><i>Image gallery</i></h1> <h2>Uploaded images:</h2> <form action="<?=$PHP_SELF?>" method="post"> <!-- This form is used for image deletion --> <?php $result = mysql_query("SELECT id, image_time, title FROM {$table} ORDER BY id DESC"); if (mysql_num_rows($result) == 0) // table is empty echo '<ul><li>No images loaded</li></ul>'; else { echo '<ul>'; while(list($id, $image_time, $title) = mysql_fetch_row($result)) { // outputing list echo "<li><input type='radio' name='del' value='{$id}'>"; echo "<a href='{$PHP_SELF}?show={$id}'>{$title}</a> – "; echo "<small>{$image_time}</small></li>"; } echo '</ul>'; echo '<label for="password">Password:</label><br>'; echo '<input type="password" name="password" id="password"><br><br>'; echo '<input type="submit" value="Delete selected">'; } ?> </form> <h2>Upload new image:</h2> <form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data"> <label for="title">Title:</label><br> <input type="text" name="title" id="title" size="64"><br><br> <label for="photo">Photo:</label><br> <input type="file" name="photo" id="photo"><br><br> <label for="password">Password:</label><br> <input type="password" name="password" id="password"><br><br> <input type="submit" value="upload"> </form> The code below works well and shows all the images in a folder in reverse chronological order. But I want to limit it to a certain number of images . This would enable me to have several pages of images. So the first page would display the latest 50 images, the second page would show 50-100, and the third, 100-150. Any helps on how to modify? I can create the pages manually. I just want to know how to limit the current page to a certain range. Code: [Select] <?php //Your folder $files = glob("images/*.*"); function sortnewestfilesfirst($a, $b) { return filemtime($b) - filemtime($a); } usort($files, "sortnewestfilesfirst"); $colCnt=0; echo '<table border="0" style="width:1000px;">'; for ($i=0; $i<count($files); $i++) { $colCnt++; if ($colCnt==1) echo '<tr>'; echo '<td width="20%" style="font-size:8.5px; font-family:arial">'; $num = $files[$i]; echo ' <div class="ImgBorder"> <div class="clipout"> <div class="clipin"> <a href="' . $num . '" rel="lightbox[all]"><img class="thumb ImgBorder" src="'.$num.'"> </a> </div> </div></div>'." "; echo '</td>'; if ($colCnt==6) { echo '</tr>'; $colCnt=0; } } echo '</table>'; ?> Lets say ive got a function like this one Code: [Select] function getPictures() { global $max_width, $max_height; if ( $handle = opendir(".") ) { $lightbox = rand(); echo '<ul id="pictures">'; while ( ($file = readdir($handle)) !== false ) { if ( !is_dir($file) ) { $split = explode('.', $file); $ext = $split[count($split) - 1]; if ( ($type = getPictureType($ext)) == '' ) { continue; } if ( ! is_dir('thumbs') ) { mkdir('thumbs'); } if ( ! file_exists('thumbs/'.$file) ) { if ( $type == 'jpg' ) { $src = imagecreatefromjpeg($file); } else if ( $type == 'png' ) { $src = imagecreatefrompng($file); } else if ( $type == 'gif' ) { $src = imagecreatefromgif($file); } if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) { $newW = $oldW * ($max_width / $oldH); $newH = $max_height; } else { $newW = $max_width; $newH = $oldH * ($max_height / $oldW); } $new = imagecreatetruecolor($newW, $newH); imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH); if ( $type == 'jpg' ) { imagejpeg($new, 'thumbs/'.$file); } else if ( $type == 'png' ) { imagepng($new, 'thumbs/'.$file); } else if ( $type == 'gif' ) { imagegif($new, 'thumbs/'.$file); } imagedestroy($new); imagedestroy($src); } echo '<li><a href="'.$file.'" rel="lightbox['.$lightbox.']">'; echo '<img src="thumbs/'.$file.'" alt="" />'; echo '</a></li>'; } } echo '</ul>'; } }What it does is: It checks for files(images) in a directory, check for file types jpg, png or gif cuz I work on gd library and it supports only these 3 type of images and make thumbnails. My problem is I cant change the directory of images, after I do that I just got error or it doesnt read images at all. I tried Code: [Select] $dir = "/galerija/"; if ( $handle = opendir($dir) ) But nothing happens, it just leaves me blank space(as I said above it doesnt read images at all) Hi, I have a game image gallery using arrays to hold the current images, and when you go to a new location, like "newLocation=2" , it goes to a new array of background images. The problem is, when I try it in my browser, and I put in a new array of image for like, "location 2", The image doesn't show up, the images from location 1 show up. This is driving me nuts because I want to start adding content to the zones of my game already.LOL!. If anyone can help please I'd be very grateful. Thank you. Derek ok, here is the code to the page, I only included the parts of the page that are relevant to what I am talking about. Code: [Select] <?php session_start(); //$currentBackground=''; $echoLocation=''; $player=''; $monsters=''; $_SESSION['player'] = $player;// set this right after they log in, run this once, eventually in database. $_SESSION['monsters']=$monsters; $currentMonsterLevel='';//get rid of this eventually and put in session variable cuz we use it on other pages. $currentPlayerLevel=''; $error=''; $playerHp='';//get rid and make session var. $monsterHp=''; $echoPlayerMana=''; $echoMonster=''; $echoSpell=''; $player=''; $monsters=''; $playerMessage=''; $monsterMessage=''; $currentPLayerLevel =''; } } ////////////////////////////////////////////////////////////////////////////////// /////////////////////////////GAME NAVIGATION AND MONSTER SEARCH CODE NOT FINISHED////////////////////////////////// $locations[0] = array(); $locations[1] = array( 'background_images' => array( "<img src='sundragon_environments/ocean/ocean1_FRAME.jpg'/>", "<img src='sundragon_environments/ocean/ocean1_FRAME2.jpg'/>", "<img src='sundragon_environments/ocean/ocean1_FRAME3.jpg'/>", "<img src='sundragon_environments/ocean/ocean1_FRAME4.jpg'/>", "<img src='sundragon_environments/ocean/ocean1_FRAME5.jpg'/>" ), 'monster_images' => array( "<img src='sundragon_monsters_source/water/goldfish/goldfish.png'/>", "<img src='sundragon_monsters_source/water/eel/eel_transp_FRAME.png '/>", "<img src='sundragon_monsters_source/water/shark/shark_transp_FRAME.png'/>", "<img src='sundragon_monsters_source/water/octalisk/octalisk_transp_FRAME.png'/>", "<img src='sundragon_monsters_source/water/teardrop_ocean_protector/teardrop_ocean_protector.png'/>" ) ); $locations[2] = array( 'backgroundImages' => array( "<img src='sundragon_environments/shore/teardrop_shore/teardrop_shore.jpg'/>" ), 'monster_images' => array( "<img src='sundragon_monsters_source/water/goldfish/goldfish.png'/>" ) ); if(isset($_GET['newLocation'])) { $_SESSION['current_location']=$_GET['newLocation']; } if(!isset($_SESSION['current_location']) && !isset($_SESSION['current_background']) && !isset($_SESSION['currentMonster'])) { $_SESSION['current_location'] = 0; $_SESSION['current_monster'] = 0; $_SESSION['current_background'] = 0; } if($_SESSION['current_location'] != 0) { if(!isset($_SESSION['current_background']) && !isset($_SESSION['current_monster'])) { $_SESSION['current_monster'] = 0; $_SESSION['current_background'] = 0; } if(isset($_GET['further'])) { //below is- inside the locations array, teardrop ocean (1) the background image is 4(example)+1 is set, then //do this if(isset($locations[$_SESSION['current_location']]['background_images'][$_SESSION['current_background']+1])) { $_SESSION['current_background']+=1; } if(isset($locations[$_SESSION['current_location']]['monster_images'][$_SESSION['current_monster']+1])) { $_SESSION['current_monster']+=1; } } elseif(isset($_GET['back'])) { if(isset($locations[$_SESSION['current_location']]['background_images'][$_SESSION['current_background']-1])) { $_SESSION['current_background']-=1; } if(isset($locations[$_SESSION['current_location']]['monster_images'][$_SESSION['current_monster']-1])) { $_SESSION['current_monster']-=1; } } $currentBackground=$_SESSION['background'][$_SESSION['current_background']]; $currentMonster=$_SESSION['monster'][$_SESSION['current_monster']]; } else { //?newLocation=1 means set it to Teardrop ocean. $currentBackground = ' <img src="aradia.jpg" width="256" height="328" border="0" usemap="#Map" /> <map name="Map" id="Map"> <area shape="rect" coords="5,176,81,249" href="?newLocation=1"/> </map>'; $currentMonster = ''; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Realm of the Sun Dragon</title> <link rel="stylesheet" type="text/css" href="css/gamestyles.css"> <style type="text/css"> body { margin-top:-32px; padding:0; color: gold; } table { color: black; } .style8 {color: #000000} </style> </head> <body oncontextmenu="return false;"> <div id="container"> <div id="monster_message"> <?php echo "this is the monster battle and NPC talk window";?> </div> <div id="currentWeapon"> <img src="sundragon_interface_template/items/swords/sword_shrunk.png" width="190" height="65" /> </div> <div id="iframe_player_top_lft" > <div id="left_player_stats"><table align="center" width="30" border="0"> <tr> <td><strong>HP</strong></td> <td><strong><font color="red"><?php echo $playerHp;?></font></strong></td> </tr> <tr> <td><strong>MANA</strong></td> <td><strong><font color="green"><?php echo $echoPlayerMana;?></font></td> </tr> <tr> <td><strong>EXP</strong></td> <td><strong><font color="blue">999</font></strong></td> </tr> <tr> <td><strong>PLAT</strong></td> <td><strong><font color="white">999</font></strong></td> </tr> </table></div> <p> </p> <p> </p> <p> </p> <p align="center"><strong><br /> <span class="style8">Octalisk (Level <?php echo $currentMonsterLevel;?>) </span></strong> <br/> <strong><span class="style8">HP</span><font color="red"> <?php echo $monsterHp;?></font></strong> </p> <div id="spelleffectsleft" > <div class="divcenter"> <div align="center"> <div class="inline"> <div align="center">spell</div> </div> <div class="inline"> <div align="center">spell</div> </div> <div class="inline"> <div align="center">spell</div> </div> </div> </div> <!--end divcenter--> </div><!--end spell effects--> <div id="bottomspellsleft" > <div class="divcenter"> <div class="inline"> <div align="center">spell</div> </div> <div class="inline"> <div align="center">spell</div> </div> <div class="inline"> <div align="center">spell</div> </div> </div> <!--end div center--> </div><!--end bottomspells--> </div><!-- end player div--> <div id="iframe_spell_foreground"><?php echo $echoSpell;?></div> <div id="iframe_monster_background"><?php echo $currentBackground;?></div> <div id="iframe_transparent_monster"><?php echo $currentMonster;?></div> <!--not here--> <div id="iframe_player_top_right" > <table width="160" height="64" border="0" align= "center"> <tr> <td width="160"><div align="center"> <p><strong><br /> Silverglade (Level: <?php echo $currentPLayerLevel;?>)<br /> </strong></p> </div></td> </tr> </table> <div class="spelleffects" > <div class="divcenter"> <div class="inline"> <div align="center">spell</div> </div> <div class="inline"> <div align="center">spell</div> </div> <div class="inline"> <div align="center">spell</div> </div> </div> </div> <div class="bottomspells" > <div class="divcenter"> <div class="inline"> <div align="center">spell</div> </div> <div class="inline"> <div align="center">spell</div> </div> <div class="inline"> <div align="center">spell</div> </div> </div> </div> </div> <div id="iframe_chat_right"> the data from the chat message box will be output to this div</div> <!--not here--> <div id="iframe_player_center_bottom" align="center" ><div style="display: inline;"> <form style="display: inline; margin: 0;" ...> <form style="display: inline; margin: 0;" action='gamestart_NEWEST.php' method='post'><input type='submit' name='attack' value='Attack'/><input type="submit" name="search" value="search" /><input type="submit" value="cast spell" name="spell" /><input type="submit" name="inventory" value="Inventory"/></form> <form style="display: inline; margin: 0;" method="get" action=""><input type="submit" value="go further" name="further" /> <input type="submit"value="Go back" name="back"/></form> </form> </div> <div id="chat"> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <strong>Message:</strong> <textarea name="message"></textarea> <input type="submit" name="submit" value="Chat"> <input type="hidden" name="ip" value="<?php echo $_SERVER['REMOTE_ADDR']; ?>"> </form> </div></div></div> <!--not here--> <div id="log_off"> <a href="logout.php"><strong>LOG OFF</strong></a> </div> <!--not here--> </div> </body> </html> Hi , I got "High Slide Script" for making photogallery .. The problem is that code has no admin panel to upload images and their description . All you make that you write image path into html code of its index page.. I thought to make admin panel by a small database you enter the image path uploaded and description . and the code has a loop to read this data throught a php code . I attached what I made . The problem is : why my images doesn't appear ??? NB: the original script in the file named : highslide-custom-example.htm my code is in the file : highslide-custom-example.php I attached the DB also.. Here is the attachments : http://www.seed-share.com/6mghkdpg0ywj Thanks I'm tired and just about given up. Can anybody help me? Code: [Select] <?php $objConnect = mysql_connect("localhost","","root") or die(mysql_error()); $objDB = mysql_select_db("sdf"); $pic2 = "SELECT * FROM images"; if (!isset($_GET['Page'])) $_GET['Page']='0'; $pic1 = mysql_query($pic2); $Num_Rows = mysql_num_rows($pic1); $Per_Page = 16; // Per Page $Page = $_GET["Page"]; if(!$_GET["Page"]) {$Page=1;} $Prev_Page = $Page-1; $Next_Page = $Page+1; $Page_Start = (($Per_Page*$Page)-$Per_Page); if($Num_Rows<=$Per_Page) {$Num_Pages =1;} else if(($Num_Rows % $Per_Page)==0) {$Num_Pages =($Num_Rows/$Per_Page) ;} else {$Num_Pages =($Num_Rows/$Per_Page)+1; $Num_Pages = (int)$Num_Pages;} $pic2 .=" order by thumbnailID ASC LIMIT $Page_Start , $Per_Page"; $pic1 = mysql_query($pic2); $cell = 0; $link1 = "SELECT * FROM images"; $result_link1 = mysql_query($link1); $link = mysql_fetch_array($result_link1); $alt1 = "SELECT * FROM images"; $alt = mysql_fetch_array(mysql_query($alt1)); echo ' <div id="tablediv"> <table border="0" cellpadding="17" cellspacing="0" class="table"> <tr>'; while($pic = mysql_fetch_array($pic1)) { if($cell % 4 == 0) { echo '</tr><tr>'; } if($cell == 2) { echo ' <td> fillerspace </td>'; } elseif ($cell == 3) { echo ' <td> Fillerspace2 </td>'; } else { echo ' <td> <a href="/' . $link["link"] . '.php"> <div class="image"> <img src="https://s3.amazonaws.com/image/' . $pic["pic"] . '.png" alt="' . $alt["alt"] . '" height="200" width="200" /> </div> </a> </td>'; } $cell++; } echo '</tr></table></div>'; ?> Basically, there are a couple of faults with this code. I didn't include the pagination part, but there is, for simplicity. But right now, when I insert a new record such as this: INSERT INTO `images` VALUES (' ', 'blog', 'yo', '6', 'hello', '2011-02-15T07:24:17Z') The columns go in order of thumbnailID, folder, link, pic, alt, and time.^^^^^^^^ several problem arises. One, the new record is not displayed as the newest entry on my site. So the record is actually placed in one of the paginated pages. How can I reverse the order? The other thing is, it seems like my pic column is the only thing being understood. You see, when I inserted the above record, I checked my site and saw the pic 6, but the link wasn't 'yo', and the alt wasn't 'hello'. Why is that? By the way, my host is awfully terrible. Maybe it's just having a major delay in reading the link and alt? I don't know. That would be the only reasonable answer, unless my code is off. Thank you, and I'll check 10hours from now. |