multiple file_exists function in one if statement overwrite each other - php

I am creating a word to image converter and for multy image words, I need to write a bit more complex if statements.
My first if statement works well for 2 image word(word = image + image):
$words = array("car", "bike",...)
foreach ($words as $x => $word) {
$jpg = "Pictures/".$words[$x] . ".jpg";
$jpg1 = "Pictures/".$word."/".$word. "1.jpg";
$jpg2 = "Pictures/".$word."/".$word. "2.jpg";
$jpg3 = "Pictures/".$word."/".$word. "3.jpg";
if (file_exists($jpg1) && file_exists($jpg2)) {
print '<div class="result1"><div id="result1" style="background-image:url('.$jpg1.')"></div>
<div id="result2" style="background-image:url('.$jpg2.')"></div>
<a id="word'. $x .'">'. $words[$x] .'</a></div>';
}
This if spatement says that if the file in directory jpg1 and jpg2 exists, print this...So if it locates just the two files in those directories it will work.
However, when I try adding a 3rd file_exists function to an else if statement like this:
else if (file_exists($jpg1) && file_exists($jpg2) && file_exists($jpg3)) {
print '<div class="result2"><div id="result3" style="background-image:url('.$jpg1.')"></div>
<div id="result4" style="background-image:url('.$jpg2.')"></div>
<div id="result5" style="background-image:url('.$jpg3.')"></div>
<a id="word'. $x .'">'. $words[$x] .'</a></div>';
}
The first if statement overrides the second one, even though the second one is correct. and the first one isn't.
I wanted to ask if everything is correct with my syntax? Or if I can even use multiple file_exists functions like this.
Or any other reason why this might not work.

Related

How to write an if statement in a foreach statement

I am currently writing a script where a user inputs a number into a form, and the script searches through a folder for an image matching that number and displays it for the user (with download button coming). Right now my code looks like this:
$photo_id = trim($_REQUEST['photo_id']);
$dir = "./wp-content/uploads/easter_pics";
$images = (scandir($dir));
foreach ($images as $value); {
$file_ext = strpos($value, ".");
$file_name = substr($value, 0, $file_ext);
if ($file_name === $photo_id) {
echo ("<img src = '../wp-content/uploads/easter_pics/" .
$file_name . ".jpg' />");
}
}
This code works only if the user inputs the number for the last image in the directory. I think I get the basic principle of what is wrong. $images keeps getting assigned the value of the last item in the array for $dir. At least I think.
The problem is I could be wrong, and also I don't know how to fix it. I want the if statement to display the image if the user input matches any photo in the directory then break.
Your foreach is wrong:
foreach ($images as $value); {
should be
foreach ($images as $value) {
(notice the missing semicolon)
That being said, for your particular case, foreach over a scanned dir might not be the best solution. Try validating the input better (e.g. use intval if the ID is always a number) and just see if the file exists.

Foreach loop depending on files in directory

Is there a way to create a foreach loop, that will run for however many instances of a filename with a sequential number exists in a directory?
For example I have one directory with images. The images will have filenames such as these:
firstname-lastname_before1.jpg
firstname-lastname_after1.jpg
firstname-lastname_before2.jpg
firstname-lastname_after2.jpg
firstname2-lastname2_before1.jpg
firstname2-lastname2_after1.jpg
firstname2-lastname2_before2.jpg
firstname2-lastname2_after2.jpg
This essentially shows photos belonging to two people. Each person has four photos, two sets of two photos, a before and after.
I can already handle the individual names when echoing out, but I'm trying to find a way to set a foreach loop that will find all sequential instances of the condition that's currently applied.
i.e. If I'm viewing a page for one person, the foreach loop should run through all files relating to that person.
At the moment I just have one hard-coded instance of the block I want to loop.
<div class="photo-set col-md-4">
<figure class="cd-image-container">
<?php $procedure = get_post_custom_values('Procedure'); ?>
<img src="<?php echo get_template_directory_uri()."/img/before-after/".preg_replace("/[\s_]/", "-", strtolower($procedure[0]))."_".preg_replace("/[\s_]/", "-", strtolower($post->post_title))."_after1.jpg";?>" alt="Original Image">
<span class="cd-image-label" data-type="original">After</span>
<div class="cd-resize-img">
<img src="<?php echo get_template_directory_uri()."/img/before-after/".preg_replace("/[\s_]/", "-", strtolower($procedure[0]))."_".preg_replace("/[\s_]/", "-", strtolower($post->post_title))."_before1.jpg";?>" alt="Modified Image">
<span class="cd-image-label" data-type="modified">Before</span>
</div>
<span class="cd-handle"></span>
</figure>
</div>
This is just using before1 and after1, as I wanted to style it up first.
So to summarise, my question is: Can I have a foreach loop that will find all files that match the condition below, that are sequentially named, and sort them into a set of 2 (for before and after)?
UPDATE:
I've tried using the glob function, but I'm really not sure this is what I'm looking. After using this code:
$procedures = get_post_custom_values('Procedure');
$procedure = preg_replace("/[\s_]/", "-", strtolower($procedures[0]));
$patientName = preg_replace("/[\s_]/", "-", strtolower($post->post_title));
foreach(glob('img/before-after/*$patientName*/*.jpg') as $filename) {
Nothing is being returned on the page. I'm not sure on how the glob expression should be. As it needs to firstly find a directory that matches $patientName, and then inside there are loads of files with different procedures in the title. Like this for an example:
tummy-tuck_john-smith_before1.jpg
tummy-tuck_john-smith_after1.jpg
tummy-tuck_john-smith_before2.jpg
tummy-tuck_john-smith_after2.jpg
nose-reshaping_john-smith_before1.jpg
nose-reshaping_john-smith_after1.jpg
etc. So how can I code it so that it will pull the correct files (in sets of two, as I have a before and after for each), for the patient name, and the procedure?
UPDATE:
This code also returns nothing, and I don't know why? The $files array is returning as 0.
$procedures = get_post_custom_values('Procedure');
$procedure = preg_replace("/[\s_]/", "-", strtolower($procedures[0]));
$patientName = preg_replace("/[\s_]/", "-", strtolower($post->post_title));
$directory = get_template_directory_uri()."/img/before-after/".$patientName."/";
$files = glob($directory.'*', GLOB_BRACE);
foreach($files as $filename) {
Can someone please help?
You can use glob() function. You can pass first param as pattern and loop through the results of the function.
Example
foreach(glob('[a-zA-Z0-9]+-[a-zA-Z_0-9]+.jpg') as $filename)
{
echo $filename;
}
You can also use \w but it depends on your conditions.

PHP syntax equivalent to SQL %

I have a folder unit_images that is full of images with random names except they have a prefix that corresponds to a PRIMARY KEY in a db table.
1_4534534fw4.jpg
2_43534tw4t45.png
You get my point. I am using YoxView to view images and am doing something like this:
<?php
$query = "SELECT id FROM images WHERE unit = ".$_GET['id']."";
$result = mysqli_query($con, $query);
echo '<div class="yoxview">';
while ($row = mysqli_fetch_assoc($result))
{
echo '<img src="unit_images/01.jpg" alt="First" title="First image" />
<img src="unit_images/02.jpg" alt="Second" title="Second image" />'
}
echo '</div>';
?>
I want to list the images from my folder unit_images WHERE the unit is the one currently being shown.I just do not know how to tell PHP the filename. I want to do something similar to a 1_% in SQL. Does that make sense? Since I do not know what the rest of the filename looks like I just need to tell php it doesn't matter.
The closest equivalent to SQL's % wildcard that works for files is the shell's * wildcard, which is available in php through the glob() function. You can iterate through its results as follows:
foreach (glob("unit_images/1_*.jpg") as $filename) {
echo '<img src="unit_images/' . htmlspecialchars(basename($filename))
. '" />';
}
If I understand you correctly, you want to get a list of items in a directory with a certain prefix.
Step 1 (use sandir() to determine the items in the directory):
$files = scandir('unit_images');
Step 2 (eliminate the unwanted image names):
for ($i=0; $i<count($files); i++)
{
$file = $files[i];
$prefix = explode("_", $file)[0];
if ($prefix != $_GET['id'])
{
unset($files[i]);
}
}
$files is now an array of only the file names prefixed with $_GET['id]
My advice would be to store the whole name of the file in a column so that you can reference it directly instead of having to search in the file system for a matching name.
Having said that, you can search for a file using the glob PHP function.
Maybe you can do something like this:
glob("unit_images/<YOUR_PRIMARY_KEY>_*.{png,jpg}", GLOB_BRACE);

How to batch add images with similar name using jquery/ php

I'm adding images to a website but the amount I want to add would take a long time, is there a quicker way of adding these images and for it to automatically find new images if the file name was appended +1 such as image1.jpg, image2.jpg etc.
I am using PHP. Also thought maybe this could be done using a javascript or jquery loop, for loop maybe, im just unsure how.
<img src="images/other/pic2.png"></a>
<img src="images/other/pic3.png"></a>
<img src="images/other/pic4.png"></a>
<img src="images/other/pic5.png"></a>
<img src="images/other/pic6.png"></a>
<img src="images/other/pic7.png"></a>
<img src="images/other/pic8.png"></a>
Its not a good idea to blindly loop a curtain amount of iterations hoping that the file is there and is a valid file, a better way would to loop the directory of files, check that the file is first a valid image and contains the expected filename prefix. This way you can add as may images to the dir knowing that there be added without changing code.
<?php
$img_path = './images/other/';
$prefix = 'img';
if ($fh = opendir($img_path)) {
while (false !== ($file = readdir($fh))) {
if ($file != "." && $file != "..") {
//Validate its an image and get size, also check that the image filename starts with the $prefix
$attr = getimagesize($img_path.$file);
if(isset($attr[3]) && substr($file,0,strlen($prefix)) == $prefix){
echo '<img src="'.$img_path.$file.'" '.$attr[3].' alt="'.$file.'"/>';
}
}
}
closedir($fh);
}
?>
Well judging by your description, doing something like this would probably be suitable:
$initialImageNumber = 2;
$endingImageNumber = 9;
for ($i = $initialImageNumber; $i <= $endingImageNumber; $i++)
echo '<img src="images/other/pic' . $i . '.png">';

PHP If folder exists do a loop for each subfolder

I am trying to get my code to work. I basically check that if a folder exists, and any sub folder exists within that directory called 3 or more (3,4,5) then do a loop, otherwise nothing.
// the folder path
$folderPath="".cdnurl."assets/".pid."";
// looks like site.com/assets/342/
// is there a sub folder called 3 or more, 3,4,5 and loop from 3
// site.com/assets/342/3
// site.com/assets/342/4
// etc, we only loop if 3 exists other wise nothing
$folderSubNumber =>3;
while(file_exists($folderPath.$folderSubNumber)) {
echo '<li><img src="assets/pid/'.folderSubNumber.'';
} else {
// nothing
echo "";
}
It looks like what you have should do it. Just change that => to a simple =, and don't forget to increment:
while (file_exists($folderPath.$folderSubNumber)) {
echo '...';
$folderSubNumber += 1;
}
(Also, the else part isn't allowed. But you don't need it here, so nothing lost.)
A simple method:
$subdirs = glob(cdnurl . "assets/" . pid . "/*", GLOB_ONLYDIR);
that'll return all subdirectories in the specified directory. Ref: http://php.net/glob
Prepare for some constructive criticism, please.
There's a lot wrong with this code. First I'll add comments to explain some of the mistakes as well as some of the pointless things that do nothing.
$folderPath="".cdnurl."assets/".pid."";
// 1. Single-quotes will perform slightly better.
// 2. There is no need for the first "". or the final ."" - they do nothing.
// 3. Ideal: $folderPath = cdnurl.'assets/'.pid;
// 4. This assumes that cdnurl and pid are constants declared with the define() command. If they are not constants, you need dollar-signs, which would make it:
// $folderPath = $cdnurl.'assets/'.$pid;
$folderSubNumber => 3;
// You cannot put a "more than X" or "less than X" in a variable. The => is used in foreach() loops for a completely different purpose, and when declaring values in an array only when the array is originally declared. (In other words; in this case, this does nothing.)
// Indentation really does matter. This should be indented the same as the code above.
while(file_exists($folderPath.$folderSubNumber)) {
// 1. $folderSubNumber never changes and so this while-loop always asks the exact same question.
// 2. You don't have a directory separator "/", so this will append $folderSubNumber straight to pid, above.
echo '<li><img src="assets/pid/'.folderSubNumber.'';
// 1. folderSubNumber needs a dollar-sign because it's a variable. If it is not defined as a constant, it will simply be the literal string "folderSubNumber".
// 2. The appended .'' does nothing and shouldn't be there.
// 3. You are neither closing the <img> tag, nor the <li> tag, nor in fact the src-attribute.
// 4. Ideal: echo '<li><img src="assets/pid/'.$folderSubNumber.'" /></li>';
} else {
// 1. There is no "else" in while.
// 2. You don't need an "else" if the intention is to do nothing.
echo "";
// This is 100% pointless, it does nothing.
}
What you then need, is to increment $foldeSubNumber after you've tried it in the while-loop (see the answer by 'sdleihssirhc'). But also note that you probably need the directory separator between $folderPath and $folderSubNumber. That would be: $folderPath.'/'.$folderSubNumber
Good luck!
// Build folder path
$folder_path = cdnurl . 'assets/' . $pid . '/';
// Loop from 3 to 5
for ($i = 3; i <= 5; $i++) {
// Checking for a valid sub-directory
// Will check sub-directory e.g.: site.com/assets/342/3/
if ( is_dir($folder_path . $i . '/') ) {
// Sub-directory exists
echo $folder_path . $i;
} else {
// No Sub-directory, break out of for loop
// This is will stop PHP for looking for sub-directory 4 or 5
break;
}
}

Categories