Delete Array Of Filenames Inside A Foreach Loop Using PHP - php

I am creating a 'delete account' function for users of a site if they want to delete all of their details.
Deleting the relevant records from the database has been pretty straight forward. However, I want to deleted the images they have saved in the site's images folder.
Below is the code I'm trying, a part of which is based on #kmoser's suggestion.
// $db_image_id, $db_image_ext, $db_image_filename are fetched in a previous code block for when images are outputted on the page.
if(isset($_POST['delete-account'])) {
$loggedInUser = $_SESSION['logged_in'];
$imagesLibrary = 'images-lib/';
$imagesDownload = 'images-download/';
try {
$s = $connection->prepare("SELECT filename FROM `imageposts` WHERE user_id = :user_id");
$s->bindParam(':user_id', $loggedInUser);
$s->execute();
// -- DELETE THE USER'S IMAGE FILES FROM 'IMAGES-LIB' FOLDER
while ($row = $s->fetch()) {
if (isset($pattern)) {
$pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}' . '.' . $row['file_extension'];
foreach (glob($pattern, GLOB_BRACE) as $filenames) {
unlink($filenames);
}
}
}
header("Location: index.php");
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
The key piece of the above code is this snippet below:
// -- DELETE IMAGE FILES FROM 'IMAGES-LIB' FOLDER
while ($row = $s->fetch()) {
if (isset($pattern)) {
$pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}' . '.' . $row['file_extension'];
foreach (glob($pattern, GLOB_BRACE) as $filenames) {
unlink($filenames);
}
}
}
I was initially getting an error PHP Notice: Undefined index: file_extension in /Applications/MAMP/htdocs/site/profile-edit.php in relation to the 3rd line of PHP code above that declares the $pattern variable. I've managed to fix this by wrapping the code in the if(isset($pattern)) if statement that is now present. I don't get any error logs now, but the files are not being deleted out of the 'images-lib' directory.
A typical filename example is 6146972e2dc73_1632016174-500.jpeg
Here is an example of how the files look in the database:
When outputted onto a page in an <img> tag, the size e.g. -500 part of the filename is concatenated on with a string inside the src attribute.
src="<?php echo '/images-lib/' . $db_image_filename . '-500' . '.' . $db_image_ext; ?>"
Any help or assistance on how to delete images specific to a user from the images directory would be wonderful.

There's no need to store the filenames and extensions in separate arrays, or even in an array at all. Just fetch every image filename and extension in a loop, assemble it into a pattern (e.g. images/6146972e2dc73_1632016174-{500,750,1000,1500}.jpeg, then glob() the pattern to find each matching file and unlink it:
while ($row = $s->fetch()) {
$pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}.' . $row['file_extension'];
foreach (glob($pattern, GLOB_BRACE) as $filename) {
unlink($filename);
}
}

Related

Check if filename from directory exists as a value in database

I have a bunch of .png's in a directory that are named the same as the values in the database. I would like to do a check if the filename (without '.png') exists in the database or not.
At the moment I am using this code to display the flags those are in the database
<?php
$result = mysql_query("SELECT `country` FROM `countries`");
while($row = mysql_fetch_array($result)) {;
?>
<img src="images/countries/<?php echo $row['country']?>.png" />
<?php }; ?>
Since there are only 3 countries in the column it's displayed as:
I would like to display the flags that are not in the database as well, but then in greyscale.
I came up wit this code to get all the flags from the directory
<?php
$directory = "images/countries/";
$images = glob($directory . "*.png");
foreach($images as $image)
{
echo '<image src="'.$image.'" class="flaginactive"/>'; //show all flags as inactive
echo basename($image, '.png'); //get file name with .png
}
?>
But somehow I am stuck and clueless how I could get them both in an if statement.
Can someone advise me how I can solve this the best way. I am aware I am using the old mySQL functions.
There are many ways to achieve this. I will relate one.
First load the names in the database in to an array. Then check the existence of the enumerated file names of the directory in the array to decide the class of the element.
Elements are shown inactive if a file in the directory is not found in the database.
<?php
$directory = "images/countries/";
//Lets save all the file names in the database to an array
$dbImages = array();
$result = mysql_query("SELECT `country` FROM `countries`");
while($row = mysql_fetch_array($result)) {
array_push($dbImages, $directory . $row['country'] . '.png');
}
//Lets go through all the files in the directory and see if they are in the $dbImages array
$images = glob($directory . "*.png");
foreach($images as $image)
{
//Decide the class attribute based on the existence of the file name in $dbImages array
if (in_array($image, $dbImages))
$classAttribute = '';
else
$classAttribute = 'class="flaginactive"'
echo '<image src="'.$image.'" ' . $classAttribute . ' />';
}
?>
You can file_exists() function like this
<?php
$directory = "images/countries/";
$images = glob($directory . "*.png");
foreach($images as $image)
{
if(file_exists($_SERVER['DOCUMENT_ROOT'] . $directory . $image . '.png')) //Files exists goes here
{
echo '<image src="'.$image.'" class="flaginactive"/>'; //show all flags as inactive
echo basename($image, '.png'); //get file name with .png
}
}
?>

How to remove image from web root when data edit and update by cakephp

