PHP search with multiple hits - php

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

Related

How to presence of some string data in PHP code

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.

advice on building php based file manager

I am trying to build a php based file management system, but am having a few problems, basically I have found a script but it has problems reading directory names with spaces in them, here is the script :
<?php
global $dir_path;
if (isset($_GET["directory"])) {
$dir_path = $_GET["directory"];
//echo $dir_path;
}
else {
$dir_path = $_SERVER["DOCUMENT_ROOT"]."/";
}
$directories = scandir($dir_path);
foreach($directories as $entry) {
if (is_dir($dir_path . "/" . $entry) && !in_array($entry, array('.','..'))) {
echo "<li>" . $entry . "</li>";
}
else {}
}
?>
Any help would be greatly appreciated, thanks!

PHP nested file tree

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

Replace a string content with other content PHP

I have an a string declared at the top of my PHP script:
$dirname = "./rootfs/home/".$user."/";
After running the code, that string should be replace so it looks like this:
$dirname = "./rootfs/home/".$user."/testdir/";
Is there any way to replace the content? This is a dumb question for sure, but didn't found any way to do it, thanks! :D
Code I'm using:
Main PHP:
<?php
//Variables
$rootfs = "rootfs/";
$user = "www";
$dirname = "./rootfs/home/".$user."/";
//Variables
//Commands on rootfs/bin/
include($rootfs."/bin/ls.php");
include($rootfs."/bin/about.php");
include($rootfs."/bin/echo.php");
include($rootfs."/bin/uname.php");
include($rootfs."/bin/apt-get.php");
include($rootfs."/bin/whoami.php");
include($rootfs."/bin/cd.php");
//Commands on rootfs/bin/
$command=$_POST['command'];
$commandexp = explode(" ", $command);
switch ($commandexp[0]) {
case "cd":
//$dirname = "./rootfs/home/".$user."/";
//$prompt = cd($dirname, $commandexp[1]);
$dirname .= cd($dirname, $commandexp[1]);
echo $dirname;
break;
case "ls":
switch ($commandexp[1]) {
case "-la":
//$dirname = "./rootfs/home/".$user."/";
$files = ls($dirname);
foreach($files as $value){
$prompt .= substr(sprintf('%o', fileperms($dirname.$value)), -4)." ".$user." ".$value."<br>";
}
break;
case "--help":
$prompt = "Usage: ls [-la]";
break;
default:
echo $dirname." ";
$files = ls($dirname);
foreach($files as $value){
$prompt .= $value." ";
}
break;
}
break;
default:
$prompt = "command not found";
}
echo $prompt;
?>
The cd.php
<?php
function cd($actualdir, $dir) {
//echo $actualdir.$dir."<br>";
if(file_exists($actualdir.$dir)) {
echo $dir;
return $dir;
} else {
return "no";
}
}
?>
The ls.php
<?php
function ls ($directory) {
// create an array to hold directory list
$results = array();
// create a handler for the directory
$handler = opendir($directory);
echo $handler;
// open directory and walk through the filenames
while ($file = readdir($handler)) {
// if file isn't this directory or its parent, add it to the results
if ($file != "." && $file != "..") {
$results[] = $file;
}
}
// tidy up: close the handler
closedir($handler);
// done!
return $results;
}
?>
To add a string just do that:
$dirname .= "/testdir/";
To concatenate one string to the end of another string: $dirname .= 'testdir/'
To reassign a totally new string to the variable: $dirname = 'This is the new string'
See String Operators
Is this what you want:
$dirname .= "testdir/";
Finally used a session variable for storing the actual dir

Multiple File Exists Checking? A Better way?

I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.
Right now I am doing this script as follows:
if (file_exists($img = $node.".png")) { }
else if (file_exists($img = $node.".jpg")) { }
else if (file_exists($img = $node.".gif")) { }
else
{
$img = 'RANDOM.png';
}
There has to be a better way than this... anyone have any ideas?
$list = array_filter(array("$node.png", "$node.jpg", "$node.gif"), 'file_exists');
if (!$img = array_shift($list)) {
$img = 'RANDOM.png';
}
Alternatives :
$list = scandir(".");
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#", $list);
This returns a list of file names that start with $node and with a .jpg, .png or .gif suffix.
If the directory contains many entries, if may be faster to use glob() first:
$list = glob("$node.*"); // take care to escape $node here
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#");
The preg_grep() can also be replaced by
$list = array_intersect($list, array("$node.png", "$node.jpg", "$node.gif"));
Or with a loop:
$img = null;
foreach(array('png','jpg','gif') as $ext) {
if (!file_exists("$node.$ext")) continue;
$img = "$node.$ext"; break;
}
$img = $img ? $img : "RANDOM.png";
The most compact (and therefore not recommended) form would be:
if (array_sum(array_map("file_exists", array($fn1, $fn2, $fn3)))) {
It could be adapted to also returning the found filename using array_search:
array_search(1, array_map("file_exists", array($fn1=>$fn1, $fn2=>$fn2)))
Hardly readable. Note how it also requires a map like array("$node.png"=>"$node.png", "$node.gif"=>"$node.gif", ...). So it would not be that much shorter.
$n_folder="images/nodes/";
$u_folder="images/users/";
$extensions=array(".png",".jpg",".gif");
foreach ($extensions as $ext)
{
if (file_exists($n_folder.$node.$ext))
{
$img=$n_folder.$node.$ext;
break;
}
elseif (file_exists($u_folder.$node.$ext))
{
$img=$u_folder.$node.$ext;
break;
}
}
if (!$img)
{
random image generator script...
}
Okay... this is what I finalized on:
$searches = array(
$folder . "nodes/" . $node . ".png",
$folder . "nodes/" . $node . ".jpg",
$folder . "nodes/" . $node . ".gif",
$folder . "users/" . $user . ".png",
$folder . "users/" . $user . ".jpg",
$folder . "users/" . $user . ".gif"
);
foreach ($searches AS $search)
{
if (file_exists($search))
{
$img = $search;
break;
}
}
if (!$img)
{
random image generator script...
}

Categories