Replace a string content with other content PHP - 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

Related

PHP search with multiple hits

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

php loop through files in subfolders in folder and get file paths

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

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 string with PHP code

I need to find a string within a string ("foo", for example) and then replace it with a PHP code. Is it possible?
I'm creating a Joomla Plugin. When my article has something like "{foo}", i will replace it with an include (require, or whatever).
I've made something like:
public function onContentBeforeDisplay($context, &$row, &$params, $page=0)
{
// $row->text has the article text ...
if (preg_match('/{contact-form}/', $row->text))
{
require_once(dirname(__FILE__) . DS . 'tmpl' . DS . 'default.php');
}
}
But this code will insert default.php at the beginning. I want to replace it in {contact-form} tag.
Thank you.
You can use the PHP function "substr_replace()", whose details are given here.
\n";
/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";
/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";
/**
* Your food & search is here
*/
/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";
/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>
You can create a PHP file that matches the keyword (like: foo.php) and simply extract the keyword from the text and use it to include that file.
For example:
<?php
$str = "This is {foo} text";
$includePath = "/path/to/my/files/";
// Careful with the Regular Expression. If you allow chars like . in the
// keyword this could create a security problem. (Dots allow you to go backwards
// which would allow people to execute files outside your path.)
if (preg_match_all('/\{([\w]+)\}/', $str, $matches))
{
foreach ($matches[1] as $_match)
{
$filePath = $includePath . $_match . ".php";
if (file_exists($filePath))
{
include $filePath;
}
else
{
trigger_error("File does not exist '$filePath'.", E_USER_WARNING);
}
}
}
?>
I think you just want this, don't you?
<?php
$replacement = file_get_contents('myfile.php');
$content = str_replace('{foo}', eval($replacement), $content);
?>
If you need to replace any string on series of files on your remote server and well you don't have time for it! , here is your solution , I hope it can help someone.
////
//PHP 5.3 + Class find and replace string in files
//
//by Bruce Afruz
//
//2013
//
//example usage for single file:
//
//$new = new fileReplacement('./');
//$new->setExt("check.php");
//$new->changeContents("hello", "goodbye");
//
//example usage for multiple files:
//
//$new = new fileReplacement('./test');
//$new->setExt("*.html");
//$new->changeContents("hello", "goodbye");
//
//to change directory:
//
//$new = new fileReplacement('./test');
//$new->setDir("./test2");
//$new->setExt("*.html");
//$new->changeContents("hello", "goodbye");
////
class fileReplacement
{
private $ext , $dir ;
public function getDir() {
return $this->dir;
}
public function setDir($dir) {
$this->dir = $dir;
}
public function getExt() {
return $this->ext;
}
public function setExt($ext) {
$this->ext = $ext;
}
function __construct($dir) {
$this->dir = $dir;
}
public function rglob($pattern = '*', $flags = 0, $path = '') {
chdir($this->getDir());
$paths = glob($path . '*', GLOB_MARK | GLOB_ONLYDIR | GLOB_NOSORT);
$files = glob($path . $pattern, $flags);
foreach ($paths as $path) {
$files = array_merge($files, $this->rglob($pattern, $flags, $path));
}
return $files;
}
public function changeContents($replace , $sentence , $flags = 0, $path = '') {
$all = $this->rglob($this->getExt() , $flags, $path);
foreach ($all as $file) {
$filename = $file;
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$contents = str_replace($replace , $sentence, $contents);
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'w+')) {
echo "Cannot open file ($filename)
";
exit;
}
// Write $contents to our opened file.
if (fwrite($handle, $contents) === FALSE) {
echo "Cannot write to file ($filename)
";
exit;
}
echo "Success, wrote content to file ($filename)
";
fclose($handle);
} else {
echo "The file $filename is not writable
";
}
}
}}

problem calling a php method from within itself

class styleFinder{
function styleFinder(){
}
function getFilesNFolders($folder){
$this->folder = $folder ;
if($this->folder==""){
$this->folder = '.';
}
if ($handle = opendir($this->folder)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file<br /> ";
if(is_dir($file)){
echo "<b>" . $file . " is a folder</b><br /> with contents ";
$this::getFilesNFolders($file);
# echo "Found folder";
}
}
}
closedir($handle);
}
}
}
I wan to print out a complete tree of folders and files, the script is going into the first folders and finding the files, then finding any sub folders, but not subfolders of those (and yes there is some). Any ideas please?
$this::getFilesNFolders($file);
Should Be
$this->getFilesNFolders($file);
Since PHP 5.1.2 you have this usefull class available: http://www.php.net/manual/en/class.recursivedirectoryiterator.php
Accessing a class function is done like this:
$this->functionName():
Since no one provided that yet, here is the RecursiveDirectoryIterator version of your code:
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/directory'),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $fileObject) {
if($fileObject->isDir()) {
echo "<strong>$fileObject is a folder:</strong><br>\n";
} else {
echo $fileObject, "<br>\n";
}
}
As others have said, within the method itself, you need to call getFilesNFolders with $this -> getFilesNFolders($file). Also, the way the code is posted you're missing a } at the end, but since there is one starting the text after the code, that is probably a typo. The code below worked for me (I ran via the command line, so added code to indent different directory levels and also to output \n's):
<?php
class StyleFinder{
function StyleFinder(){
}
function getFilesNFolders($folder, $spaces){
$this->folder = $folder ;
if($this->folder==""){
$this->folder = '.';
}
if ($handle = opendir($this->folder)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($file)){
echo $spaces . "<b>" . $file . " is a folder</b><br/> with contents:\n";
$this -> getFilesNFolders($file, $spaces . " ");
} else {
echo $spaces . "$file<br />\n";
}
}
}
closedir($handle);
}
}
}
$sf = new StyleFinder();
$sf -> getFilesNFolders(".", "");
?>

Categories