Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

While loop that finds out whether an image exists and then shows it 1

Status
Not open for further replies.

krigbert

Programmer
Jun 2, 2005
95
NO
The above is what I'm trying to do. Now, all the images have names like "illustration20thumb.png" - $p (the category) and $no (the number of the page within the category) are variables given through the url of the page.

Code:
                     $lili = 20;
                    
						while(file_exists('illu/' . $p . $lili . '.png')){
                    
                          
							if($lili != $no){ ?>
								<a href="index.php?p=illustrasjon&no=<? print($lili); ?>" title="link til portef&oslash;ljebilde">
								<img src="illu/<? print($p . $lili) ?> thumb.png" height="30px" width="30px" alt="" /></a><? 
							
							} /* if lili == no */
															
							$lili -= 1;
											 
						} /* while lili */
The above doesn't work though, and I'm getting frustrated because I don't know what I'm doing wrong here....


Also, this unrelated code works:
Code:
<img id="storsak" src="<? print($p);print($no) ?>sthumb.jpg" alt=" " />

illustration and webdesign
 

I'll do something more like this :

Code:
// - ! - retrieve files
if ($handle = opendir($target_path["file"])) {

		while (false !== ($file_name = readdir($handle))) {
    
        if(strstr($file_name, "thumb.png")) {
    		
        echo"
        <img src=\"" . $target_path["http"] . $file_name . "\" />
        ";
        
        }
    	
    }

}
 
i agree. you have not properly explained the variables you use, nor the research you have done, the barriers you have hit and what you have done to overcome them.

help us to help you.
 
Okay, I've struggled with it for a while, but I'm just not getting anywhere at all. I suppose it's worth mentioning:

Code:
						while($lili > 0){ 
						if($lili != $no){ 
						if(file_exists($p . "/" . $p . $lili . "thumb.png")){ ?>
						
									<a href="index.php?p=illustrasjon&no=<? print($lili); ?>" title="link til portef&oslash;ljebilde">
									<img src="<? print($p . "/" . $p . $lili); ?>thumb.png" height="30px" width="30px" alt="" /></a><? 
									$lili -= 1;
						
						}}}

If I remove the line with "if(file_exists..." (except the ?> at the end) and the corresponding curly bracket, it works - except, of course, it doesn't check whether the files exist, so I get a bunch of broken image boxes.

illustration and webdesign
 
With the code I posted above, you don't have to check whether a file exists or not because it scans the whole directory.

Simply give values to $target_path["file"] and $target_path["http"] and you're set.

$target_path["file"] is the filesystem path to the images directory.

$target_path["http"] is the relative or absolute url of the images directory.

