Check if filename from directory exists as a value in database - php

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
}
}
?>

Related

Delete Array Of Filenames Inside A Foreach Loop Using 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);
}
}

Access image with PHP when the file name is unknown

How could I get image using PHP if I don't know it's name?
Explanation: when user uploads image to the server, the image gets such name: user_id_timestamp.jpg. Now I want to access this image, but I only know half of it's name: <img src="user_id_*.jpg"/>. The * part is unknown. Thanks for help.
I think your looking for glob()
So you can do something like this:
<?php
$userId = 234567865;
foreach (glob($userId . "_*.jpg") as $filename)
echo "$filename size " . filesize($filename) . "<br />";
?>
Example output could be:
234567865_1418760613.jpg size 879394
EDIT:
If you want to stop the script if you found the image you can use this:
<?php
$userId = 234567865;
$pattern = $userId . "_*.jpg";
foreach (glob($pattern) as $filename) {
if (strpos($filename, $userId) !== true) {
echo "User: $userId File: $filename";
break;
}
}
?>
Example output could be:
User: 234567865 File: 234567865_1418760151.jpg
If you have multiple files from the same user and you want the image with the newest timestamp use this:
<?php
$userId = 234567865;
$pattern = $userId . "_*.jpg";
$last = 0;
$newest = 0;
foreach (glob($pattern) as $filename) {
if(substr($filename, strpos($filename, "_") + 1) > $last)
$newest = $filename;
$last = substr($filename, strpos($filename, "_") + 1);
}
echo "The newest avatar image from user: $userId is: $newest";
?>
Example output could be:
The newest avatar image from user: 234567865 is: 234567865_1418760151.jpg
For more information see: http://php.net/manual/en/function.glob.php

php code to display images from directory not working

i have this code to display images, where each user has his own, i'll comment it to save your time
<?php
session_start();
$name=$_SESSION['valid_user']; //saved current username in variable
$loc="./uploads/"; //location of image directory
$path=$loc.$name; //current user's folder to save his images
echo $path."<br>"; //i used this to make sure the path is ok, only for testing
if(is_dir($path)) //if directory exists, show it exists,otherwise show it
{ //doesnt exists
echo "<br>exists";
}
else
{
echo "<br>not exists";
}
$files = glob($path."/");
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i]; //picture number
print $num."<br />";
echo '<img src="'.$path.'" alt="random image" height="100" width="100"/>'."<br /><br />";
} //shows the picture till the last one
?>
the output that i get is this this
./uploads/user_name
exists
but it does not show the images, even though the folder is not empty (upload script works fine).
EDIT; solved it (low rep, cant answer my own question).
got it. For anyone who cares, this line here
echo '<img src="' . $path . '/' . $files[$i] . '" <!-- etc --> />';
wasn't working because i added $files, which already contained the path, and it was giving input to img src as
/uploads/username/uploads/username
so that was two times the same path.Upon removing $path, and using just
<img src="' . $files[$i] . '"
did the trick. Thank you all for your help.
I think you need to pass a wildcard path to glob: glob($path . '/*'). You are also not printing the filename in the image source attribute:
echo '<img src="' . $path . '/' . $files[$i] . '" <!-- etc --> />';
Also, your $num is actually the filename, not the picture number - that is $i. You could really simplify that loop using the foreach construct:
foreach($files as $filename) {
// etc
}
you need to add a pattern for using glob afaik
$files = glob($path."/*.*"); // all files
$files = glob($path."/*.jpg"); // all jpgs etc.pp
foreach($files as $idx => $file)
{
$num = $idx+1; //idx starts with 0 so we add one here
print $num."<br />";
echo '<img src="'.$path.'/'.$file'" alt="random image" height="100" width="100"/>'."<br /><br />";
}

PHP Storing/Retrieving image names in MySQL DB

I am currently working on a multiple image uploader with file directory. I am wanting to store file name inside my MySQL.
How can I store these variables(image names) inside my table through php ?
How can I retrieve the variables through php?
URL Generate by uploader:
http://www.website.com/imageupload/index.php?i=4ff4bfd02c241.jpg
http://www.website.com/imageupload/index.php?i=4ff4bfd02c242.jpg
Filename:
4ff4bfd02c241.jpg
4ff4bfd02c242.jpg
Table Name: urlimage
id: autoincrement
image_name
I am able to echo out the path and the name through this:
$images = explode(',', $_GET['i']);
$path = Configuration::getUploadUrlPath('medium', 'target');
foreach ($images as $image) {
echo '<div><p>' . $path . $image . '</p><img src="' . $path . $image . '" /></div>';
}
?>
$images = explode(',', $_GET['i']);
$path = Configuration::getUploadUrlPath('medium', 'target');
if(is_array($images)){
$sql = "INSERT INTO `urlimage` (`image_name`) VALUES ";
foreach ($images as $image) {
//echo '<div><p>' . $path . $image . '</p><img src="' . $path . $image . '" /></div>';
$value[] = "(".$path.$image.")"; // collect imagenames
}
$sql .= implode(',', $value).";"; //build query
//don't know how you send queries, you should use a kind of mysqli-functionality
queryfunction($sql);
}
Addiontally: you should think of using $_POST rather than $_GET becaus there's a length limit depending on the browser (some of them cut URLs after 255 chars).
Also never put in userdefined content directly into you DB. You'll need some kind of escaping ( http://php.net/manual/en/function.mysql-real-escape-string.php ).

How to ask PHP to find filename that contains something

im trying to do this :
$filename = "/destination/destination2/file_*";
" * " = anything
destination2 files :
file_somethingrandom
and since it $filename contains * so it should be selecting file_somethingrandom
how to do it?
Use the glob() function like this:
$filename = "/destination/destination2/file_*";
foreach (glob($filename) as $filefound)
{
echo "$filefound size " . filesize($filefound) . "\n";
}
Try this
foreach (glob("/destination/destination2/file_*") as $filename) {
echo $filename;
}
Cheers!
You can use different functions other than echo, but it does what it does, randomly picks a filename in a group of files inside "/destination/destination2/" whose name contains "file_".
<?php
$filea = glob('/destination/destination2/file_*');
echo $filea[rand(0,count($filea)-1];
?>

Categories