I have the code below which list files from directory and all sub directory and its working fine.
Now what I want to achieve is to only display PHP files that contains the following string functions
eval, system, shell_exec.
I guess I have to create an array like
$check=array("unescape", "system(","shell_exec(");
Below is the code that just list all the PHP files
function c_check($path){
if(file_exists($path) && is_dir($path)){
$files = glob($path ."/*");
if(count($files) > 0){
// Loop through retuned array
foreach($files as $file){
if(is_file("$file")){
// Display only filename
echo basename($file) . "<br>";
} else if(is_dir("$file")){
c_check("$file");
}
}
} else{
echo " directory file not found";
}
} else {
echo " directory does not exist.";
}
}
// Call the function
c_check("../content_folder");
You could do something similar to the code below, loading each file and then checking if it contains any of those strings.
Keep in mind this won't be very fast, i'd consider using something like grep and parsing it's output.
function c_check($path)
{
$checks = ["unescape", "system(", "shell_exec("];
if (file_exists($path) && is_dir($path)) {
$files = glob($path . "/*");
if (count($files) > 0) {
// Loop through returned array
foreach ($files as $file) {
if (is_file("$file")) {
$fileContents = file_get_contents($file);
foreach ($checks as $illegalString) {
if (strpos($fileContents, $illegalString) !== false) {
echo basename($file) . "<br>";
}
}
} else {
if (is_dir("$file")) {
c_check("$file");
}
}
}
} else {
echo " directory file not found";
}
} else {
echo " directory does not exist.";
}
}
You have to read the content of the file first and do a search. Try replacing your if block in foreach loop with this.
if(is_file("$file")){
$contents = file_get_contents($file);
if(strpos($contents, "eval")!==false || strpos($contents, "system")!==false || strpos($contents, "shell_exec")!==false){
//this is the file you're looking for.
}
}
It read the content for the file and make a search for the words.
Related
In my controller I receive ZIP file, which may contain xml and nested multi level zip files.
How to create flat directory, which will contain only xml files recursively extracted from all zip files?
I'd recommend for the sake of simplicity, creating a temporary directory, extracting the ZIP to that directory:
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->extractTo('tmp');
$zip->close();
} else {
echo 'failed';
}
then, maybe a recursive function to iterate all files.
function recursiveDirectoryIterator($path){
$out = [];
foreach(glob($path . "/*") as $entry){
if ( is_dir($entry) ) {
$sub = recursiveDirectoryIterator($entry);
foreach($sub as $subEntry){ $out[] = $subEntry; }
} else {
$out[] = $entry;
}
}
return $out;
}
then, to finish just use:
foreach(recursiveDirectoryIterator("tmp") as $file){
if ( !rename ( $file , getcwd() . basename($file) ) {
echo 'Failed to rename: ' . $file . ' to ' . getcwd() . basename($file) . '<br>';
}
}
if you have multiple nested ZIP archives, just amend this approach. Maybe created a key => value list of the archives, such as:
$archive['imagePack1'] = "tmp/archive1.zip";
$archive['imagePack2'] = "tmp/archive2.zip"
foreach($archive as $key => $path){
$zip = new ZipArchive;
if ($zip->open('tmp/' . $path) === TRUE) {
$zip->extractTo('tmp/' . $key);
$zip->close();
} else {
echo 'failed';
}
}
This is file1.php:
<?php
// Start the session
session_start();
?>
<?php
$path_to_check = '';
$needle = $_POST['query'];
foreach(glob($path_to_check . '*.xml') as $filename)
{
foreach(file($filename)as $fl)
{
if(strpos($fl, $needle)!==false)
{
$_SESSION["hit"] = $filename;
}
}
}
header('Location: file2.php');
?>
The search is working and returning the name of the file where searchword is found as a variable $_SESSION["hit"] = $filename;
However if the searchword is found in multiple files it will not work. Then I would need to go to another page file1b.php (or file1b.html) where the multiple files will be listed. Then from there do a choice to get to file2.php.
How could it be done?
Make $_SESSION['hit'] an array of all the filenames with a match.
$_SESSION['hit'] = array();
foreach(glob($path_to_check . '*.xml') as $filename)
{
foreach(file($filename)as $fl)
{
if(strpos($fl, $needle)!==false)
{
$_SESSION["hit"][] = $filename;
break;
}
}
}
You can then print the filenames with a simple loop.
foreach ($_SESSION['hit'] as $filename) {
echo $filename . "<br>";
}
Im really new to PHP i searched google to find a correct script that loops through all subfolders in a folder and get all files path in that subfolder
<?php
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename. '<br/>';
}
?>
So i have folder 'posts' in which i have subfolder 'post001' in which i have two files
controls.png
text.txt
And the code above echos this
posts\.
posts\..
posts\post001\.
posts\post001\..
posts\post001\controls.png
posts\post001\text.txt
But i want to echo only the file paths inside these subfolders like this
posts\post001\controls.png
posts\post001\text.txt
The whole point of this is that i want to dynamically create divs for each subfolder and inside this div i put img with src and some h3 and p html tags with text equal to the .txt file so is this proper way of doing that and how to remake my php script so that i get just the file paths
So I can see the answers and they are all correct but now my point was that i need something like that
foreach( glob( 'posts/*/*' ) as $filePath ){
//create div with javascript
foreach( glob( 'posts/$filePath/*' ) as $file ){
//append img and h3 and p html tags to the div via javascript
}
//append the created div somewhere in the html again via javascript
}
So whats the correct syntax of doing these two foreach loops in php im really getting the basics now
See if this works :)
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
if ((substr($file, -1) != '.') && (substr($file, -2) != '..')) {
echo $file . '<br/>';
}
}
<h1>Directory Listing</h1>
<?php
/**
* Recursive function to append the full path of all files in a
* given directory $dirpath to an array $context
*/
function getFilelist($dirpath, &$context){
$fileArray = scandir($dirpath);
if (count($fileArray) > 2) {
/* Remove the . (current directory) and .. (parent directory) */
array_shift($fileArray);
array_shift($fileArray);
foreach ($fileArray as $f) {
$full_path = $dirpath . DIRECTORY_SEPARATOR . $f;
/* If the file is a directory, call the function recursively */
if (is_dir($full_path)) {
getFilelist($full_path, $context);
} else {
/* else, append the full path of the file to the context array */
$context[] = $full_path;
}
}
}
}
/* $d is the root directory that you want to list */
$d = '/Users/Shared';
/* Allocate the array to store of file paths of all children */
$result = array();
getFilelist($d, $result);
$display_length = false;
if ($display_length) {
echo 'length = ' . count($result) . '<br>';
}
function FormatArrayAsUnorderedList($context) {
$ul = '<ul>';
foreach ($context as $c) {
$ul .= '<li>' . $c . '</li>';
}
$ul .= '</ul>';
return $ul;
}
$html_list = FormatArrayAsUnorderedList($result);
echo $html_list;
?>
Take a look at this:
<?php
$filename[] = 'posts\.';
$filename[] = 'posts\..';
$filename[] = 'posts\post001\.';
$filename[] = 'posts\post001\..';
$filename[] = 'posts\post001\controls.png';
$filename[] = 'posts\post001\text.txt';
foreach ($filename as $file) {
if (substr($file, -4, 1) === ".") {
echo $file."<br>";
}
}
?>
Result:
posts\post001\controls.png
posts\post001\text.txt
What this does is checking if the 4th last digit is a dot. If so, its an extension of three letters and it should be a file. You could also check for specific extensions.
$ext = substr($file, -4, 4);
if ($ext === ".gif" || $ext === ".jpg" || $ext === ".png" || $ext === ".txt") {
echo $file."<br>";
}
I have searched on google and on this site for something similar to what I want but nothing fits exactly and all my efforts to adapt them have failed, I want to make a script that will map out its directory and all its subfolders and the folders be at the top of the subdirectory and files after them. So far I have come up with this:
<?php
$rawParent = scandir('.');
$parentDir = array_diff($rawParent, array('.', '..','cgi-bin','error_log'));
$arrayOfDirectories = array();
$arrayOfFiles = array();
foreach ($parentDir as $child){
if(is_dir($child)){
array_push($arrayOfDirectories,$child);
}else{
array_push($arrayOfFiles,$child);
}
}
foreach ($arrayOfDirectories as $directory){
echo $directory.'<br>';
}
echo "<br>";
foreach ($arrayOfFiles as $file){
echo "<a href='".$file."'>".$file.'</a><br>';
}
?>
It's good so far but it only does the first level of the directory, can this code be adapted to go through all levels of folders and nest them? If so how? I need a few pointers, I will further use javascript to have toggles on the folders to see the contents, so I will need PHP to output something nested.
Sorry if I am not making much sense, don't really know how to explain.
Use recursive function like this :
<?php
function list_directory($directory)
{
$the_directory = opendir($directory) or die("Error $directory doesn't exist");
while($file = #readdir($the_directory))
{
if ($file == "." || $file == "..") continue;
if(is_dir($directory.'/'.$file))
{
print '<ul>'.$directory.'/'.$file;
list_directory($directory.'/'.$file);
print '</ul>';
}
else
{
print "<li> $file </li>";
}
}
closedir($the_directory);
}
$path_to_search = '/var/www';
list_directory($path_to_search);
?>
Version with storage in array :
<?php
function list_directory($directory, &$storage)
{
$the_directory = opendir($directory) or die("Error $directory doesn't exist");
while($file = #readdir($the_directory))
{
if ($file == "." || $file == "..") continue;
if(is_dir($directory.'/'.$file))
{
list_directory($directory.'/'.$file, $storage);
}
else
{
$storage[] = $file;
}
}
closedir($the_directory);
}
$storage = array();
$path_to_search = '/var/www';
list_directory($path_to_search, $storage);
echo '<pre>', print_r($storage,true) , '</pre>';
?>
This will do what you asked for, it only returns the sub directory names in a given path, and you can make hyperlinks and use them.
$yourStartingPath = "your string path";
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($yourStartingPath),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $file) {
if($file->isDir()) {
$path = strtoupper($file->getRealpath()) ;
$path2 = PHP_EOL;
$path3 = $path.$path2;
$result = end(explode('/', $path3));
echo "<br />". basename($result);
}
}
I need help on this one
I have managed to loop through my parent folder and echo the sub folder en wants to create on PHP file that can help me loop through the sub folders. my code is below:
<?php
$path="../downloads/pastpapers/UCU/foundations/";
$dir = new DirectoryIterator($path);
foreach ($dir as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
$dirName=$fileinfo->getFilename();
echo "<div id='linkFrame'><a href='$dirName.php'><img src='images/folder.png'><br/>$dirName</img></a> </div>";
}
}
?>
Just try the following in test file php :
<?php
$path = '../downloads/pastpapers/UCU/foundations';
ListFolder($path);
function ListFolder($path)
{
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$explode = explode("/", $path);
$dirname = end($explode);
//display the target folder.
echo ("<li>$dirname\n");
echo "<ul>\n";
while (false !== ($file = readdir($dir_handle)))
{
if($file!="." && $file!="..")
{
if (is_dir($path."/".$file))
{
//Display a list of sub folders.
ListFolder($path."/".$file);
}
else
{
//Display a list of files.
echo "<li>$file</li>";
}
}
}
echo "</ul>\n";
echo "</li>\n";
//closing the directory
closedir($dir_handle);
}
?>
for more information pls visit this page