Deleting multiple file and its name variants with PHP from a text file list
Get the solution ↓↓↓I need to create a script to delete a bunch of images in a wordpress directory. As you may already know, a single image file can have multiple variants, depending on how the images are rendered.
Anyway, i have a list of images in a text file, which contains the following:
wp-content/uploads/2018/09/L_14BQ-FK1
wp-content/uploads/2018/09/L_15EKP160VIBROBT-KIT
wp-content/uploads/2018/09/L_29DS15172GB
wp-content/uploads/2018/09/L_29DS18172GB
wp-content/uploads/2018/09/L_29DS2415
For example i need to delete L_14BQ-FK1.jpg and its variants such as L_14BQ-FK1-100x100.jpg, L_14BQ-FK1-200x200.jpg, etc.
So far i have tried the foreach inside a foreach but its not working:
$list = file('list.txt');
if ($list === false) {
die('Cannot open file');
}
foreach($list as $file){
$theFile = glob($file.'*.jpg');
foreach ($theFile as $single){
echo $single."<br>";
}
}
Surprisingly the echo only produced the last list and its variants, L_29DS2415-100x100.jpg, L_29DS2415-100x200.jpg, etc
Can someone help please?
Answer
Solution:
Reading at the file manual at php.net, I just realised that the array returned from the function FILE include the new line, so revising my original code by adding the flags of 'FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES' works perfectly.
So the final code will be:
$list = file('list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($list === false) {
die('Cannot open file');
}
foreach($list as $file){
$theFile = glob($file.'*.jpg');
foreach ($theFile as $single){
echo $single."<br>";
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: integrity constraint violation: 1452 cannot add or update a child row: a foreign key constraint fails
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.