Image (src) not refreshing after file-upload -> image [duplicate] - php

This question already has answers here:
PHP force refresh image
(5 answers)
Closed 2 years ago.
Having an image 'update' problem, whereby the image does not change after new file upload. the SRC attribute is designed to remain same; each uploaded file overwrites the previous one.
Let me elaborate::
I have a simple webpage, say Home.php and the page shows an image 'IMAGE1.jpg' where the image tag's src = "directory456/IMAGE1.jpg", understandably.
This homepage allows the user to change the image, through a file upload button Input type="file" (as we all know) located inside a "form". The form POSTS all the file data to another php file "Upload_File_Check.php".
Inside "Upload_File_Check.php", simple actions are performed:
(1) Check file size <2.0 MB,
(2) Check file "type" ($_FILES['filename']['type']) is one of {image/jpeg image/gif image/png}, and
(3) depending on whichever, utilizes the imagecreatefrom(gif/png/bmp)() function in PHP, to convert them ALL to jpg,
(4) ALL uploaded files are saved as "directory456/IMAGE1.jpg" using same file name hence overwriting the previous file sitting the in the directory. This way, knowing that the image's name will always be IMAGE1.jpg, I will not need to store/retrieve that from database. (comments welcome on this practice).
However, once the user clicks on the "Upload" button, and checks in "Upload_File_Check.php" are completed successfully, I would have thought that since "Home.php" is reloaded (? not sure about this), the image tag would get refreshed and now show the new image which has just been uploaded (SRC has remained same src="directory456/IMAGE1.jpg")?. The old image is showing, only upon manual page reload does the new image show.. how can I get the image tag to now refresh and load recent image pointed to ?
Code for Home.php:
<FORM method='post' action='Upload_File_Check.php' enctype='multipart/form-data'>
<INPUT type='file' name='filename_' size='10'>
<INPUT type='submit' value='upload'>
</FORM><?PHP echo $_SESSION['UPLOAD_FILE_ERR'];?>
Code for Upload_File_Check.php:
<?PHP
if($_FILES['filename_']['error'] > 0)
{ $_SESSION['UPLOAD_FILE_ERR'] .= "ERROR: ". $F_error;
header("location: HOME.PHP");}
else
{ $F_name = $_FILES['filename_']['name'];
$F_tmpnm = $_FILES['filename_']['tmp_name'];
$F_type = $_FILES['filename_']['type'];
$F_size = $_FILES['filename_']['size'];
if (!$F_tmpnm) // if file not chosen
{ $_SESSION['UPLOAD_FILE_ERR'] .= "ERROR - must have a file. "; }
if (!(($F_type == "image/bmp")||($F_type == "image/png")||($F_type == "image/jpeg")||($F_type == "image/gif")))
{ $_SESSION['UPLOAD_FILE_ERR'] .= "INVALID - only BMP JPG PNG GIF files allowed "; }
if ($F_size > 2097152)
{ $_SESSION['UPLOAD_FILE_ERR'] .= "File must be < 2.0MB "; }
if (($_SESSION['UPLOAD_FILE_ERR']) !== "")
{ header("HOME.PHP"); }
else
{ $F_destpath = "directory456/";
$F_destname = "IMAGE1.jpg";
move_uploaded_file($F_tmpnm, ($F_destpath . $F_name));
//convert MOVED file to jpg.
switch($F_type)
{ case "image/png":
$Converted_image=imagecreatefrompng($F_destpath . $F_name); break;
case "image/bmp":
$Converted_image=imagecreatefrombmp($F_destpath . $F_name); break;
case "image/gif":
$Converted_image=imagecreatefromgif($F_destpath . $F_name); break;
case "image/jpeg": break;
}
imagejpeg($Converted_image, $F_destpath . $F_destname , 90);
}
header("location: HOME.PHP");
}
?>
How do I get the IMAGE tag to refresh and point to the new image.. Would greatly appreciate your help...
New bie here, would also welcome all comments on the way I have programmed the stuff below.. what are best practices, what are faster (more efficient) methods, etc..

