php check if file exist: check only portion - php

in php we can check if file exist using
if(file_exists("destination/"))
{
condition
}
but what I wanted to do is...
for example I already have this file on my destination
hello_this_is_filename(2).doc
how would I know if there is a file in that directory having a name containing a character
hello_this_is_filename
I wanted to search that way because... if there is exists on that directory, what will I do is... renaming the file into
hello_this_is_filename(3).doc
I also need to count the existence of my search so I know what number I'm going to put like
(3), (4), (5) and so on
any help?

Use glob.
if (count(glob("destination/hello_this_is_filename*.doc"))) {
//...
}

Leveraging Marc B's suggestion and xdazz, I would do something as follows:
<?php
$files = glob("destination/hello_this_is_filename*");
if (count($files)) {
sort($files);
// last one contains the name we need to get the number of
preg_match("([\d+])", end($files), $matches);
$value = 0;
if (count($matches)) {
// increment by one
$value = $matches[0];
}
$newfilename = "destination/hello_this_is_filename (" . ++$value . ").doc";
?>
Sorry this is untested, but thought it provides others with the regexp work to actually do the incrementing...

Related

Finding a filename match in two directories and writing the matched filename to an array

I have looked on Stackover for a simular issue but can't find a solution.
I am trying to write a script that looks at the content of two directories to findout if a filename match can be found in both
directories. If a match is found write the name of the matched filename to an array.
The first thing I am doing is using""scandir" to create an array of data from the first directory.
In the "foreeach"loop through the array from the "scandir" result and perform a "file_exists" using the variable "$image1"
to fing a match in the seconds directory "allimages/boardsclean". If a match is found write the filename to the "$found_images" array.
Testing the result of the "$found_images" array I am not seeing the result I was expecting.
Can anyone see where I am going wrong?
$c1 = 0;
$c2 = 0;
$scan = scandir('allimages/temp1');
$found_images = array();
foreach ($scan as $image1) {
if (file_exists('allimages/temp1/'.$image1) && ('allimages/temp2/'.$image1)) {
echo "file match in Scan $image1</br>";
$found_images[] = 'allimages/adminclean/'. $image1;
$c1++;
}
}
echo $c1."</br>";
foreach ($found_images as $image3) {
echo "file match $image3 </br>";
$c2++;
}
echo $c2."</br>";
First, you don't need to test for the file from the scandir because, well... it's already there and was returned. Second, you don't test for the one in the second directory. You need:
if(file_exists('allimages/temp2/'.$image1)) {
However, just scan both directories and compute the intersection of the returned arrays which will give you files common to both directories. It's as simple as:
$found = array_intersect(scandir('allimages/temp1'), scandir('allimages/temp2'));
Then you can filter out directories if you want and add allimages/adminclean/ in the array or when needed.

PHP If-Else does not work for comparing filecontents

I am trying to make a PHP application which searches through the files of your current directory and looks for a file in every subdirectory called email.txt, then it gets the contents of the file and compares the contents from email.txt with the given query and echoes all the matching directories with the given query. But it does not work and it looks like the problem is in the if-else part of the script at the end because it doesn't give any output.
<?php
// pulling query from link
$query = $_GET["q"];
echo($query);
echo("<br>");
// listing all files in doc directory
$files = scandir(".");
// searching trough array for unwanted files
$downloader = array_search("downloader.php", $files);
$viewer = array_search("viewer.php", $files);
$search = array_search("search.php", $files);
$editor = array_search("editor.php", $files);
$index = array_search("index.php", $files);
$error_log = array_search("error_log", $files);
$images = array_search("images", $files);
$parsedown = array_search("Parsedown.php", $files);
// deleting unwanted files from array
unset($files[$downloader]);
unset($files[$viewer]);
unset($files[$search]);
unset($files[$editor]);
unset($files[$index]);
unset($files[$error_log]);
unset($files[$images]);
unset($files[$parsedown]);
// counting folders
$folderamount = count($files);
// defining loop variables
$loopnum = 0;
// loop
while ($loopnum <= $folderamount + 10) {
$loopnum = $loopnum + 1;
// gets the emails from every folder
$dirname = $files[$loopnum];
$email = file_get_contents("$dirname/email.txt");
//checks if the email matches
if ($stremail == $query) {
echo($dirname);
}
}
//print_r($files);
//echo("<br><br>");
?>
Can someone explain / fix this for me? I literally have no clue what it is and I debugged soo much already. It would be heavily gracious and appreciated.
Kind regards,
Bluppie05
There's a few problems with this code that would be preventing you from getting the correct output.
The main reason you don't get any output from the if test is the condition is (presumably) using the wrong variable name.
// variable with the file data is called $email
$email = file_get_contents("$dirname/email.txt");
// test is checking $stremail which is never given a value
if ($stremail == $query) {
echo($dirname);
}
There is also an issue with your scandir() and unset() combination. As you've discovered scandir() basically gives you everything that a dir or ls would on the command line. Using unset() to remove specific files is problematic because you have to maintain a hardcoded list of files. However, unset() also leaves holes in your array, the count changes but the original indices do not. This may be why you are using $folderamount + 10 in your loop. Take a look at this Stack Overflow question for more discussion of the problem.
Rebase array keys after unsetting elements
I recommend you read the PHP manual page on the glob() function as it will greatly simplify getting the contents of a directory. In particular take a look at the GLOB_ONLYDIR flag.
https://www.php.net/manual/en/function.glob.php
Lastly, don't increment your loop counter at the beginning of the loop when using the counter to read elements from an array. Take a look at the PHP manual page for foreach loops for a neater way to iterate over an array.
https://www.php.net/manual/en/control-structures.foreach.php

Excluding file extensions from my preg_match

I have a script I am using to filter some ROM and ISO files.
I have (with a lot of help) got a working script where files are filtered by filename, however I am trying to add a section in which I can include extra ad-hoc filenames to be filtered for me by providing them in a local .txt file. This is working OK, however in my .txt file I am having to put the full filename (including the .txt extension) into the .txt - for example my "manualregiondupes.txt file looks like this:
Game One.zip
Game Two.zip
Game Three.zip
Whereas I want it to just type them in my .txt file like so:
Game One
Game Two
Game Three
The current regex i'm using is trying to match the full filename it finds (including the .zip extension) whereas I want it to just match the section before the file extension. I have to be careful, however - as I don't want a game like:
"Summer Heat Beach Volleyball (USA)" being matched if "Beach Volleyball (USA)" is in the .txt.
Same goes for words on the other side - like
"Sensible Soccer (USA) (BETA)" being matched if "Sensible Soccer (USA)" is in the .txt
Here is my script;
// Make sure what manualregiondupes.txt is doing
if (file_exists('manualregiondupes.txt'))
{
$manualRegionDupes = file('manualregiondupes.txt', FILE_IGNORE_NEW_LINES);
$manualRegionPattern = "/^(?:" . implode("|", array_map(function ($i)
{
return preg_quote(trim($i) , "/");
}
, $manualRegionDupes)) . ')$/';
echo "ManualRegionDupes.txt has been found, ";
if (trim(file_get_contents('manualregiondupes.txt')) == false)
{
echo "but is empty! Continuing without manual region dupes filter.\n";
}
else
{
echo "and is NOT empty! Applying the manual region dupes filter.\n";
}
}
else
{
echo "ManualRegionDupes.txt has NOT been found. Continuing without the manual region dupes filter.\n";
}
// Do this magic for every file
foreach ($gameArray as $thisGame) {
if (!$thisGame) continue;
// Probably already been removed
if (!file_exists($thisGame)) continue;
// Filenames in manualregiondupes.txt
if (file_exists('manualregiondupes.txt'))
{
if (trim(file_get_contents('manualregiondupes.txt')) == true)
{
if (preg_match($manualRegionPattern, $thisGame))
{
echo "{$thisGame} is on the manual region dupes remove list. Moved to Removed folder.\n";
shell_exec("mv \"{$thisGame}\" Removed/");
continue;
}
}
}
... SCRIPT CONTINUES HERE BUT ISN'T RELEVANT!
What's the easiest way of doing this? I think i've just asked a very long question when it's actually quite simple, but oh well - I am not very good with PHP (or any script to be honest!) so apologies and thankyou's in advance! :D
You can use pathinfo in regex like -
$withoutExt = preg_replace('/\.' . preg_quote(pathinfo($path, PATHINFO_EXTENSION), '/') . '$/', '', $path);
it gives you perfect file name output without extension for
file.txt -> file
file.sometext.txt -> file.sometext

php Update filename from directory

so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.

Get full path from filename in php

So I have a URL which contains &title=blabla
I know how to extract the title, and return it. But I've been searching my ass off to get the full path to the filename when I only have the filename.
So what I must have is an way to search in all directories for an html file called 'blabla' when the only thing it has is blabla. After finding it, it must return the full path.
Anyone who does have an solution for me?
<?php
$file = $_GET['title'];
if ($title = '') {
echo "information.html";
} else {
//here it must search for the filepath and echo it.
echo "$filepath";
}
?>
You can use the solution provided here.
It allows you to recurse through a directory and list all files in the directory and sub-directories. You can then compare to see if it matches the files you are looking for.
$root = '/'; // directory from where to start search
$toSearch = 'file.blah'; // basename of the file you wish to search
$it = new RecursiveDirectoryIterator($root);
foreach(new RecursiveIteratorIterator($it) as $file){
if($file->getBasename() === $toSearch){
printf("Found it! It's %s", $file->getRealPath());
// stop at the first match
break;
}
}
Keep in mind that depending on the number of files you have, this can be slow as hell
For a start this line is at fault
if ($title = '') {
See http://www.php.net/manual/en/reserved.variables.files.php

Categories