How to ask PHP to find filename that contains something - php

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];
?>

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);
}
}

Read the filename from a folder that contains just one file

I have folders that have one file in each.
I am trying to read the name of that file and pass to variable in php.
foreach(glob('photos/folder_name/thumbs') as $filename)
{echo $filename;}
Using the above script, no data is returned for $filename. Any thoughts?
Thanks.
You need to use wildcards in the string you give to glob.
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>

rename file names php

I need to swap file names using php. For example I have two files, first file: image1.jpg and the second file: image2.jpg. I want to swap the file names. So that the first file will be names image2.jpg and the second file will be named image1.jpg;
my failed attempt at this:
function swap($name1, $name2)
{
$tempName1 = "temporary1";
$tempName2 = "temporary2";
myRename($name1, $tempName1);
myRename($name2, $tempName2);
myRename($tempName1, $name2);
myRename($tempName2, $name1);
}
function myRename($oldTitle, $newTitle)
{
$oldDirectory = "images/".$oldTitle.".jpg";
$newDirectory = "images/".$newTitle.".jpg";
rename($oldDirectory, $newDirectory);
}
How can I successfully swap the names?
Something like this will solve your problem:
swap($file1, $file2, 'test/');
function swap ($name1, $name2, $dir = '') {
rename($name1, $name1 . '-tmp');
rename($name2, $name2 . '-tmp');
rename($name2 . '-tmp', $dir . $name1);
rename($name1 . '-tmp', $dir . $name2);
}
Hope this helps!
<?php
rename('images/image1.jpg','images/tmp.jpg');
rename('images/image2.jpg','images/image1.jpg');
rename('images/tmp.jpg','images/image2.jpg');
function myRename($oldTitle, $newTitle)
{
$fullpath="C:\HD path to that file";//sth like that for full path
$oldDirectory = $fullpath."images/".$oldTitle.".jpg";
$newDirectory = $fullpath."images/".$newTitle.".jpg";
rename($oldDirectory, $newDirectory);
}
Use absolute or relative path to rename

While loop to add 1 to filename if it already exists not working in PHP

I'm trying to create a bit of code to first check the content of a directory to see if a file exists and if it does, append a number to the filename. Unfortunately I can't get it to work at the moment, the php produces no errors but a new file is not created if one already exists. Here is my code atm:
$Scan_Name_Output = "dirbuster_" . $workload["Scan_Name"] . "_output.txt";
$Check_Output = exec("ls " . $Output_Directory . " | grep -w " . $Scan_Name_Output);
$j = 1;
while (!empty($Check_Output))
{
$Scan_Name_Output = $Scan_Name_Output . $j;
$j++;
If I replace the while loop with an if statement, it works - so it's not the file paths or anything that are causing the problem. I've tried a fair few combinations but can't get it to work.
I have tried using file_exists() but it doesn't work - I think it's because I'm passing it variables that have been put through escapeshellarg(). As a result I think file_exists literally looks for /path/to/dir/'Report1.txt' - obviously 'Report1.txt' doesn't exist, Report1.txt does. This is why I was using exec and ls.
Thanks for any responses
PHP has some nice functions built in to handle files. You should think about using file_exists() for example.
$basename = "dirbuster_" . $workload["Scan_Name"] . "_output.txt";
$Scan_Name_Output = $basename;
$j = 1;
while (file_exists($Scan_Name_Output)){
$Scan_Name_Output = $basename . $j;
$j++;
}
$ourFileHandle = fopen($Scan_Name_Output, 'w') or die("can't open file");
Try this:
$Scan_Name_Output = "dirbuster_" . $workload["Scan_Name"] . "_output.txt";
if (file_exists($Scan_Name_Output))
{
rename($Scan_Name_Output, $Scan_Name_Output . "1");
}

Simple PHP echo help

How could I add an echo in here
move_uploaded_file($_FILES["torrent"]["tmp_name"], "uploads/ (HERE) .torrent");
I have tried a few things with no luck.
It's just a mere guess, but perhaps you want to do something like that:
$newFileName = 'someFielenameGeneratedByYourScript';
move_uploaded_file($_FILES["torrent"]["tmp_name"], "uploads/" . $newFileName . ".torrent");
You could do something like:
$location = "uploads/" . $name . ".torrent";
move_uploaded_file($_FILES["torrent"]["tmp_name"], $location);
echo $location;
You don't need to echo, since you are passing it to a function not trying to display it in the output.
move_uploaded_file($_FILES["torrent"]["tmp_name"], "uploads/ ".$variable." .torrent");

Categories