checking existence of file start from name "sample" using php - php

Could someone help me with how I can check the existance of files which starts with any name like sample1.pdf, sample12.pdf in a particular folder using PHP? Below is my code for checking a single file.
<html>
<?php
if(file_exists("properties/".$owner."/".$property."/sample1.pdf") )
?>
</html>

The PHP function glob (here) will provide you an array of files that match. So you can do the following:
$files = glob("properties/{$owner}/{$property}/sample*.pdf");
This will then return an array of files within the "properties/{$owner}/{$property}/" directory that start with "sample" and have an extension of .pdf
You can then loop through the files and do what you need
//Check if there are any files and there were not any FATAL errors
if (count($files) > 0 && $files !== FALSE) {
foreach ($files as $file) {
//Do something here
}
} else {
//There were no matching files
}
Hope this helps

Related

PHP best way to call loop function multiple time

I have a specific directory which may contain zip files.
I would like to loop through each sub-element of my directory to check if this is a zip. And unzip that. Then process the others files.
I'm using flysystem to work with my files.
So I went for this
$contents = $this->manager->listContents('local://my_directory , true);
foreach ($contents as $file) {
if( $file['extension'] == 'zip')
//Unzip in same location
}
The problem is that the files unziped are not in the loop and if the zip file, contain another zip. The second one will be never be unziped.
So I thought about it
function loopAndUnzip(){
$contents = $this->manager->listContents('local_process://' . $dir['path'] , true);
foreach ($contents as $file) {
if( $file['extension'] == 'zip')
//Unzip and after call loopAndUnzip()
}
}
But the initial function will never be finished and be called over and over if there are zip inside zip.
Isn't it a performance issue?
How to manage this kind of thing?
You can use glob to find them, and make the function recursive. You can do this by starting at a certain dir, unzip all the files into it & check if there are new zips.
I recommend using recursive directories as well. If A.zip and B.zip both have a file called example.txt, it overwrites. With dirs it wont:
function unzipAll(string $dirToScan = "/someDir", $depth=0):void {
if($depth >10 ){
throw new Exception("Maximum zip depth reached");
}
$zipfiles = glob($dirToScan."*.zip");
// Unzip all zips found this round:
foreach ($zipfiles as $zipfile) {
$zipLocation = "/".$zipname;
// unzip here to $zipLocation
// and now check if in the zip dir there is stuff to unzip:
unzipAll($dirToScan.$zipLocation, ++$depth);
}
}
The $depth is optional, but this way you cant zipbomb yourself to death.
loopAndUnzip will do all files again, so you will just again unpack the same zipfile and start over with the entire folder, ad infinitum.
Some possibilities:
Keep a list of items that was already processed or skipped and don't process those again, so while iterating over $contents, keep a separate array, and have something like:
PHP:
foreach ($contents as $file) {
if (!array_search($processedFiles, $file) {
if( $file['extension'] == 'zip')
//Unzip in same location
}
$processedFiles[] = $file;
}
Use an unzipper that returns a list of files/folders created, so you can explicitly process those instead of the full directory contents.
If the unzipper can't do it, you could fake it by extracting to a separate location, get a listing of that location, then move all the files in the original location, and process the list you got.

PHP Find files with specific name part in folder

Is there a way to get all the files with a specific name from a folder with php?
For example I have in folder next files:
6546-da6sd.png
465-dasd.jpg
654-548484.jpg
654-sasaf.png
654-sakj879.jpg
776-54fsdfs.png
....
I want to get all files that start with "654-" (but not the first (6546-da6sd.png))
Thank You!
you can use glob() and strpos() like:
<?php
$dir = 'files/';
$key = '654-';//search key
foreach (glob("$dir*") as $file) {
$file = str_replace($dir,'',$file);
if (strpos($file, $key) == 0) {
echo($file."<br>");
}
}
?>

Deleting files in php directory

if(unlink('./'.date('m-d-Y').'/'.$file))
{
echo "file named $file has been deleted successfully";
}
else
{
echo "file is not deleted";
}
I have the code above to delete my files.
However, is it possible to only let it delete files that contain ".5010."
Can I do something like "%.5010.%" or something, also if its more than one file do I need to put it in a while or a foreach loop? Because now it deletes all my files.
You can use glob() to find the pathnames matching a pattern.
So your code would look something like this,
$path="./".date('m-d-Y')."/*".$file."*";
$files = glob($path); // this will return multiple files.
foreach ($files as $file) {
unlink($file);
}
glob() returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
You can loop on file with glob and after use preg_match to select files who match a pattern
<?php
foreach(glob('path/to/dir/*.*') as $file) {
if (preg_match('*.5010.*', $file)) {
unlink($file)
}
}

Comparing files and creating notepad to tell which line is different in php

I was stuck for sometime after this some sort of code. I'm not so new yet not so old in coding using php but I need help with regards to this one.
I have two directories which has more than 1 file, it may come as text or xml.
Lets say directory 1 is populated today and directory 2 will be populated tom.Both directories have the same number of files and the same name and order.
What I want to have is a comparing tool which will comapre each and every file but of course i need to compare those with similar names and then if there's a difference or update in either of the file, it will create a notepad which will write the filename, line in which they have difference.
I came up to this part but im stuck and i need your help guys.
Thanks.
<?php
$dirA = glob('C:\Users\aganda88\Desktop\testing docs\testingdocs1\*');
$dirB = glob('C:\Users\aganda88\Desktop\testing docs\testingdocs2\*');
//Checking that the files are the same
foreach($dirA as $fileName) {
// the file exists in the other folder as well with the same name
if ($exists = array_search($fileName, $dirB) !== false) {
// it exists!
if (md5_file($fileName) !== md5_file($dirB[$exists])) {
// The files are not identical so i need to create a text file to show what line is not the same
copy($fileName, $dirB[$exists]);
/* problem here is you didn't specify which in your requirements */
}
} else {
// it doesn't (what to do here? you didn't specify!)
}
}
// compare the other way
foreach($dirB as $fileName) {
// does the file exist in the other directory?
if ($exists = array_search($fileName, $dirA) !== false) {
// it exists!
if (md5_file($fileName) !== md5_file($dirA[$exists])) {
copy($fileName, $dirA[$exists]);
}
} else {
// it doesn't (what to do here? you didn't specify!)
}
}
?>
Get a list of all files in each directory
You can use glob to grab a list of files in each directory...
$dirA = glob('C:\Users\aganda88\Desktop\testing docs\testingdocs1\*');
$dirB = glob('C:\Users\aganda88\Desktop\testing docs\testingdocs2\*');
Checking that the files are the same
You can do a simple md5 checksum on matching filenames to determine if they are identical or not.
foreach($dirA as $fileName) {
// does the file exist in the other directory?
if ($exists = array_search($fileName, $dirB) !== false) {
// it exists!
if (md5_file($fileName) !== md5_file($dirB[$exists])) {
// The files aren't identical so one of them needs updated
copy($fileName, $dirB[$exists]);
/* problem here is you didn't specify which in your requirements */
}
} else {
// it doesn't (what to do here? you didn't specify!)
}
}
// compare the other way
foreach($dirB as $fileName) {
// does the file exist in the other directory?
if ($exists = array_search($fileName, $dirA) !== false) {
// it exists!
if (md5_file($fileName) !== md5_file($dirA[$exists])) {
copy($fileName, $dirA[$exists]);
}
} else {
// it doesn't (what to do here? you didn't specify!)
}
}
Update files
There's one part of your requirements that you have not clearly defined behavior in... Which file do you update? Because while a change may have been made to C:\Users\aganda88\Desktop\testing docs\testingdocs1\test1.txt these requirements do not distinguish between you overwriting C:\Users\aganda88\Desktop\testing docs\testingdocs1\test1.txt with C:\Users\aganda88\Desktop\testing docs\testingdocs2\test1.txt or C:\Users\aganda88\Desktop\testing docs\testingdocs2\test1.txt with C:\Users\aganda88\Desktop\testing docs\testingdocs1\test1.txt... i.e. the fact that the files are not the same doesn't specify which one should be the source and which one should be the destination. Without that it doesn't really matter if you know that they aren't the same or not...

File Exist and catch all searchs

I'm trying to find if a file exists. I know the name of it but I do not know the extension. What could I do PHP wise so that the file exists function checks for the file without knowing it's extension?
file_exists('image_storage/ses_' . $session_user_id . 'need to put something here for the
extension' );
You could use PHP's glob function to get a list of files that match a given pattern:
$files = glob('image_storage/ses_' . $session_user_id . '.*');
if (count($files) > 0) {
// check your files with a loop
foreach ($files as $file) {
// do whatever you want; this file exists =]
}
}
You won't need to check if the file exists with glob; if it returns it in the array, it should exist.
If you are in linux you can do this..
$ret = exec("ls image_storage/ses_" . $session_user_id."*");
if(!empty($ret))
{
//file exists..
}

Categories