This question is a duplicate of PHP force refresh image.
The image isn't refreshing because the browser is caching the older file. To solve, just add a cache-busting query string to the URL in your img src. Unix timestamps work well for this. Note, however, that this will force the image to reload every time the page is loaded.
<img src="IMAGE1.jpg?t=<?php echo time() ?>">

Related

Is that correct way that this code i using (remove file/unlink) in php

I want to ask you guys about my code in my php update form.
I use unlink($file_Path) to Remove my image file in my folder & my server and that work fine!
So I wonder when using "unlink($file_Path)" to removing an image, In my php page it show me an "Image File Icon " when there was no picture (The image file was removed) But it show me like that (Image file Icon) Because, I though It still has a some value (my value = "../filename.jpg")
so I put "value=" "/" (None Value to Reset a Value)
example :
<input type="hidden" name="newSubimage1" value=""/>
and that work fine when I use with "!empty($ro.."
example :
if (isset($row['subimage1']) && !empty($row['subimage1']))
{
echo "<img src='../images/images_products/".$row['subimage1']."'>";
} else {
echo "No Image Here"; }
`
to not show an "Image File Icon"
Is that a correct way ? that I used to Removing file / Not display an Image File Icon or you has any easy way or the best way that you want to suggest me.
thanks
$image_file_ext = array('jpg', 'png', 'bmp');
$file_ext = pathinfo($row['subimage1'],PATHINFO_EXTENSION);
if (isset($row['subimage1']) && !empty($row['subimage1']) && in_array($file_ext, $image_file_ext))
{
echo "<img src='../images/images_products/".$row['subimage1']."'>";
} else {
echo "No Image Here";
}

Why does avatar disappear upon revisiting page?

When a user submits a picture, the file is moved to a generated folder (for security purposes) with its file pathway recorded on the database. The picture displays correctly when the user stays on the page, but when the user exits from the page and revisits it, the picture they had previously uploaded fails to display (nothing displays at all). I seem to be unable to evoke the image from its location through its session variable and would like insight on this, thanks.
What I've tried:
echoing the avatar session variable -> image doesn't display at all
echoing the location of the image -> image displays when the user does not leave page after submitting. When the user leaves and
revisits the page, the image does not display. In its place, a
outline of where the image is suppose to register shows.
A lot of small tweaks (for instance, setting avatar session variable to location, and so on).
Here is my code:
$fln = $_FILES['avatar']['name'];
if(isset($fln) && tmp_name !== "") {
$tmp_name = $_FILES['avatar']['tmp_name'];
$fls = $_FILES['avatar']['size'];
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rdn = substr(str_shuffle($chars), 0, 15);
//size checker
if($fls > 6500000) {
echo "Image must be less than 6.5 MB...";
}
else {
mkdir("user_data/user_avatars/$rdn/");
$location = "user_data/user_avatars/$rdn/$fln";
move_uploaded_file( $tmp_name, $location);
$imageCD = "UPDATE users SET avatar=? WHERE email=? LIMIT 1";
$imageST = $con->prepare($imageCD);
$imageST->bind_param('ss', $location, $_SESSION["email_login"]);
$imageST->execute();
$_SESSION["avatar"] = $location;
}
}
else {
$location = "/img/default_pic.jpg";
}
Here is where the image is suppose to display:
<img src="<?php echo $_SESSION["avatar"]; ?>" class="profilePic" id="profilePic" />
The session variable will only be active as long as the user doesn't close the browser.
So if you're trying to echo $_SESSION["avatar"] it will work when the user just uploaded the avatar and surfs around on your page. When they leave and come back later, the session has been cleared. Furthermore, the session is only between the current user and the webserver and the avatar will only be displayed for the user itself, and not anyone else on your site!
It will therefore not be the ideal solution to load the image from session!
Every time a user visits your page you need to load their information from your database (including the avatar path) and display it directly from there.

Trying to display images from a filesystem in php

Today i am looking for help. This is my first time asking so sorry in advance if I make a few mistakes
I am trying to code a small web application that will display images.Originally I used the blob format to store my images in a database, however from researching on here People suggest to use a file system. My issue is I cannot display an image. It could be a very small error or even a bad reference to a files location however I cannot make it work.
This is a small project that I hope to be able to improve on and hopefully create into a sort of photo gallery. I am running this application on a localhost.
I am having an issue with displaying images from a filesystem.
// index.php
<form action="process.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>
My form then leads to a process page where the request is dealt with.
<?php
// process.php
// connect to the database
include 'connection.php';
// take in some file data
$filename =$_FILES['image']['name'];
// get the file extension
$extension = strtolower(substr($filename, strpos($filename, '.')+1));
// if the file name is set
if(isset($filename)){
// set save destination
$saved ='images/';
// rename file
$filename = time().rand().".".$extension;
$tmp_name=$_FILES['image']['tmp_name'];
// move image to the desired folder
if(move_uploaded_file($tmp_name, $saved.$filename)){
echo "Success!";
// if success insert location into database
$insert="INSERT INTO stored (folder_name,file_name) VALUES('$saved', '$filename')";
// if the query is correct
if($result=mysqli_query($con,$insert)){
echo "DONE";
echo"</br>";
// attempt to print image
echo "<img src=getimage.php?file_name=$filename>";
}
}
}
else{
echo "Please select a photo!!";
}
?>
Now as you can see I have an < img > tag. To try and learn, I was trying to just display the recently uploaded image. To try and do this I created a getimage file.
<?php
//getimage.php
// set the page to display images
header("Content-Type: image/jpeg");
include "connection.php";
// get requested filename
$name = ($_GET['file_name']);
$query = "SELECT * FROM stored WHERE file_name=$name";
$image = mysqli_query($con,$query);
$row = mysqli_fetch_array($image,MYSQLI_ASSOC);
$img = $row['file_name'];
echo $img;
?>
My database structure is as follows:
database name = db_file.
table name = stored.
columns = folder_name, file_name
Again, this is just a small project so I know I will have to alter the database if I wish to create a larger more efficient application.
It seems you use the database lookup to get just the file name, but you already have the file name. Try adding the folder name, create a valid path.
change
$img = $row['file_name'];
to
$img = $row['folder_name'] . '/' . $row['file_name'];
check your <img>tag to see if the correct url is present. You may or may not need the '/', it depends on how you stored the folder name. You may need to add the domain name. There is just not enough information know what is needed.
Your <img> should look like this
<img href="http://www.yourdomain.com/folder name/file name">
in the end

PHP multiple image file upload and storage to folder and database

I am building a site that will show night revelers a listing of night club establishments and events happening in a big city. I'm trying to build a back-end page where an administrator can be able to add clubs and input information such as establishment name, location, relative pricing etc and of course some images of the club.
Each club will have to have at least one image, the main image. There can be an additional 5 but these are optional, ie. database fields can be null.
I have a form that looks like this:
Establishment Main Photo
TextField: name = "establishment_image"
Establishment Photo 1
TextField: name = "establishment_image"
Establishment Photo 2
TextField: name = "establishment_image"
Establishment Photo 3
TextField: name = "establishment_image"
Establishment Photo 4
TextField: name = "establishment_image"
Establishment Photo 5
TextField: name = "establishment_image"
Its kinda like the yahoo mail attach file form. As you can see the textfields have the same textfield name for now.
I need to know what kind of changes I need to make on my submit form to be able to: for instance;
Put a main pic and leave other textfields blank,
Put a main pic, pic 1 and 2 and leave other textfields blank,
Put a main pic, pic 1, 2 and 3 and leave other textfields blank etc.
My establishment_submit.php looks like this:
<?php require_once('../Connections/connections.php'); ?>
<?php //maintain the session
if (!isset($_SESSION))
{
session_start();
}
?>
<?php
//retrieve data from Query String
$establishment_name= $_POST['establishment_name'];
$short_description= $_POST['short_description'];
$long_description= $_POST['long_description'];
$location= $_POST['location'];
$url_link= $_POST['url_link'];
$establishment_address= $_POST['establishment_address'];
$establishment_pricing= $_POST['establishment_pricing'];
$establishment_telephone= $_POST['establishment_telephone'];
$establishment_contact= $_POST['establishment_contact'];
$establishment_email= $_POST['establishment_email'];
$establishment_image = $_FILES['establishment_image']['name'];
//escape User Input to help prevent SQL Injection
$establishment_name= mysql_real_escape_string($establishment_name);
$short_description= mysql_real_escape_string($short_description);
$long_description = mysql_real_escape_string($long_description);
$location= mysql_real_escape_string($location);
$url_link= mysql_real_escape_string($url_link);
$establishment_address= mysql_real_escape_string($establishment_address);
$establishment_pricing= mysql_real_escape_string($establishment_pricing);
$establishment_telephone= mysql_real_escape_string($establishment_telephone);
$establishment_contact= mysql_real_escape_string($establishment_contact);
$establishment_email= mysql_real_escape_string($establishment_email);
$establishment_image= mysql_real_escape_string($establishment_image);
//redirect when successful
$establishmentAddSuccess = "establishment_add_success.php";
?>
<?php
//define a maximum size for the uploaded images
define ("MAX_SIZE","10000");
// note that these dimensions are considered the maximum and are not fixed
// because we have to keep the image ratio intact
//define a maximum size for the uploaded images
define ("LARGE_WIDTH","500");
define ("LARGE_HEIGHT","390");
define ("WIDTH","100"); //set here the width you want your thumbnail to be
define ("HEIGHT","100"); //set here the height you want your thumbnail to be.
// this is the function that will create the appropriately sized images from the upload
// the resize will be done considering the width and height defined, but without deforming the image
function make_largeimage($img_name,$filename,$new_large_w,$new_large_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))
$src_img=imagecreatefromjpeg($img_name);
if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);
if(!strcmp("gif",$ext))
$src_img=imagecreatefromgif($img_name);
//gets the dimensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
// next we will calculate the new dimensions for the large image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimensions 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 dimensions will be from the fixed ones
$ratio1_large=$old_x/$new_large_w;
$ratio2_large=$old_y/$new_large_h;
if($ratio1_large>$ratio2_large)
{
$large_w=$new_large_w;
$large_h=$old_y/$ratio1_large;
}else
{
$large_h=$new_large_h;
$large_w=$old_x/$ratio2_large;
}
// we create a new image with the new dimensions
$dst_large_img=ImageCreateTrueColor($large_w,$large_h);
// resize the big image to the newly created one
imagecopyresampled($dst_large_img,$src_img,0,0,0,0,$large_w,$large_h,$old_x,$old_y);
// output the created image to the file. Now we will have the image into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_large_img,$filename);
else
imagejpeg($dst_large_img,$filename);
if (!strcmp("gif",$ext))
imagegif($$dst_large_img,$filename);
//destroys source and destination images.
imagedestroy($dst_large_img);
imagedestroy($src_img);
}
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))
$src_img=imagecreatefromjpeg($img_name);
if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);
if(!strcmp("gif",$ext))
$src_img=imagecreatefromgif($img_name);
//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
// next we will calculate the new dimensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimensions 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 dimensions 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 dimensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
// resize the big image to the newly 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);
if (!strcmp("gif",$ext))
imagegif($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 errro occures. If the error occures the file will not be uploaded.
$errors=0;
// if it is not empty
for($i=0;$i<count($_FILES['establishment_image']["name"]);$i++)
{
// get the original name of the file from the clients machine
$filenames = stripslashes($_FILES['establishment_image']['name'][$i]);
// get the extension of the file in a lower case format
$extensions = getExtension($filenames);
$extensions = strtolower($extensions);
// 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 (($extensions != "jpg") && ($extensions != "jpeg") && ($extensions != "png") && ($extensions != "gif"))
{
$warning = ("File extension of an image(s) not allowed");
header("location:establishment_add.php?warning=$warning");
$errors=1;
exit();
}
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['establishment_image']['tmp_name'][$i]);
$sizekb=filesize($_FILES['establishment_image']['tmp_name'][$i]);
//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > MAX_SIZE*1024)
{
$warning = ("Images have exceeded the size limit of 10MB");
header("location:establishment_add.php?warning=$warning");
$errors=1;
exit();
}
$rand= rand(0, 100000);
//we will give an unique name, for example a random number
$image_name=$rand.'.'.$extension;
//the new name will be containing the full path where the image will be stored (images folder)
$consname="C:/wamp/www/NNL/Administrator/Establishment_Images/".$image_name; //change the image/ section to where you would like the original image to be stored
$consname2="C:/wamp/www/NNL/Administrator/Establishment_Images/Thumbs/".$image_name;
//change the image/thumb to where you would like to store the new created thumbnail of the image
$copied = copy($_FILES['establishment_image']['tmp_name'][$i], $consname);
$copied = copy($_FILES['establishment_image']['tmp_name'][$i], $consname2);
//localhost calling of images
$img_large="../Establishment_Images/".$image_name; //change the image/ section to where you would like the original image to be stored
$img_thumb="../Establishment_Images/Thumbs/".$image_name;
//we verify if the image has been uploaded, and print error instead
if (!$copied) {
$warning = ("Unable to upload image file");
header("location:establishment_add.php?warning=$warning");
$errors=1;
exit();
}else{
// the new large image will be placed in Images/ folder
$imagelarge_name=$consname ;
// 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
$imagelarge=make_largeimage($consname,$imagelarge_name,LARGE_WIDTH,LARGE_HEIGHT);
// the new thumbnail image will be placed in Images/Thumbs/ folder
$thumb_name=$consname2 ;
// 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($consname,$thumb_name,WIDTH,HEIGHT);
}
}
}
?>
<?php
//If no errors registered, redirect page
if(isset($_POST['Submit']) && !$errors)
{
//insert into database
$query2 = "INSERT INTO establishment(establishment_name,
establishment_short_description,
establishment_long_description,
establishment_address,
establishment_telephone,
establishment_contact,
establishment_email,
location_id,
establishment_pricing,
establishment_url_link,
establishment_mainphoto_url,
establishment_thumb_url)
VALUES
('$establishment_name',
'$short_description',
'$long_description',
'$establishment_address',
'$establishment_telephone',
'$establishment_contact',
'$establishment_email',
'$location',
'$establishment_pricing',
'$url_link',
'$img_large[0]',
'$img_thumb[0]')";
//Execute query
$qry_result2 = mysql_query($query2) or die(mysql_error());
header("Location: " . $establishmentAddSuccess);
}
else
{
$establishment_msg = ("Unable to add establishment");
header("location:establishment_add.php?establishment_msg=$establishment_msg");
exit();
}
?>
This worked fine for single image uploads but doesnt work now. I know I need to make changes from the line;
for($i=0;$i<count($_FILES['establishment_image']["name"]);$i++)
{
How do I make this form be able to upload multiple images. I will appreciate any help.
You can use PHP's array notation as you would in regular form fields:
Pic 1: <input type="file" name="establishment_image[]" />
Pic 2: <input type="file" name="establishment_image[]" />
However, the file processing stuff in PHP will handle it a bit differently than you'd expect server-side:
$_FILES = array(
'establishment_image' => array(
'name' => array(
0 => 'name of Pic 1 file',
1 => 'name of Pic 2 file'
),
'error' => array(
0 => error code for pic1 upload,
1 => error code for pic2 upload
etc...
);
It's easy enough to handle, though:
foreach(array_keys($_FILES['establishment_image']['name']) as $idx) {
....
}
The other option is to give each file input a unique name and work with that serverside. If you hard code a numeric "sub key" in each:
<input type="file" name="establishment_image_1" />
<input type="file" name="establishment_image_2" />
Then you can simply do
for ($i = 1; $i <= 5; $i++) {
echo "Name of file is ", $_FILES["establishment_image_$i"]['name'];
...
}
Image upload pages are a lot of brain damage when you consider the quirks of imagick, UI patterns for the upload page, permissions, etc. My shortcut in a situation where an internal admin is doing the page is Gallery.
The admin then uses gallery for upload, resize, cropping, etc. In essence, the basics plus the "extras" that my clients might demand but that I might not be able to justify charging enough to do from scratch. On the user-side, I query out the gallery from the MySQL database and arrange in any manner I wish, normally via a flashy JQuery front-end I've rigged up. But, it could be anything...and I could even use the gallery stock front-end.
Simiplicity-wise, it doesn't get easier for the user to understand. I can have it up and running in under 2 hours start to finish. And since images are being stored statically in the file system, there's no more additional load than expected.
If you do opt to go it alone, there's certainly more than one way to attack this challenge. I'd recommend checking out this popular post: How can I upload files asynchronously?

auto hyper-link

I am trying to auto generate pages.
What I am trying to do is make a upload form for an image upload that's displayed in a gallery.
I have this but I then want each image to have a page hyper-link auto made for each image where the image can be seen bigger with buying information that's also been uploaded to a MySQL table not 100% with codeigniter I am still luring please look at the site I am trying to build at http://www.fresherdesign.co.uk/PIFF/index.php/main/gallery
This is a direct link to the gallery that I would link to make the page's from, currently they just open a direct link to the image on its own
Any help would be awesome thanks to everyone in advance
Alan Morton
If you want the actual images to be uploaded (and not stored in the database - note that db storage is slightly more difficult to accomplish than your standard upload), you can create a field in the database for the image's location; that is how you are going to correspond your image data with your page content.
Now, if you want a hyperlink to automatically be made, I suggest querying the database of all "Active" entries (again, could be another field unless you simply delete old entries). Each entry should have a unique ID associated with it. This way, when you give the list, simply include a tag similar to
while($row = mysql_fetch_array($query_result)){
// Change this to whatever formatting you need
print '<!-- Whatever content for link -->';
}
Now that's just your loop to get the results. The actual page now should query the database based on the ID given. The query should grab the page content from the database. Something like this would work
<?php
if(!isset($_GET['id'])){
die("Please use a valid link!");
}
$q = mysql_query("SELECT * FROM YOUR_DB_TABLE WHERE ID='".mysql_real_escape_string($_GET['id'])."' LIMIT 1;");
if(!$q || mysql_num_rows($q) < 1){
die("A MySQL Error Occurred: ".mysql_error());
}
while($row = mysql_fetch_array($q)){
// Again, adjust this accordingly
print "Data column 1: ".$row['DataRow1']."<br />".
"Data Column 2: ".$row['DataRow2']."<br />".
"<img src='".$row['ImageLocation']."' />";
}
?>
Now, I haven't tested this exact code, however all of it should work as is. But you will need to adjust it appropriately to fit your requests; but this is one way to accomplish what you're looking for.
Precondition
You'll need to have the directory name in which things are stored, relative to where your php page is located. Obviously, you have this already to create the page. I will assume it is stored in the $dir variable.
Code
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
}
}
Output
This will provide you a list of images that link to the image file itself.
Possible Modifications
1) You may want to only show some of the files in the directory, or a certain amount: Use the if block added here to do that:
if ($handle = opendir($dir)) {
//set $strThatSpecifiesImages to whatever you want;
//for the example, I'm saying that we only want to show files with "gal_image" in the filename
$strThatSpecifiesImages = "gal_image";
$maxFilesToShow = 10; //set this to whatever you want; example max is 10
$count = 0;
while (($count < $maxFilesToShow) && (false !== ($file = readdir($handle))) {
if (strpos($file, $strThatSpecifiesImages) > -1) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
$count++;
}
}
}
2) You might also want to change how things are displayed, so that you don't just have the full image shown here every time. Do this by modifying things in the echo blocks that are outputting HTML. You can have the browser resize the images, or just change it completely so that the links use text instead, or something else.

Categories