Page 1 of 1

If/Else with form

Posted: Fri Apr 10, 2009 12:42 pm
by WayneG
I have a directory which will have 1 or 0 images in it.
I want to say "IF there is a file in the directory, print it, ELSE print the form."
Here is the code I am struggling with:

<?php

$dir = 'imagefolder';
if (count(glob("$dir/*")) === 1) {

$handle = opendir('imagefolder');
if($handle) {
while(false !== ($file = readdir($handle))) {
if(preg_match("/\w+(.jpg)/",$file)) {
print "<img src='imagefolder/$file'>";
print "$file <br>";
}
}
closedir($handle);
}
else {
?>

<fieldset>
<legend>Image upload</legend>
<p>Select Matchcard from your computer and click 'Upload' </p>
<form name="form" enctype="multipart/form-data" method="post" action="upload.php" />
<p><input type="file" size="32" name="my_field" value="" /></p>
<p class="button"><input type="hidden" name="action" value="image" />
<input type="submit" name="Submit" value="Upload" /></p>
</form>
</fieldset>

<?
;
}
}
?>

Hope someone can help.
Wayne.

Re: If/Else with form

Posted: Fri Apr 10, 2009 1:42 pm
by nyoka
If you know the name of the potential files you can use the following php function.

Code: Select all

 
file_exists('location/of/the/file.name')
 
Alternatively you can get a list of .jpg files using the code below which would allow you to simplify the main IF statement.

Code: Select all

 
<?php
$files = array();
$dir = 'imagefolder';
$files = glob("$dir/*.jpg", GLOB_NOSORT);
if (count($files) > 0) {
    foreach ($files AS $file)
        print "<img src='$dir/$file' />$file <br />";
} else {
?>
.... form goes here ....
<?php
}
?>
 

Re: If/Else with form

Posted: Fri Apr 10, 2009 2:04 pm
by WayneG
Thanks for that swift reply.
It works except I seem to have trouble with " print "<img src='$dir/$file'>$file <br />"; "
I can only see the logo of where the image should be, not the image itself.
Any ideas?
Thanks,
Wayne.

Re: If/Else with form

Posted: Fri Apr 10, 2009 3:12 pm
by nyoka
Can you view source and post just the html code that is outputted for the image bit I should be able to help.

Re: If/Else with form

Posted: Fri Apr 10, 2009 3:52 pm
by WayneG
Here is the source:
<img src='imagefolder/imagefolder/IMG_3508.jpg' />imagefolder/IMG_3508.jpg <br />
I think I can see the problem!

Re: If/Else with form

Posted: Fri Apr 10, 2009 6:06 pm
by nyoka
Ok perfect, I can see the problem, change the line:

Code: Select all

 
print "<img src='$dir/$file' />$file <br />";
 
To:

Code: Select all

 
print "<img src='$file' />$file <br />";
 
This is because the variable contains the directory info, you may want to display just the file in which case use:

Code: Select all

 
print "<img src='$file' />" . str_replace("imagefolder/", "", $file) . " <br />";
 

Re: If/Else with form

Posted: Mon Apr 13, 2009 5:45 pm
by WayneG
Perfect.
Thanks.