I write a edit function to update news's info, delete previous image from web root and insert new image:
code is below:
if(unlink($data['News']['image_url']['tmp_name'], WWW_ROOT . 'media/' . $data['News']['image_url']['name'])) //delete image from root and database
{
echo 'image deleted.....'; //success message
}
I can't delete old image and insert new image,how can i correct my function ?
Here your data can not find existing data. use this code
$data1 = $this->News->findById($newsid);
$this->request->data = $data1;
$directory = WWW_ROOT . 'media';
if(unlink($directory.DIRECTORY_SEPARATOR.$data1['News']['image_url']))
{
echo 'image deleted.....';
}
Pass filepath as first argument of unlink():
unlink(WWW_ROOT . 'media/' . $data['News']['image_url']['name'] . '/' . $data['News']['image_url']['tmp_name']);
Also make sure that you have proper permissions to perform this operation in directory containing image.

PHP - Moving multiple files with different files names to own directory

Hi wonder if you can help,
I'm looking to do this in PHP if someone can help me. I have a number of files that look like this:
"2005532-JoePharnel.pdf"
and
"1205121-HarryCollins.pdf"
Basically I want to create a PHP code that when someone ftp uploads those files to the upload folder that it will 1) Create a directory if it doesn't exist using there name 2) Move the files to the correct directory (E.g. JoePharnel to the JoePharnel Directory ignoring the number at the beginning)
I have looked through alot of code and found this code and have adapted it:
<?php
$attachments = array();
preg_match_all('/([^\[]+)\[([^\]]+)\],?/', $attachments, $matches, PREG_SET_ORDER);
foreach ($matches as $file) {
$attachments[$file[1]] = $file[2];
}
foreach ($attachments as $file => $filename) {
$uploaddir = "upload" . $file;
$casenumdir = "upload/JoePharnel" . $CaseNumber;
$newfiledir = "upload/JoePharnel" . $CaseNumber .'/'. $file;
$each_file = $CaseNumber .'/'. $file;
if(is_dir($casenumdir)==false){
mkdir("$casenumdir", 0700); // Create directory if it does not exist
}
if(file_exists($casenumdir.'/'.$file)==false){
chmod ($uploaddir, 0777);
copy($uploaddir,$newfiledir);
}
$allfiles = $CaseNumber .'/'. $file . "[" . $filename . "]" . ",";
$filelistfinished = preg_replace("/,$/", "", $allfiles);
echo $filelistfinished;
// displays multiple file attachments on the page correctly as: casenumber/testfile1.pdf[testfile1.pdf],casenumber/testfile2.pdf[testfile2.pdf],
],
}
?>
Sorry for the lack of code but best i could find.
Any help is much appreciated.
Thanks.

path to image folder on server

i have a wordpress inside Public html folder on server.
i want to dispaly images from the folder Public_html--->Trial-->Wordpress_site-->uploads
below is page.php code
<?php
$directory = dirname(__FILE__).'/uploads';
echo $directory;
try {
// Styling for images
foreach ( new DirectoryIterator("/" . $directory) as $item ) {
if ($item->isFile()) {
echo "<div class=\"expand_image\">";
$path = "/" . $directory . "/" . $item;
echo $path;
echo "<img src=/"". $path . "\" width=861 height=443 />";
echo "</div>";
}
}
}
catch(Exception $e) {
echo 'No images found for this player.<br />';
}
?>
The images arent getting displayed..
anyone knows about the same??
edit1
I think there is problem in this sentence
echo "<img src=/"". $path . "\" width=861 height=443 />";
is it?
edit2
//home/softwar2/public_html/Pradnnya_blog/wordpress_site/wp-content/themes/deep-red/our_results/4thpanelfinal.jpg
is the path that i get when echoed.
__FILE__ gives you the path of the current file on the filesystem; however, when you visit the webpage and you see a link in the tag, you'll try to access that as a URL instead of a file. For this, you might find $_SERVER['PHP_SELF'] useful, or another one of the $_SERVER elements. It might be better to have the URL in a configuration file though, because $_SERVER may sometimes not be set.
Good catch, there's a bit of a syntax error:
echo "<img src=\"". $path . "\" width=861 height=443 />";
You'll want to use the backslash to escape the double quote.

List files on directory and build the html

I'm making a page with some flash games, but, since in the past will be many games it will be very bored to add all those games one by one on the site. I know that using PHP we can get the list of the files in the directory and I know that, using this method, I can display all the games on the directory to the visitors page but, I was thinking if you can help me to add an image to each game that corespond with the name of the game. Ex:
In "games" folder we will have games: play1.swf, play2.swf, play3.swf
and, in "images" directory we will have images: play1.jpg, play2.jpg, play3.jpg.
To display the list of the games, can we make a combination of jpg files with swf files? Play1.jpg will be the image of play1.swf game and, when a visitor clicks on the image, will be redirect to a page named ex: playgames.php?play1
assuming this directory structure:
/foo/images
game1.jpg
game2.jpg
/foo/games
game1.swf
game2.swf
Something like this:
<?php
$dir = "/foo";
$files = new DirectoryIterator($dir . DIRECTORY_SEPARATOR . 'games');
$games = array();
foreach($files as $file){
if (!$file->isDot()) {
$potential_image_location = $file->getPath() . '/../images/' . $file->getBasename('.swf') . '.jpg';
if (file_exists($potential_image_location)) {
$games[$file->getBaseName()] = array(
'game_path' => $file->getPathname(),
'image_path' => realpath($potential_image_location),
);
}
}
}
if (!count($games)) {
die("Sorry, couldn't find any game / image combos");
}
?>
<table>
<?php
foreach ($games as $game_name => $info) {
echo '<tr><td><img src="' . htmlentities($info['image_path']) . '" alt="' . htmlentities($game_name) . '"></td>' . PHP_EOL;
echo '<td>' . $info['game_path'] . '</td></tr>';
}
?>
</table>
its all about using opendir in a clever way, heres the docs on it http://php.net/manual/en/function.opendir.php

Categories