PHP - Simple Image Gallery Reading From Directory - Random / Numerical Placement
I have a very simple piece of code to create a grid based gallery. The thumbnails are loaded from a single directory and are name 1.jpg... 2.jpg... 3.jpg etc
At the moment the images appear to be loaded in randomly. I want them to load in numerically in terms of their filename. I know I may need to use 'sort' or 'natsort' but where in the code? Thanks for any help you can give me Code: [Select] <? $images = "Images/Bag Thumbs/"; # Location of small versions $big = "ruxxwomens.php?id="; # Location of big versions (assumed to be a subdir of above) $cols = 4; # Number of columns to display if ($handle = opendir($images)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != ".." && $file != rtrim($big,"/")) { $files[] = $file; } } closedir($handle); } $colCtr = 0; echo '<table width="800" cellspacing="0" cellpadding="0" border="0"><tr>'; foreach($files as $file) { if($colCtr %$cols == 0) echo '</tr><tr>'; echo '<td align="center"><a href="' . $big . $file . '"><img src="' . $images . $file . '" cellspacing="0" cellpadding="0" border="0"></a></td>'; $colCtr++; } echo '</table>' . "\r\n"; ?> Similar TutorialsHello, I have this script that I am trying to work with, it works and It is a basic image viewer/Gallery and it reads from a directory, I have all my images like so 1.png, 2.png, 3.png etc. They show up just wonderful and does what I want it to do. but I cannot get it to read the directory in numeric form. Here is my code that I am working with <?php require_once("data/connect.php"); // set the absolute path to the directory containing the images define ('IMGDIR', 'birthday/'); // same but for www define ('WEBIMGDIR', 'birthday/'); // set session name for slideshow "cookie" define ('SS_SESSNAMEB', 'slideshow_sessb'); // global error variable $err = ''; // start img session session_name(SS_SESSNAMEB); session_start(); // init slideshow class $ss = new slideshow($err); if (($err = $ss->init()) != '') { header('HTTP/1.1 500 Internal Server Error'); echo $err; exit(); } // get image files from directory $ss->get_images(); // set variables, done. list($curr, $caption, $first, $prev, $next, $last) = $ss->run(); /* slideshow class, can be used stand-alone */ class slideshow { private $files_arr = NULL; private $err = NULL; public function __construct(&$err) { $this->files_arr = array(); $this->err = $err; } public function init() { // run actions only if img array session var is empty // check if image directory exists if (!$this->dir_exists()) { return 'Error retrieving images, missing directory'; } return ''; } public function get_images() { // run actions only if img array session var is empty if (isset($_SESSION['imgarr'])) { $this->files_arr = $_SESSION['imgarr']; } else { if ($dh = opendir(IMGDIR)) { while (false !== ($file = readdir($dh))) { if (preg_match('/^.*\.(jpg|jpeg|gif|png)$/i', $file)) { $this->files_arr[] = $file; } } closedir($dh); } $_SESSION['imgarr'] = $this->files_arr; } } public function run() { $curr = 1; $last = count($this->files_arr); if (isset($_GET['img'])) { if (preg_match('/^[0-9]+$/', $_GET['img'])) $curr = (int) $_GET['img']; if ($curr <= 0 || $curr > $last) $curr = 1; } if ($curr <= 1) { $prev = $curr; $next = $curr + 1; } else if ($curr >= $last) { $prev = $last - 1; $next = $last; } else { $prev = $curr - 1; $next = $curr + 1; } // line below sets the caption name... $caption = str_replace('-', ' ', $this->files_arr[$curr - 1]); $caption = str_replace('_', ' ', $caption); $caption = preg_replace('/\.(jpe?g|gif|png)$/i', '', $caption); $caption = ucfirst($caption); return array($this->files_arr[$curr - 1], $caption, 1, $prev, $next, $last); } private function dir_exists() { return file_exists(IMGDIR); } } ?> <? // Image files array $image_files = array( ); // Array to store the images that were sorted $image_sorted = array( ); // Read the extension of the file name passed function readExtension( $file ) { $extension = substr( $file, strrpos( $file, '.' ) + 1 ); return $extension; } // This may already exist but I was in a coding frenzy. Obviously, this checks if it is an image or not function isImage( $file ) { $extension = readExtension( $file ); $valid_images = array( "gif", "jpg", "jpeg", "png", "gif" ); for( $i = 0; $i < sizeof( $valid_images ); $i++ ) { if( $extension == $valid_images[ $i ] ) { return true; } } } // Traverse the directory and get all the images in that folder function getImagesInFolder( $dir ) { if( $handle = opendir( $dir ) ) { while( false !== ( $file = readdir( $handle ) ) ) { if( $file != "." && $file != ".." && $file != "Thumbs.db" ) { if( !( is_dir( $dir . $file ) ) ) { $file_fp = $dir . $file; if( isImage( $file_fp ) ) array_push( $GLOBALS['image_files'], $file_fp ); } } } closedir( $handle ); } } //The brunt of the post. Explained below in more detail function sortByModDate( $array_in, &$array_out ) { for( $i = 0; $i < sizeof( $array_in ); $i++ ) { $time_stamp = date("G:i:s-d-m-y", filemtime( $array_in[ $i ] ) ); $array_out[ $array_in[ $i ] ] = $time_stamp; } arsort( $array_out, SORT_STRING ); $array_out = array_keys( $array_out ); if( $array_out[ 0 ] == "0" ) array_shift( $array_out ); unset( $array_in ); } // Get the sorted file by index number. This seems a bit redundant so you can modify as you see fit. function getSortedImageByIdx( $index_num ) { sortByModDate( $GLOBALS['image_files'], $GLOBALS['image_sorted'] ); return $GLOBALS[ '{image_sorted[ $index_num ]}' ]; } ?> <!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" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>A Great Escape Spalon</title> <!-- BEGIN CSS STYLES --> <link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" /> <style type="text/css"> body{margin: 0;padding: 0;font: 100% Verdana, Arial, Helvetica, sans-serif;font-size: 14px;} div#gallery{margin: 40px auto;text-align: center;} div#gallery img{margin: 20px;} div#gallery p{color: #004694;} div#gallery div.pn{padding: 10px;margin: 0 5px;} a{color:#333;} a:hover{color:#cc0000;} a.sp{padding-right: 40px;} </style> <style type="text/css"> #main { position: relative; width: 1024px; margin: 0 auto; height:auto; vertical-align: middle; } #footer {position: absolute; bottom: 0; left: 0; width: 600px; height: 50px;} html, body { background-image:url(img/background.png); background-repeat:repeat-x; } #apDiv1 { position:absolute; background-image:url(img/sides.png); top: 1px; left: 1px; width: 1017px; } #apDiv2 { position:absolute; width:206px; height:384px; z-index:3; left: 50px; top: 127px; } #apDiv3 { position:absolute; width:216px; height:386px; z-index:4; left: 715px; top: 128px; } #apDiv4 { position:absolute; width:970px; height:115px; z-index:5; top: -1px; left: 1px; } #apDiv5 { position:absolute; width:200px; height:115px; z-index:5; left: 296px; top: 9px; } #apDiv6 { position:absolute; width:342px; height:115px; z-index:2; left: 101px; top: 129px; } #apDiv7 { position:absolute; width:452px; height:115px; z-index:6; left: 295px; top: 177px; } /* Left Menu */ #apDiv8 { position:absolute; width:0px; height:0px; z-index:7; left: 123px; top: 179px; } #apDiv9 { position:absolute; width:3px; height:2px; z-index:8; left: 123px; top: 233px; } #apDiv10 { position:absolute; width:13px; height:2px; z-index:10; left: 123px; top: 272px; } #apDiv11 { position:absolute; width:3px; height:0px; z-index:11; left: 123px; top: 313px; } #apDiv12 { position:absolute; width:1px; height:1px; z-index:12; left: 120px; top: 354px; } #apDiv13 { position:absolute; width:0px; height:0px; z-index:13; left: 120px; top: 399px; } #apDiv14 { position:absolute; width:3px; height:2px; z-index:14; left: 123px; top: 449px; } #apDiv15 { position:absolute; width:1px; height:0px; z-index:15; left: 123px; top: 492px; } #apDiv16 { position:absolute; width:1px; height:1px; z-index:16; left: 123px; top: 537px; } #apDiv17 { position:absolute; width:2px; height:2px; z-index:17; left: 123px; top: 581px; } /* Right Menu */ #apDiv18 { position:absolute; width:2px; height:4px; z-index:18; left: 774px; top: 179px; } #apDiv19 { position:absolute; width:4px; height:0px; z-index:19; left: 774px; top: 233px; } #apDiv20 { position:absolute; width:4px; height:3px; z-index:20; left: 774px; top: 315px; } #apDiv21 { position:absolute; width:49px; height:1px; z-index:21; left: 774px; top: 360px; } #apDiv22 { position:absolute; width:1px; height:1px; z-index:22; left: 774px; top: 405px; } #apDiv23 { position:absolute; width:21px; height:0px; z-index:23; left: 774px; top: 450px; } #apDiv24 { position:absolute; width:3px; height:0px; z-index:24; left: 774px; top: 496px; } #apDiv25 { position:absolute; width:5px; height:0px; z-index:25; left: 774px; top: 536px; } #apDiv26 { position:absolute; width:5px; height:0px; z-index:26; left: 774px; top: 272px; } #apDiv27 { position:absolute; width:0px; height:0px; z-index:27; left: 773px; top: 579px; } #apDiv28 { position:absolute; width:448px; height:501px; z-index:28; left: 277px; top: 137px; } #apDiv29 { position:absolute; width:200px; height:115px; z-index:1; left: 711px; top: 914px; } </style> <!-- END CSS STYLES --> <!-- BEGIN LIGHTBOX JS --> <script type="text/javascript" src="js/prototype.js"></script> <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script> <script type="text/javascript" src="js/lightbox.js"></script> <!-- END LIGHTBOX JS --> </head> <body> <!-- MAIN LAYOUT --> <div id=main> <div id="apDiv1"><img src="img/sides.png" width="995" height="1016"/></div> <div id="apDiv2"><img src="img/left_menu/leftmenu.png" /></div> <div id="apDiv3"><img src="img/left_menu/leftmenu.png" /></div> <div id="apDiv4"><img src="img/flower_top.png" width="1016" /></div> <div id="apDiv5"><img src="img/top_logo.png" width="446" /></div> <div id="apDiv6"><img src="img/middle_white_flower.png" width="840" /></div> <div id="apDiv7"><img src="img/back_center.png" width="453"/></div> <!-- END MAIN LAYOUT --> <!-- LEFT MENU BEGIN --> <div id="apDiv8"><img src="img/left_menu/menu.png" /></div> <div id="apDiv9"><a href="page.php?page=introduction"><img src="img/left_menu/introduction.png" border="0" /></a></div> <div id="apDiv10"><a href="page.php?page=hair_services"><img src="img/left_menu/hair_services.png" border="0" /></a></div> <div id="apDiv11"><a href="page.php?page=nail_services"><img src="img/left_menu/nail_services.png" border="0" /></a></div> <div id="apDiv12"><a href="page.php?page=body_treatments"><img src="img/left_menu/body_treatments.png" border="0"></a></div> <div id="apDiv13"><a href="page.php?page=specialties"><img src="img/left_menu/specialties.png" border="0" /></a></div> <div id="apDiv14"><a href="page.php?page=massage"><img src="img/left_menu/massage.png" border="0" /></a></div> <div id="apDiv15"><a href="page.php?page=packages"><img src="img/left_menu/packages.png" border="0" /></a></div> <div id="apDiv16"><a href="page.php?page=facials"><img src="img/left_menu/facials.png" border="0" /></a></div> <div id="apDiv17"><a href="page.php?page=extras"><img src="img/left_menu/extras.png" border="0" /></a></div> <!-- END OF LINKS --> <!-- RIGHT MENU BEGINS --> <div id="apDiv18"><img src="img/right_menu/info.png" /></div> <div id="apDiv19"><a href="page.php?page=price_list"><img src="img/right_menu/price_lists.png" border="0" /></a></div> <div id="apDiv20"><a href="page.php?page=gift_certificate"><img src="img/right_menu/gift_cert.png" border="0" /></a></div> <div id="apDiv21"><a href="page.php?page=meet_the_team"><img src="img/right_menu/meet_the_team.png" border="0" /></a></div> <div id="apDiv22"><a href="page.php?page=news_reviews"><img src="img/right_menu/news_reviews.png" border="0" /></a></div> <div id="apDiv23"><a href="page.php?page=employment"><img src="img/right_menu/employment.png" border="0" /></a></div> <div id="apDiv24"><a href="page.php?page=galleries"><img src="img/right_menu/galleries.png" border="0" /></a></div> <div id="apDiv25"><a href="page.php?page=products"><img src="img/right_menu/products.png" border="0" /></a></div> <div id="apDiv26"><a href="page.php?page=spa_price_list"><img src="img/right_menu/spa_price_lists.png" border="0" /></a></div> <div id="apDiv27"><a href="page.php?page=contact"><img src="img/right_menu/phone_number.png" border="0" /></a></div> <!-- BEGIN CENTER TEXT --> <div id="apDiv28"> <div id="gallery"> <?PHP $title = IMGDIR; $title = str_replace("/"," ",$title); echo $title; ?> <a href="<?=WEBIMGDIR;?><?=$curr;?>" rel="lightbox"><?PHP echo getSortedImageByIdx( 0 ); ?><img src="<?=WEBIMGDIR;?><?=$curr;?>" alt="" width="448" height="350"/></a> <p>Click on the Image to get a better view! or Click <a href="<?=WEBIMGDIR;?><?=$curr;?>" rel="lightbox">Here!</a></p> <div class="pn"> <a href="?img=<?=$first;?>">First</a> | <a href="?img=<?=$prev;?>" class="sp">Previous</a><a href="?img=<?=$next;?>">Next</a> | <a href="?img=<?=$last;?>">Last</a> </div> </div> <!-- END CENTER TEXT --> </div> </div> </body> </html> What I am looking for in help is to be able to get it to show the images in order Here it is working http://agreatescape.org/birthday.php? if you click the image lightbox will pop up but if you look at the image url it will go from 1.png to 58.png etc.. I have looked and looked and tried for hours and cant seem to get my head around it.. Thank you in advance 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>'; ?> My images generator comprises
an array of image names extracted form an images table from a database using a select statement
a random number generator,
and a string that builds the correct pathname for the selected file.
To select one of the images for display, i generate a random number between 1 and the length of the array.
Though the generator is working, I noticed one of the random numbers is throwing up this error:
Warning: getimagesize(images/): failed to open stream: No such file or directory in
An inspection of the array reveals 2 array elements (representing my number of images) but one array element is NULL ( the first entry in the banner table
image_generator.php
require_once('connection.inc.php'); $sql = 'SELECT `filename` FROM banner'; $result = $mysqli->query($sql, MYSQLI_STORE_RESULT) or die(mysqli_error()); $row = $result->fetch_array(MYSQLI_ASSOC);//an array of image names $count = $result->num_rows; for ($i = 1; $i <= $count; ++$i) { $row[$i] = $result->fetch_array(MYSQLI_ASSOC); } $i = rand(1, $count); //a random number generator, //The random number is used in the final line to build the correct pathname for the selected file. $selectedImage = "images/{$row[$i]['filename']}"; if (file_exists($selectedImage) && is_readable($selectedImage)) { $imageSize = getimagesize($selectedImage); }var_dump($row) array (size=1) 'filename' => string 'ginsomin2.jpg' (length=13) nullRANDON IMAGE DISPLAY require_once 'image_generator.php'; <div id="banner" class="wrapper clearfix"> <img src="<?php echo $selectedImage; ?>" alt="banner"> </div>Kindly advice how i may proceed from here? Thanks. I have a directory full of pictures that I would like to display in a gallery. Originally I was going to write HTML like this...
<li> <img src=/photos/img_001.jpg"> </li>
And then simply copy and paste that for the number of photos I have, and then tweak the code to: img_002.jpg, img_003.jpg, and so on. I guess that is silly considering that I have over 500 photos to display! How could I use PHP to go to my /photos/ directory, scan all of the files in that directory, and then grab the file name so I could automate this process? Sorry, but I haven't written PHP in several years so all of this escapes me! ☹️ hey guys im tyring to read my directory (whole of the web server)...i want to be able to put the file name and root into an array...im just wanting to know whats the best function i need to do this please?...thank you Hi Everyone, I am a noob so forgive me I tried looking this up myself But I am still confused. Basically, I am trying to use the above code to display a gallery of images from my images folder on my image site. But this free code I found below Pulls the images from the /root not a named directory where the images are stored. Would someone be kind enough to tell me how I can get the script below to pull the large images from a folder called "images" Vs the script looking for the images the root. Thanks so much in advance Code: [Select] <?php # SETTINGS $max_width = 100; $max_height = 100; function getPictureType($ext) { if ( preg_match('/jpg|jpeg/i', $ext) ) { return 'jpg'; } else if ( preg_match('/png/i', $ext) ) { return 'png'; } else if ( preg_match('/gif/i', $ext) ) { return 'gif'; } else { return ''; } } 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>'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UFT-8" /> <title>Pictures</title> <link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" /> <style type="text/css"> #pictures li { float:left; height:<?php echo ($max_height + 10); ?>px; list-style:none outside; width:<?php echo ($max_width + 10); ?>px; text-align:center; } img { border:0; outline:none; } </style> </head> <body> <?php getPictures(); ?> <script type="text/javascript" src="js/prototype.js"></script> <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script> <script type="text/javascript" src="js/lightbox.js"></script> </body> </html> Hi
I have this json file
{"user":"RD32","time":"14:00","type":"staff"} {"user":"XC12","time":"21:00","type":"management"} {"user":"YG89","time":"09:00","type":"staff"} and I want to pull just "staff" from it and output like user: RD32 time: 14:00 ----- user: YG89 time: 09:00 is that possible? Hey, I'm trying to work out how I can have a simple script that will work like this: Page 1 - Heading, Paragraph, Image read from database. Page 2 - Has text boxes allowing you to change heading, paragraph and image (url) with each edit using a different text box. (Admin panel) The database connection would be in a separate file. So far I've got the database connection sorted. Code: [Select] <?php //Database Information $dbtype = "mysql"; $db_host = "localhost"; $db_user = ""; $db_pass = ""; $db_name = ""; $db_port = ""; $db_table_prefix = "userCake_"; ?> At the top of each of the other pages this is what I've got. Code: [Select] <?php require_once("models/config.php"); ?> Let's say I give each bit stored in the database a page ID and an object ID. If the page selected is index.php how can we give it a page ID of 1 and give then include all the separate 'objects' throughout the page? Hopefully this makes sense? Cheers, Jack well I lowered my standards massively. LOL. I decided to google, "php upload and display image", instead of "php gallery". Here is the error I get Warning: copy(/images/sheila.jpg) [function.copy]: failed to open stream: No such file or directory in /hermes/bosweb/web173/b1739/sl.brendansite1/public_html/ealike2/smallgallery/smallgallery.php on line 59 and here is the script that I mostly understand. I thought it was the ..images/, but now I don't know what it is. any help greatly appreciated. thank you. below is the code for the page. Code: [Select] <!-- Start PHP Code For Image Upload --> <?php //define a maxim size for the uploaded images in Kb define ("MAX_SIZE","5060"); //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 errro occures. //If the error occures 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['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['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 and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h2>Unknown extension!</h2>'; $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=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h2>You have exceeded the file size limit! Please reduce the image size to 100 Kb or less!</h2>'; $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="../images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h2>Copy unsuccessful!</h2>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['Submit']) && !$errors) { echo "<h2>File Uploaded Successfully!</h2><br />"; echo "<img src='http://ealike.com/images/<?php echo $image_name; ?> />"; } ?> <!-- End PHP Code For Image Upload --> <!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>Untitled Document</title> </head> <body> <!-- Start Image Upload Form --> <form name="newad" method="post" enctype="multipart/form-data" action=""> <input type="file" name="image"> <input name="Submit" type="submit" value="Upload image"> </form> <!-- End Image Upload Form --> </body> </html> Hello, Five images will be displayed inside a division. There will be a previous and next button/link. If someone click the next button the next image will be added in that div and the first image will be gone from that div. The previous button/link will do the same thing. Is it possible with php? I am confused if it's a javascript or ajax question. Thanks. I wonder whether someone may be able to help me please. I'm fairly new to PHP programming so please bear with me. I currently have a HTML user input form, where two of the fields are dependable drop down boxes. The user selects text values from these and, along with other pieces of information, the record is saved to a mySQL database. However, rather than saving the text value I save the 'id' field value for each selection made. On another 'Read Only' form, the user can then go back to have a look at the records they have previously saved. The problem I have is that rather than the user being able to see the text values selected from the drop down menus, they can only see the id for each of the selections made. I just wondered whether it would be at all possible please that someone could show me what I need to do so that the user can see the 'text' rather than the 'id' value from the selections they have made. The code that I am using to load the information into the read only form is below. Code: [Select] <?php require("phpfile.php"); // Start XML file, create parent node $dom = new DOMDocument("1.0"); $node = $dom->createElement("markers"); $parnode = $dom->appendChild($node); // Opens a connection to a MySQL server $connection=mysql_connect ("hostname", $username, $password); if (!$connection) { die('Not connected : ' . mysql_error());} // Set the active MySQL database $db_selected = mysql_select_db($database, $connection); if (!$db_selected) { die ('Can\'t use db : ' . mysql_error()); } // Select all the rows in the table $query = "SELECT findid, locationid, detectorid, searchheadid "; $result = mysql_query($query); if (!$result) { die('Invalid query: ' . mysql_error()); } header("Content-type: text/xml"); // Iterate through the rows, adding XML nodes for each while ($row = @mysql_fetch_assoc($result)){ // ADD TO XML DOCUMENT NODE $node = $dom->createElement("marker"); $newnode = $parnode->appendChild($node); $newnode->setAttribute("findid",$row['findid']); $newnode->setAttribute("locationid",$row['locationid']); $$newnode->setAttribute("detectorid",$row['detectorid']); $newnode->setAttribute("searchheadid",$row['searchheadid']); } echo $dom->saveXML(); ?> The two fields concerned are 'detectorid' and 'searchheadid'. The tables holding the 'id' and 'text' values for each are in the following tables 'detectors' and searchheads'. Many thanks and kind regards Chris Good morning! I have a two dimensional array, basically a table (see code below). I want to get a value from the array using two methods: 1) Using the row's key: $NewValue = $MyArray[$UniqueKey]; 2) Using the row's index (row number, so to speak): $NewValue = $MyArray[$RowNumber]; The second print statement in the code below does not work. Both print statements should output the same value. Is there an easy way to do this? The table has hundreds of rows and I will not know the key value of row 879 nor can I generate it. So I cannot use array_keys(). And I DO NOT want to start at the first row and count up to the 879th row. Any clever ideas to share and enlighten? Thanks! <?php // Initialize the array keys and values $MyArray = array(); $MyArray['first']['col1'] = 'abc'; $MyArray['first']['col2'] = 'def'; $MyArray['first']['col3'] = 'ghi'; $MyArray['second']['col1'] = 'jkl'; $MyArray['second']['col2'] = 'mno'; $MyArray['second']['col3'] = 'pqr'; $MyArray['third']['col1'] = 'stu'; $MyArray['third']['col2'] = 'vwx'; $MyArray['third']['col3'] = 'yz'; $MyArray['fourth']['col1'] = 'a1a'; $MyArray['fourth']['col2'] = 'b2b'; $MyArray['fourth']['col3'] = 'c3c'; $MyArray['fifth']['col1'] = 'ddd'; $MyArray['fifth']['col2'] = 'eee'; $MyArray['fifth']['col3'] = 'fff'; // Two methods to get a value. Second one does nothing. print"{$MyArray['third']['col2']}</br>"; print"{$MyArray[2]['col2']}</br>"; ?> I have an associative array that is serialized and stored in a MySQL DB. The array is a duty roster for my son's Cub Scout camping trip (adult volunteers for specific jobs). When a user clicks a spot on the jQuery/client side, it sends it to my php page via ajax, which should pull up the array from the DB, unserialize it, replace the value "Available" with the person's name for the date/time/job that they clicked on. For ease of processing, I need to reference the value to replace by numerical indexes rather than the associative key string-type name, but when I try it, it just says Undefined offset. I thought I could access key/values using the numerical index in square brackets, just as I could if it were a non-associative array. What gives? (You can see near the end where I tried to access the array by index; this now-commented out line just tacked it on at the end, like it was recognizing the digits as strings instead of integers. I've tried to cast the values as integers before putting them in brackets, but same effect. Code: [Select] // get the duty roster array from the database $query = "select dutyroster from ".$eventsTable." where eventID = 1"; $result = mysql_query($query); if(!$result) { } else { //put the returned result into a usable array $returnedRows = mysql_fetch_array($result,MYSQL_BOTH); $unserializedArray = unserialize($returnedRows[0]); } //get the returned values for ID, email, and fillerValue $ID = "0-0-2-2";//$_POST['ID']; $email = "blank@blank.com";//$_POST['email']; $fillerValue = "Dude (test)";//$_POST['fillerValue']; // parse $ID to break out the array index & set them as variables $explodedArray = explode("-",$ID); $iDate = (int)$explodedArray[0]; $iTimeblock = (int)$explodedArray[1]; $iJob = (int)$explodedArray[2]; $iSlot = (int)$explodedArray[3]; echo "<br/> the values a idate: ".$iDate." and iTimeblock: ".$iTimeblock." and iJob: ".$iJob." and iSlot: ".$iSlot."</br>"; echo "<BR/> the random selected value to display is: ".$unserializedArray[0]; //$unserializedArray[$iDate][$iTimeblock][$iJob][$iSlot] = $fillerValue; print_r($unserializedArray); Hi, I've read a lot of places that it's not recommended to store binary files in my db. So instead I'm supposed to upload the image to a directory, and store the link to that directory in database. First, how would I make a form that uploads the picture to the directory (And what kinda directories are we talking?). Secondly, how would I retrieve that link? And I guess I should rename the picture.. I'd appreciate any help, or a good tutorial (Haven't found any myself). Can I get some help or a point in the right direction.
I am trying to create a form that allows me to add, edit and delete records from a database.
I can add, edit and delete if I dont include the image upload code.
If I include the upload code I cant edit records without having to upload the the same image to make the record save to the database.
So I can tell I have got the code processing in the wrong way, thing is I cant seem to see or grasp the flow of this, to make the corrections I need it work.
Any help would be great!
Here is the form add.php code
<?php require_once ("dbconnection.php"); $id=""; $venue_name=""; $address=""; $city=""; $post_code=""; $country_code=""; $url=""; $email=""; $description=""; $img_url=""; $tags=""; if(isset($_GET['id'])){ $id = $_GET['id']; $sqlLoader="Select from venue where id=?"; $resLoader=$db->prepare($sqlLoader); $resLoader->execute(array($id)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Add Venue Page</title> <link href='http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <?php $sqladd="Select * from venue where id=?"; $resadd=$db->prepare($sqladd); $resadd->execute(array($id)); while($rowadd = $resadd->fetch(PDO::FETCH_ASSOC)){ $v_id=$rowadd['id']; $venue_name=$rowadd['venue_name']; $address=$rowadd['address']; $city=$rowadd['city']; $post_code=$rowadd['post_code']; $country_code=$rowadd['country_code']; $url=$rowadd['url']; $email=$rowadd['email']; $description=$rowadd['description']; $img_url=$rowadd['img_url']; $tags=$rowadd['tags']; } ?> <h1 class="edit-venue-title">Add Venue:</h1> <form role="form" enctype="multipart/form-data" method="post" name="formVenue" action="save.php"> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <div class="form-group"> <input class="form-control" type="hidden" name="id" value="<?php echo $id; ?>"/> <p><strong>ID:</strong> <?php echo $id; ?></p> <strong>Venue Name: *</strong> <input class="form-control" type="text" name="venue_name" value="<?php echo $venue_name; ?>"/><br/> <br/> <strong>Address: *</strong> <input class="form-control" type="text" name="address" value="<?php echo $address; ?>"/><br/> <br/> <strong>City: *</strong> <input class="form-control" type="text" name="city" value="<?php echo $city; ?>"/><br/> <br/> <strong>Post Code: *</strong> <input class="form-control" type="text" name="post_code" value="<?php echo $post_code; ?>"/><br/> <br/> <strong>Country Code: *</strong> <input class="form-control" type="text" name="country_code" value="<?php echo $country_code; ?>"/><br/> <br/> <strong>URL: *</strong> <input class="form-control" type="text" name="url" value="<?php echo $url; ?>"/><br/> <br/> <strong>Email: *</strong> <input class="form-control" type="email" name="email" value="<?php echo $email; ?>"/><br/> <br/> <strong>Description: *</strong> <textarea class="form-control" type="text" name="description" rows ="7" value=""><?php echo $description; ?></textarea><br/> <br/> <strong>Image Upload: *</strong> <input class="form-control" type="file" name="image" value="<?php echo $img_url; ?>"/> <small>File sizes 300kb's and below 500px height and width.<br/><strong>Image is required or data will not save.</strong></small> <br/><br/> <strong>Tags: *</strong> <input class="form-control" type="text" name="tags" value="<?php echo $tags; ?>"/><small>comma seperated vales only, e.g. soul,hip-hop,reggae</small><br/> <br/> <p>* Required</p> <br/> <input class="btn btn-primary" type="submit" name="submit" value="Save"> </div> </form> </div> </body> </html>Here is the save.php code <?php error_reporting(E_ALL); ini_set("display_errors", 1); include ("dbconnection.php"); $venue_name=$_POST['venue_name']; $address=$_POST['address']; $city=$_POST['city']; $post_code=$_POST['post_code']; $country_code=$_POST['country_code']; $url=$_POST['url']; $email=$_POST['email']; $description=$_POST['description']; $tags=$_POST['tags']; $id=$_POST['id']; if(is_uploaded_file($_FILES['image']['tmp_name'])){ $folder = "images/hs-venues/"; $file = basename( $_FILES['image']['name']); $full_path = $folder.$file; if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) { //echo "succesful upload, we have an image!"; var_dump($_POST); if($id==null){ $sql="INSERT INTO venue(venue_name,address,city,post_code,country_code,url,email,description,img_url,tags)values(:venue_name,:address,:city,:post_code,:country_code,:url,:email,:description,:img_url,:tags)"; $qry=$db->prepare($sql); $qry->execute(array(':venue_name'=>$venue_name,':address'=>$address,':city'=>$city,':post_code'=>$post_code,':country_code'=>$country_code,':url'=>$url,':email'=>$email,':description'=>$description,':img_url'=>$full_path,':tags'=>$tags)); }else{ $sql="UPDATE venue SET venue_name=?, address=?, city=?, post_code=?, country_code=?, url=?, email=?, description=?, img_url=?, tags=? where id=?"; $qry=$db->prepare($sql); $qry->execute(array($venue_name, $address, $city, $post_code, $country_code, $url, $email, $description, $full_path, $tags, $id)); } if($success){ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //if uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Upload Recieved but Processed Failed!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //move uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Updated.')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } ?>Thanks in advance! Edited by hankmoody, 12 August 2014 - 05:15 PM. how to create php gallery with pagination and also add new images that control by admin
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 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) |