Then,
if(strstr($file_name, "thumb.png")) {
checks that your filenames contain "thumb.png".

 
addressing the OP code:
please explain what $p and $no and $lili mean and what type of data they hold.
 
Hi, this function might return false if safe mode is enabled!

I usually used is_file instead..

eg.

if (is_file($foo)) {
echo "<!--# The file is there -->";
}
else {
echo "<!-- # corrupt file -->";
}

[qote]is_file — Tells whether the filename is a regular file[/quote]


See also , as results of both theese functions are cached!!

Olav Alexander Mjelde
Admin & Webmaster
 
Ok, I looked at your "makkverk" and I would rather make it from scratch, if I where you.

I made this framework for you:
Code:
<?php
$extensions = array("jpg", "jpeg", "gif", "png");

$d = dir("./images");
while (false !== ($entry = $d->read())) {

if (strlen($entry)>3) {
    $ext = substr($entry, strrpos($entry, ".") + 1 );

     if (in_array($ext, $extensions)) {
       echo "Accepted<br>";
     }
     else {
       echo "denied<br>";
     }
  }
}
$d->close();
?>

Ok, so what I would do from here:
Use my framework, or my general idea..

EG. Let the dirlist scan the directory and check if the file ends in an acceptable extension.

If it does, do an is_file on the tn_ version.

My recommended directorystructure:
\public_html\thephpfile.php
\public_html\images\
\public_html\images\thumbnail\

So, you only loop the images\ dir.
When looping, you check:
Code:
if (is_file($entry)) { // is the main file there?
  if (is_file($thumbnail)) { // is the thumb there?

    }
  else { // call the function that generates the thumb

    }
  }
else {
  echo "<!--# 404 {$entry}-->";
  }
Ps. the dirlist above works, but this code below I havent checked.. So take it as psuedocode.

You should also harden it, as .php.jpg will fail in this check and that can be a security issue!


Olav Alexander Mjelde
Admin & Webmaster
 
Since jeg har missed php innimellom, er you lucky!
Code:
<html>
<head>
<script type="text/javascript">
function changeSrc(srcID)
  {
    if (srcID == 404) {
    document.getElementById("imgcontainer").style.visibility='hidden';
    document.getElementById("myImage").src='';
  }
  else {
    document.getElementById("imgcontainer").style.visibility='visible';
    document.getElementById("myImage").src=srcID;
    }
  }
</script>
</head>

<body>
<div id="imgcontainer" style="visibility:hidden;">
<img src="" id="myImage" onclick="changeSrc(404)" />
</div>
<?php
$extensions = array("jpg", "jpeg", "gif", "png");
$cols = 4;
$colpos = 0;

$d = dir("./images");
while (false !== ($entry = $d->read())) {

if (strlen($entry)>3) {
    $ext = substr($entry, strrpos($entry, ".") + 1 );

     if (in_array($ext, $extensions)) {
        if (is_file("images/{$entry}")) {
          if (is_file("images/thumbnail/{$entry}")) {
          echo "<img src=\"images/thumbnail/{$entry}\" />";
          $colpos++;
          }
          else {
            // generate a new thumb here and then print it
            echo "<div style=\"width:120px; height: 100px; margin:5px; padding:3px; border:1px solid #ddd; float:left; background:#f8f8f8;\" onclick=\"changeSrc('images/{$entry}')\"><div style=\"width:120px; height:90px; overflow:hidden;\"><img src=\"images/{$entry}\" width=\"120px\" /></div></div>";
            $colpos++;
          }
          
        } // end if is file
        else {
          echo "<!--# 404 \"{$entry}\" -->";
        }
     } // end if is in array
     else {
       echo "<!--# 500 \"{$entry}\" -->"; // not an acceptable extension
     } // end else (!in array)
  } // end if fn.len > 3
else {
echo "<!--# Omitted \"{$entry}\" -->";
}
if ($colpos == $cols) {
echo "<div id=\"spacer\" style=\"clear: both;\">&nbsp;</div>";
$colpos = 0;
}
} // end while loop
$d->close();
?> 
</body>
</html>

This is still VERY basic and lacks the thumbnail-generation function, I simply parse the img there, in the place where the thumbnail generation should be.

The layout is also a simple grid, controlled by a var.
Anyhow, you can use this as a framework.

The image could be shown in a modalpopup instead... That would be quite neat.

Olav Alexander Mjelde
Admin & Webmaster
 
I'll give you a star for impressive effort, but this really seems like overkill for my little site. I have three or so galleries of less than 20 images that aren't going to change very often - I just thought it'd be more elegant if I didn't have to tell the page what number of images are in each gallery.

It looks like that's the quicker option anyway, though. Since neither is_file nor file_exists seems to be working (I'm guessing that's it, because I can't find anything syntactically wrong with my code) and nagging the server guy in to fixing it could take a while ;)

illustration and webdesign
 
Try to upload the file I pasted here and beneath that file, in the directory structure, you make a folder: images/

inside images/ , put some files.. gif, jpg, doc, etc..

check if it fails.
If it works, there is something wrong with your scripting.

Your variables are very illogical for me, so its very hard to understand the dataflow.

Olav Alexander Mjelde
Admin & Webmaster
 
Apparently there is something wrong with my scripting, glad to have that settled.

My variables make sense to me, but I can understand that they're weird to others. Basically, "p" is for "category", "no" is for "number" and "lili" is just a random name.

