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.
If/Else with form
Moderator: General Moderators
Re: If/Else with form
If you know the name of the potential files you can use the following php function.
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
file_exists('location/of/the/file.name')
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
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.
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
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
Here is the source:
<img src='imagefolder/imagefolder/IMG_3508.jpg' />imagefolder/IMG_3508.jpg <br />
I think I can see the problem!
<img src='imagefolder/imagefolder/IMG_3508.jpg' />imagefolder/IMG_3508.jpg <br />
I think I can see the problem!
Re: If/Else with form
Ok perfect, I can see the problem, change the line:
To:
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='$dir/$file' />$file <br />";
Code: Select all
print "<img src='$file' />$file <br />";
Code: Select all
print "<img src='$file' />" . str_replace("imagefolder/", "", $file) . " <br />";
Re: If/Else with form
Perfect.
Thanks.
Thanks.