In my application root folder I have a folder named 'articles' in which there are some files. And in my root folder I have the header file and some other files. The same header file is used in the files inside the articles directory too.
In my header file, I have a dropdown menu which lists the files inside the articles directory. And I have used the following code.
<?php
$dir = "./articles";
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && $entry != "images" && $entry != "index.php") {
$foo = $entry;
$foo = str_replace("_", " ", $foo);
$foo = str_replace(".php", "", $foo);
$foo = ucwords($foo);
?>
<a class="dropdown-content-a" href="<?php echo "$entry" ?>"><?php echo $foo ?></a>
<?php
}
}
closedir($handle);
}
?>
This works fine in the files in the root folder but it does not work in the files in the 'articles' folder(But the header file is still in the root folder and relative to the header file, the path './articles' is correct).
How to overcome this by using the same header file?
use (..) to cd the previous directory
include_once(dirname(__FILE__).'/../filename.php');
Maybe you can try a condition-wise solution. Check the path and decide to use ".." or not.
Related
I have created a directory with some files in there:
index.php
one.txt
two.txt
three.txt
four.txt
In the index.php page, I am currently using this code to echo out all of the files within the directory:
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo "$entry\n";
}
}
closedir($handle);
}
?>
Now, if anyone views the index.php page, this is what they'll see:
one.txt two.txt three.txt four.txt
As you can see from the PHP code, index.php is blacklisted so it is not echoed out.
However, I would like to go a step further than this and echo out the contents of each text file rather than the filenames. With the new PHP code (that I need help with creating), whenever someone visits the index.php page, this is what they'll now see:
(Please ignore what is in the asterisks, they are not a part of the code, they just indicate what each text file contains)
Hello ** this is what the file **one.txt** contains **
ok ** this is what the file **two.txt** contains **
goodbye ** this is what the file **three.txt** contains **
text ** this is what the file **four.txt** contains **
Overall:
I would like to echo out the contents of every file in the directory (they are all text files) aside from index.php.
You could use file_get_contents to put the file into a string.
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo "$entry " . file_get_contents($entry) . "\n";
}
}
closedir($handle);
}
?>
Furthermore, you could use PHP's glob function to filter only the .txt files out, that way you do not have to blacklist files if you're going to be adding more files to that directory that need ignored.
Here is how it would be done using the glob function.
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename " . file_get_contents($filename) . "\n";
}
?>
This would print the contents of the files. You can do some workaround if the path is not the current path and writing some kind of boundary between the files contents.
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo file_get_contents($entry) . "\n";
}
}
closedir($handle);
}
?>
I hope this helps you.
Never reinvent the wheel. Use composer.
Require symfony/finder
use Symfony\Component\Finder\Finder;
class Foo
{
public function getTextFileContents($dir)
{
$finder = (new Finder())->files()->name('*.txt');
foreach ($finder->in($dir) as $file) {
$contents = $file->getContents();
// do something while file contents...
}
}
}
I would give a chance to some SPL filesystem iterators to accomplish such this task:
$dir = '/home/mydirectory';
$rdi = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
$rdi = new \RegexIterator($rdi, '/\.txt$/i');
$iterator = new \RecursiveIteratorIterator($rdi, \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $file) {
echo 'Contents of the '.$file->getPathname().' is: ';
echo file_get_contents($file->getPathname());
}
This will recursively find & iterate all .txt files in given directory, including sub-directories.
Since each $file in iteration is a FilesystemIterator instance, you can use all related methods for additional controls like $file->isLink() (true for symbolic links), $file->isReadable() (false for unreadable files) etc..
If you don't want lookup sub-folders, just change the RecursiveDirectoryIterator in the second line from:
$rdi = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
to:
$rdi = new \DirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
Hope it helps.
As #brock-b said, you could use glob to get the full list of files and file_get_contents to grab the contents:
$blacklist = array('index.php');
$files = glob('*.txt'); # could be *.* if needed
foreach ($files as $file) {
if (!in_array(basename($file), $blacklist)) {
echo file_get_contents($file);
}
}
Note: the blacklist wont be hit since you're seeking for *.txt files. Only useful when doing an *.* or *.php file search
I accidentally created a file with no name http://website.com/myFolder/.html,
now, in the control panel of my webhost, this file is not listed, I cannot see or delete it...
but I can see it using this "myList.php" file: (http://website.com/myFolder/myList.php):
<?php
echo "<ol>";
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo '<li>'.$entry.'</li>';
}
}
closedir($handle);
}
echo "</ol>";
?>
This "myList.php" file outputs all the files present in the directory: http://website.com/folder/
also the file with no name http://website.com/myFolder/.html
How can I delete this file?
I tried to create another .php file called http://website.com/myFolder/myDelete.php,
and use the php function unlink():
<?php
$path = "../myFolder/.html";
if(file_exists($path)){
if (is_file($path)){
//unlink($path);
if (!unlink($file)){
echo ("Error deleting".$path);
}else{
echo ("Deleted".$path);
}
}
}
?>
But it doesn't work.
$path = "../myFolder/.html";
if(file_exists($path)){
if (is_file($path)){
//unlink($path);
if (!unlink($file)){
^^^^^----undefined variable
Why all of that when you could just have
unlink('.html');
? Your unwanted file is in the same directory as your myDelete.php script, so the rest of all that is pointless.
Files and directories that begin with . are considered "hidden" on *nix systems. You can see them with ls -la but not with just ls.
Try changing the $file variable to just be the name of the file ".html". Make sure to use the $file variable for the delete - this is not defined in your example.
$file = ".html";
if ( file_exists( $file ) ){
if ( ! unlink( $file ) ){
echo "Error deleting '$file'" );
} else{
echo "Deleted '$file'";
}
} else {
echo "File '$file' does not exist!";
}
The one comment suggested you use FTP, you should have FTP access to your server then you can simply delete through FTP.
I'm trying to read all folder names and create buttons out of it via .php. It somehow doesn't work how I want it to work.
Foldernames to read are in /www/templates/
.php file is in /www/php/
tried to:
put read.php in /www/templates/, telling it to opendir() and readdir() of "./" and include it to /www/php/ -> shown me results (folders) of /www/php/ (where it works perfectly and shows the folders of "./" if it's placed in there aswell).
Tried using the complete path ( /opt/xyz/www/templates/ ) -> no result at all
CHMOD of the folders are 766 - owner is the same as the PHP script.
Script placed in /www/php/:
<?php
$d = opendir('../templates/');
while(false !== ($f = readdir($d))) {
if (is_dir($f) && $f != "." && $f != "..") {
echo "<form action=\"./change.php\" method=\"get\">
<input type=\"submit\" name=\"template\" value=\"" . $f . "\"><br>";
}
}
?>
Script tried in /www/templates/:
<?php
$d = opendir('./');
while(false !== ($f = readdir($d))) {
[insert-code-from-above-here] }
?>
included the script in /www/templates/ to the "index.php" with:
<?php include('../templates/read.php'); ?>
Webserver: lighttpd
I have a php file like this
class Config {
public static $__routes = array(
"Home" => "index.php",
"Support" => "support.php",
);
}
Config::__routes += (include 'config/example1.php');
Config::__routes += (include 'config/example2.php');
can I include a directory
for example:
include('include 'config/example1.php');
include('include 'config/example2.php');
will be something like:
include('config/*');
You can use glob try:
foreach (glob('config/*.php') as $file)
include( $file );
This code will include all .php files in a given folder.
<?php
if ($handle = opendir('/path/to/includes/folder')) {
while (false !== ($entry = readdir($handle))) {
$path_parts = pathinfo($entry);
if ($path_parts['extension'] == '.php') include $entry;
}
closedir($handle);
}
?>
explanation:
opendir will open the given folder and return handle of folder.
while loop will loop through all files in that folder.
pathinfo will create an array include file information which one of then is extension of file.
Then we compare extension of found file to .php, if it was php file, we include it.
Then we close the handle of opened folder.
I have created this php script which displays the contents of a designated directory and allows users to download each file. Here is the code:
<?php
if ($handle = opendir('test')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "<a href='test/$file'>$file\n</a><br/>";
}
}
closedir($handle);
}
?>
This script also displays folders, but when I click a folder, it does display the contents of the folder, but in the default Apache autoindex view.
What I would like the script to do when a folder is clicked, is display the contents, but in the same fashion as the original script does (as this is more editable with css and the like).
Would you know how to achieve this?
Don't create a link to the directory itself, but to a php page which displays the contents.
Change your php code to somthing like:
if(isset($_REQUEST['dir'])) {
$current_dir = $_REQUEST['dir'];
} else {
$current_dir = 'test';
}
if ($handle = opendir($current_dir)) {
while (false !== ($file_or_dir = readdir($handle))) {
if(in_array($file_or_dir, array('.', '..'))) continue;
$path = $current_dir.'/'.$file_or_dir;
if(is_file($path)) {
echo ''.$file_or_dir."\n<br/>";
} else {
echo ''.$file_or_dir."\n<br/>";
}
}
closedir($handle);
}
PS write you html code with double quotes.
You need your HREF to point back to your PHP script, and not the directory. You will then need to update your PHP script to now which directory it needs to read.