Here's the body of the document for context:
Code:
    <div id="bom" style="width:100%; top:0px; position:relative;">
	
    	<h1 id="overskrift" class="bigdisplay" <?php if(!isset($no)){print("style='left: 22%;'");}else{print("style='left:12%;'");} ?>><?php if(!isset($p)){ print("velkommen"); }else{ print($p); }; ?></h1>
		
		<div id="tekst" <?php if(!isset($no)){print("style='left: 22%;'");}else{print("style='left:12%;'");} ?>>
		
		    <?php 
			     if(!isset($p)){
				     include 'velkommen.txt';
			     }else{
				     $po = $p;
				     $po .=  $no;
					 $po .= '.txt';
				     include $po;
				 }; 
			?>
					
		</div> <!-- tekst -->		 
		
	    <div id="links" <?php if(!isset($no)){print("style='left: 22%;'");}else{print("style='left:12%;'");} ?>>
		   	<a href="index.php?p=about" accesskey="4">- om Fortelle -</a><br />
            <a href="index.php?p=illustrasjon" accesskey="2">- illustrasjon -</a><br />
			<a href="index.php?p=webdesign" accesskey="3">- webdesign -</a><br />
			<a href="index.php?p=kontakt" accesskey="4">- kontakt -</a>
			
		</div>  <!-- links -->
		
			<div id="logostor" <?php if(!isset($no)){print("style='right: 20%;'");}else{print("style='left:12%; margin-left:-39px;'");} ?>>
		
		      <img src="fortellelo.gif" alt="FORTELLE" class="smalldisplay" /><img src="fortelle.png" alt="" class="bigdisplay" width="320" height="293" />
		   
	       </div><!-- logostor -->
	
    </div><!-- bom -->
	
		    <div id="liste" <?php if(!isset($no)){print("style='left: 22%;'");}else{print("style='left:12%;'");} ?>>
		
		    <?php 
			
			     if(isset($p)){
				     $pl = $p;
					 $pl .= 'tall.txt';
				     include $pl;
				 };
				 
							
				 if(isset($p)){?><p><?
				 
						
						while($lili > 0){ 
						if($lili != $no){ 
						    ?>
						
									<a href="index.php?p=illustrasjon&no=<? print($lili); ?>" title="link til portef&oslash;ljebilde">
									<img src="<? print($p . "/" . $p . $lili); ?>thumb.png" height="30px" width="30px" alt="" /></a><? 
									$lili -= 1;
						
						}}


					
					?> <br /><br /><img id="storsak" src="<? print($p);print($no) ?>sthumb.jpg" alt=" " /></p> <?
						   
				 } /* if lili */ 
				 
			?>
			
			
			
		</div><!-- liste -->
		
		
	
    <div id="bakbar" class="bigdisplay"  <?php if(!isset($no)){print("style='left: 22%;'");}else{print("style='left:12%;'");} ?>> </div>
	<div id="bardec1" class="bigdisplay" <?php if(!isset($no)){print("style='left: 22%;'");}else{print("style='left:12%;'");} ?>> </div>
    <div id="bardec2" class="bigdisplay" <?php if(!isset($no)){print("style='left: 22%;'");}else{print("style='left:12%;'");} ?>> </div>
	
		  <?php  if(isset($no)){?>
		    
		    <table id="stortinn" class="bigdisplay" border="0">
              <tr>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td><img id="la" src="<? print($la); ?>" alt=" " /><img id="lala" src="<? print($lala); ?>" alt=" " /></td>
              </tr>
			  <tr>
			    <td><h1 style="opacity:.50;filter:alpha(opacity=50); "><? print($tittel); ?></h1></td>
			  </tr>
            </table>
			
			<div id="storting" class="bigdisplay">
			    <div id="gradgrad" class="bigdisplay"></div>
			</div>
			<div id="bardec3" class="bigdisplay"></div>
            <div id="bardec4" class="bigdisplay"></div>
			
		  <?php } ?>
		  
		  	<p id="valids" class="bigdisplay">
			   <a href="[URL unfurl="true"]http://validator.w3.org/check?uri=referer"><img[/URL] style="border:none;"  src="valid-xhtml10.png" alt="Valid XHTML 1.0 Strict" height="31" width="88" /></a>
			</p>

I like the script you posted, but I'd like users to be able to link to the individual pages in the gallery, and making that possible with AJAX is a bit beyond me (although I know it's possible) - I'll be learning it at some point, but I'd like to have a working version of the site up ASAP.

illustration and webdesign
 
If you take your script and view-source in the browser (when you dont use the file_exists), what does it say?

eg. only the <img src=".... part, does it give you the filenames properly? Does it point to the correct directories? etc.

I think it's too much work for others to understand your code, it might be better/faster to write it all again.

What's important though, is to tink logic/structure first.
Ps. You can make a script like this, which browses subfolders.

the tn folders can be somwhere else too!

However, I would consider making 1 or 2 mysql tables and some forms for uploading images.

Then I would simply run a query on the db with SELECT ... FROM ... WHERE ... LIMIT x,y;

I would store the images in the filesystem, but save the filename in the db.

It will be faster, give you search-options, admin-possibilities, etc. it's not very hard to make either, 1-2hrs for a not so advanced script I guess (with admin interface, 2 tables, 1 upload form, user login)

Olav Alexander Mjelde
Admin & Webmaster
 
Damn lack of edit function! Sorry about this, but I managed to fix the problem. I have no idea why, but after cleaning up a bit and changing from a while loop to a for loop, it all suddenly worked. Apparently I just need to get tidier at writing code :) Sorry for wasting your time.

illustration and webdesign
 
Lol.. We all learn from our mistakes and we also learn from others mistakes :)

Ps. remember indenting your code.
If you print a lot of code, you can print \n for newline and \t for tab.

eg. echo "\n<!-- level 1 -->\n\t<!-- level 2-->\n";

Olav Alexander Mjelde
Admin & Webmaster
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top