I am trying to write some code to look through all of the files in my server and return files that contain a certain string. The problem is that I only know the comment in the files I'm looking for is the key and I feel like this may be messing this up.
I have a function that recursively searches for files in all directories which works fine, but the reading of the file and searching of the string is not working properly.
<?php
$mal = "//###=CACHE START=###";
function getDirContents($dir) {
$files = scandir($dir);
foreach($files as $file) {
if($file == "." || $file == "..") continue;
if(!is_file($dir . $file)){
echo "Folder: " . $dir . $file . "<br />";
getDirContents($dir.$file."/");
} else {
echo "File: " . $dir . $file . "<br />";
$content = file_get_contents($dir . $file);
if (strpos($content, $mal) !== false) {
echo "FOUND" . $dir.$file . "<br>";
}
}
}
}
$dir = "./";
getDirContents($dir);
?>
For some reason, this is returning .png and .jpg files as "FOUND" and I'm not sure why. I have many files that have the $mal string in them, but it's a comment and I'm not sure if that matters. Either way, it is not working properly and not finding the files that I'm looking for.
This fails because the thing you're searching for is not actually in scope - in the function scope $mal is actually NULL and thus always found. This is outlined in the documentation at http://php.net/manual/en/language.variables.scope.php
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
This script will not produce any output because the echo statement
refers to a local version of the $a variable, and it has not been
assigned a value within this scope. You may notice that this is a
little bit different from the C language in that global variables in C
are automatically available to functions unless specifically
overridden by a local definition. This can cause some problems in that
people may inadvertently change a global variable. In PHP global
variables must be declared global inside a function if they are going
to be used in that function.
A quick and dirty way to fix this is to declare $mal a global. Saner is to pass it in as a parameter to your function, along with the dir.
Related
What I'm trying to do:
Use PHP ftp_nlist to retrieve the contents of a directory on the FTP server
The problem:
For directories that contain a lot of files (the one I encountered the problem on has nearly 40 thousand files, and no subfolders), the ftp_nlist function is returning false. For directories that are not as large, the ftp_nlist function returns an array of filenames as expected.
What I've tried:
Enabling passive mode (it already was enabled, but I see it as a common suggestion)
Adding ftp_set_option($conn_id, FTP_USEPASVADDRESS, false); after my ftp_login
using ftp_chdir, although my folder names never have spaces anyways
echoing error_get_last() after ftp_nlist returns false. The error show seems unrelated, but is shown below.
My code:
In case it is useful, here is the function I have created. What it is supposed to do is...
take in $fm (filemaker, unrelated to this problem)
take in $FTPConnectionID (the ftp connection I established in the prior to the function call)
take in $FolderPath (the path of the folder on the FTP server for which I want to list files/subfolders recursively - ex: "SomeFolder/Testing")
take in $TextFile (I am writing the paths of every file found on the FTP server to a text file, which was created prior to calling the function)
function createAuditFile($fm, $FTPConnectionID, $FolderPath, $TextFile) {
echo "createAuditFile called for " . $FolderPath . "\n";
//Get the contents of the given path. Will include files and folders.
$FolderContents = ftp_nlist($FTPConnectionID, $FolderPath);
if($FolderContents == false) {
echo "Couldn't get " . $FolderPath . "\n";
echo "ERROR: " . print_r(error_get_last()) . "\n";
} else {
print_r($FolderContents);
}
//Loop through the array, call this function recursively if a folder is found.
if(is_array($FolderContents)) {
foreach($FolderContents as $Content) {
//Create a varaible for the folder path
$ContentPath = $FolderPath . "/" . $Content;
//Call the function recursively if a folder is found
if(pathinfo($Content, PATHINFO_EXTENSION) == "") {
createAuditFile($fm, $FTPConnectionID, $ContentPath, $TextFile);
echo "Recursive call for " . $ContentPath . "\n";
//If a file is found, add the file ftp path to our array
} else {
echo "Writing to file: " . $ContentPath . "\n";
fwrite($TextFile, $ContentPath . "\n");
}
}
}
}
I can provide other code if needed, but I think my question is less of a coding issue, and more of an understanding ftp_nlist issue. I've been stuck on this for hours, so any help is appreciated. And like I said, this function works just fine for most folder paths passed to it, the problem is when there are tens of thousands of files within the folder. Thank you!
I've tried all the solutions I read on here but can't seem to get this to work.
I'm trying to call scandir in this file:
https://www.example.com/cms/uploader/index.php
to list all the files and directories in this folder:
https://www.example.com/uploads/
I don't want to hardcode the example.com part because this will be different depending on the site. I've tried many combinations of: dirname(FILE), DIR, $_SERVER['SERVER_NAME'], and $_SERVER['REQUEST_URI'], etc. I either get a "failed to open dir, not implemented in..." error or nothing displays at all. Here is the code I'm using:
$directory = __DIR__ . '/../../uploads';
$filelist = "";
$dircont = scandir($directory);
foreach($dircont AS $item)
if(is_file($item) && $item[0]!='.')
$filelist .= ''.$item.''."<br />\n";
echo $filelist;
What's the proper way to do this?
The $directory variable is set wrong. If you want to go 2 directories up use dirname() like this:
$directory = dirname(__DIR__,2) . '/uploads';
$filelist = "";
$dircont = scandir($directory);
foreach($dircont AS $item) {
if(is_file($item) && $item[0]!='.')
$filelist .= ''.$item.''."<br />\n";
}
echo $filelist;
You can read more about scandir there is a section on how to use it with urls if allow_url_fopen is enabled but this is mainly in local/development environment.
Sorry, i am not able to write a comment to ask you a question( low reputation ).
As far as i understand from your explanation, you wanted to add possible folder names to make your probe in a way will work automatically.
If yes, then i would do such piece of code like this;
$website = 'http://localhost/';
$folders = array('uploads','files', 'uploads/files');
$filelist = "";
foreach ($folders as $kinky)
$dircont = scandir($website.$kinky);
foreach ($dircont AS $item)
if (is_file($item) && $item[0] != '.')
$filelist .= '' . $item . '' . "<br />\n";
echo $filelist;
Hope it helps :)
I'm trying to recursively list every file that is in my bucket. It's not too many files but I'd like to list them to test a few things. This code works on a normal file system but it's not working on Google Cloud Storage.
Anyone have any suggestions?
function recurse_look($src) {
$dir = opendir($src);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_look($src . '/' . $file);
}
else {
echo $src . '/' . $file;
echo "<br />";
}
}
}
closedir($dir);
}
recurse_look("gs://<BUCKET>");
Personally, I would recommend not using a filesystem-impersonation abstraction layer on top of Google Cloud Storage, for a task such as listing everything inside a bucket -- rather, just reach out for the underlying functionality.
In particular, see https://cloud.google.com/storage/docs/json_api/v1/json-api-php-samples for everything about authentication etc, and, once, that's taken care of, focus on just one line in the example:
$objects = $storageService->objects->listObjects(DEFAULT_BUCKET);
This is all you need to list all objects in a bucket (which is not the same thing as "files in a directory", and the "filesystem simulations" on top of buckets and objects, I offer as being just my personal opinion, end up hurting rather than helping despite their excellent intentions:-).
Now if the objects' names contain e.g slashes and you want to take that into account as symbolically signifying something or other, go right ahead, but at least this way you're sure you're getting all the objects actually existing in the bucket, and, nothing but those!-)
Now that glob is working, you can try something like this
function lstree($dir) {
foreach (glob($dir . '/*') as $path) {
if (is_dir($path)) {
echo $path;
lstree($path);
} else {
echo $path;
}
}
lstree('gs://{bucket}/');
I have a piece of code that checks whether an image exists in the file system and if so, displays it.
if (file_exists(realpath(dirname(__FILE__) . $user_image))) {
echo '<img src="'.$user_image.'" />';
}
else {
echo "no image set";
}
If I echo $user_image out, copy and paste the link into the browser, the image is there.
However, here, the 'no image set' is always being reached.
The $user_image contents are http://localhost:8888/mvc/images/users/1.jpg
Some of these functions not needed?
Any ideas?
Broken code or a better way of doing it (that works!)?
Beside #hek2mgl answer which i think is correct, i also think you should switch to is_file() instead of file_exists().
Also, you can go a bit further like:
if(is_file(dirname(__FILE__). '/' . $user_image) && false !== #getimagesize(dirname(__FILE__) . '/'. $user_image)) {
// image is fine
} else {
// it isn't
}
L.E:1
Oh great, now you are telling us what $user_image contains? Couldn't you do it from the start, could you?
So you will have to:
$userImagePath = parse_url($user_image, PHP_URL_PATH);
$fullPath = dirname(__FILE__) . ' / ' . $userImagePath;
if($userImagePath && is_file($fullPath) && false !== #getimagesize($fullPath)) {
// is valid
}else {
// it isn't
}
L.E: 2
Also, storing the entire url is not a good practice, what happens when you switch domain names? Try to store only the relative path, like /blah/images/image.png instead of http://locathost/blah/images/image.png
You missed the directory separator / between path and filename. Add it:
if (file_exists(realpath(dirname(__FILE__) . '/' . $user_image))) {
Note that dirname() will return the directory without a / at the end.
Beginner : I cant seem to get my head around the logic of it. Have searched but seems to come up with listing files and folders from an actual directory ie. (opendir).
My problem is :
Im trying to work out (in PHP) how to list files and subfolders from a path stored in a database. (Without any access to the file or dir, so just from the path name)
For example database shows:
main/home/television.jpg
main/home/sofa.jpg
main/home/bedroom/bed.jpg
main/home/bedroom/lamp.jpg
So if i specify main/home - it shows: television.jpg, sofa.jpg and the name of the subfolder : bedroom.
scanFolder('main/home');
function scanFolder($dir) {
foreach (scandir($dir) as $file) {
if (!in_array($file, array('.', '..'))) {
if (is_dir($file)) {
scanFolder($dir . '/' . $file);
}
else {
echo $dir . '/' . $file . "\n";
}
}
}
}
You would probably want to check on each iteration if the filename is a directory or not. If it is, open it up and read its contents and output them. A recursive function would work best in this situation.
http://php.net/manual/en/function.is-dir.php