PHP opendir issue - php

Why do I get this error even though the directory exists? it works fine if I target the parent directory, I tried using %20 instead of space too, and tried removing the last / but nothing works!
Warning: opendir(/home/xxxx/user_files/users/xxxx/test directory/) [function.opendir]: failed to open dir: No such file or directory in /home/xxxx/public_html/beta/stream._pages/file._list._i.php on line 54
(Note: xxxx is just me censoring user names)

Make a file called test.php and put it in your test directory. In that file, put this code:
<? echo dirname(__FILE__);?>
Then, visit test directory/test.php in your web browser, copy and paste the path as given in test.php and try using that exact path in opendir.
Another issue might be that the permissions of your directory aren't right, try chmodding to 777

For anyone trying to find the folder outside of the public_html folder.
This code is provided by php.net for the opendir() function:
if ( $handle = opendir('../../../../') )
{
echo "Directory handle: $handle\n";
echo "Entries:\n";
/* This is the correct way to loop over the directory. */
while ( false !== ( $entry = readdir( $handle ) ) )
{
echo "$entry\n";
}
/* This is the WRONG way to loop over the directory. */
while ($entry = readdir($handle))
{
echo "$entry\n";
}
closedir( $handle );
}
Solution
The $handle I started checking out how far I could go back with '../' adding as much ../ as possible until you find yourself in the folder you need. From there you take I guess.
For me '../../../../' was enough to get there, it's different on every server.

Related

PHP fopen doesn't find existing file

I'm currently writting a login-system with PHP, for that I need to read the files with some user-information in it.
But after changing the folder system, PHP fopen doesn't read the files anymore.
Both the users.php and userinf.csv files are in the samle folder.
I allready tried to change the filepath, hard-coded the filepath , recreated the file. All of which file.
//Read file
$fp = fopen("userinf.csv", "r");
if(!$fp)
{
echo "File couldn't be read";
return false;
}
Before changing the file system, it worked. But now I am geting the error:
Warning: fopen(userinf.csv): failed to open stream: No such file or directory in FILEPATH on line 45
When you use the fread function without any reference it could fail. I always say that you need to check your path first with getcwd()
<?php
echo getcwd(); //Current Working Directory
?>
Use absolute paths, always. It removes any ambiguity. Using a relative path may change based on where your script is located, among other things, depending on your system.
$fp = fopen("/home/somewhere/blah/userinf.csv", "r");
You can always use a variable for the path as well:
// Somewhere in your code
define('ROOT_PATH', "/home/somewhere/blah");
// In the implementation
$fp = fopen(ROOT_PATH . "/userinf.csv", "r");

Copying folder to other folder with PHP

I'm trying to move folder to other folder, with all it's files. Both folders are in root directory. Tried a lot of ways, and always get no result.
Here is my latest atempt:
$source = "template/"
$dest = "projects/"
function copyr($source, $dest){
if (is_link($source)) {
return symlink(readlink($source), $dest);
}
if (is_file($source)) {
return copy($source, $dest);
}
if (!is_dir($dest)) {
mkdir($dest);
}
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
copyr("$source/$entry", "$dest/$entry");
}
$dir->close();
return true;
}
Need professional glance to tell me, where I'm getting it wrong?
EDIT:
Sorry for wrong tags.
Problem is - nothing is happening. Nothing is being copied. No error messages. Simply nothing happens.
File structure:
I suggest to try and do the following
How do you run the scrips? Do you open page in browser or run script in command line? If you open page in browser this might be an issue with permissions, paths (relative and not absolute) and errors not shown but logged.
Use absolute folder paths instead of relative paths. For example /var/www/project/template.
Apply realpath() function to all paths and check (output) the result. If path is wrong (folder does not exist, separators are wrong etc) you will get empty result from the function.
Make sure to use DIRECTORY_SEPARATOR instead of / if you run your script on Windows. I can not check if / works on Windows now but potentially this might be an issue. For example
copyr($source.DIRECTORY_SEPARATOR.$entry", $dest.DIRECTORY_SEPARATOR.$entry);
Check warnings and errors. If you do not have permission you should get warning like this
PHP Warning: mkdir(): Permission denied
You may need to enable warnings and errors if they are disabled. Try for example to make an obvious mistake with name and check if you get any error message.
Try to use tested solution from one of the answers. For example xcopy function.
Try to add debug messages or run your script in debugger step by step. Check what is happening, what is executed etc. You can add debug output near any operator like (just an idea):
echo 'Creating directory '.$name.' ... ';
mkdir($name);
echo (is_dir($name) ? 'created' : 'failed').PHP_EOL;

PHP Count through different directories and see which ones have 0 files in them

I have the following folder structure:
images/photo-gallery/2e/
72/
rk/
u3/
va/
yk/
... and so on. Basically, each time an image is uploaded it hashes the name and then creates a folder with the first two letters. So inside of 2e is 2e0gpw1p.jpg
Here's the thing... if I delete an image, it will delete the file but it will keep the folder that it's in. Now when I have a TON of images uploaded, that will be fine since a lot of images will share the same folder.. but until then, I will end up having a bunch of empty directories.
What I want to do is search through the photo-gallery folder and go through each directory and see which folders are empty.. if there are any empty folders then it will remove it.
I know how to do that for a single directory, like the 2e folder. But how would I do it for all the folders inside the photo-gallery folder?
The PHP function rmdir() will throw a warning if the directory is not empty, so you can use it on non-empty directories without risking deleting them. Combine that with scandir() and array_slice (to remove . and ..), and you can do this:
foreach(array_slice(scandir('images/photo-gallery'),2) as $dir) {
#rmdir('images/photo-gallery/' . $dir); // use # to silence the warning
}
while you could do with with php, i'm inclined to use the os for such a task. Of course you can call the below with php
find <parent-dir> -depth -type d -empty -exec rmdir -v {} \;
PLEASE READ THIS WARNING I DID NOT TEST BUT HAVE USED SIMILAR CODE DOZENS OF TIMES. FAMILURIZE YOURSELF WITH THIS AND DO NOT USE IF YOU DO NOT UNDERSTAND WHAT IT IS DOING THIS COULD POTENTIALLY WIPE YOUR SITE FROM THE SERVER.
EDIT BACKUP EVERYTHING BEFORE TRYING THIS YOUR FIRST TIME THE PATH IS VERY VERY IMPORTANT!
Ok with that said this is quite easy :)
<?php
function recursiveDelete($path){
$ignore = array(
'cgi-bin',
'.',
'..'
); // Directories to ignore
$dh = opendir($path); // Open the directory
while(false !== ($file = readdir($dh))){ // Loop through the directory
if(!in_array($file, $ignore)){ // Check that this file is not to be ignored
if(is_dir($path."/".$file)){ // Its a directory, keep going
if(!iterator_count(new DirectoryIterator($path."/".$file)))
rmdir($path."/".$file); // its empty delete it
} else {
recursiveDelete($path."/".$file);// Recursive call to self
}
}
}
}
closedir($dh); // All Done close the directory
}
// WARNING IMPROPERLY USED YOU CAN DUMP YOUR ENTIRE SERVER USE WITH CAUTION!!!!
// I WILL NOT BE HELD RESPONSIBLE FOR MISUSE
recursiveDelete('/some/directoy/path/to/your/gallery');
?>

Looping through directories in PHP?

I'm working on a script that replaces all files within a directory and the subdirectories with a single string to get rid of the generic error message our software displays.
I made it work pretty easily with all files in a single directory, but then we ran it in a folder with subdirectories and as you can probably guess, it threw a lot of errors. I completely forgot about the subdirectories.
So now I'm making a script that works with subdirectories, but I'm stumped.
Here's my code:
<?php
$files = explode("\n", shell_exec('ls'));
$count = 0;
foreach ($files as $file)
{
if (empty($file) || $file == $_SERVER['SCRIPT_NAME'])
{
continue;
}
if (is_dir($file))
{
echo "Copying to {$file}/{$_SERVER['SCRIPT_NAME']}\n";
copy($_SERVER['SCRIPT_NAME'], $file . "/" . $_SERVER['SCRIPT_NAME']);
exec("php {$file}/{$_SERVER['SCRIPT_NAME']}");
unlink($file . "/" . $_SERVER['SCRIPT_NAME']);
continue;
}
$fh = fopen($file, 'w');
fwrite($fh, '<!-- Generated %T by %h (%s) -->');
fclose($fh);
echo "Rewrote {$file}\n";
$count++;
}
echo "Finished. Rewrote {$count} files. Don't forget to delete {$_SERVER['SCRIPT_NAME']}.\n";
?>
It ends up outputting this:
[root#proxy1 orgytest]# php p.php
Rewrote blah
Rewrote dfas
Rewrote dfasfsdjkfjsa
Rewrote dfdsafdsaf
Rewrote dfsaf
Rewrote orgy
Rewrote query
Rewrote scsew
Copying to test/p.php
Rewrote blah
Rewrote dfas
Rewrote dfasfsdjkfjsa
Rewrote dfdsafdsaf
Rewrote dfsaf
Rewrote orgy
Rewrote p.php
Rewrote query
Rewrote scsew
Copying to test/test/p.php
PHP Warning: copy(test/test/p.php): failed to open stream: No such file or directory in /root/orgytest/test/p.php on line 15
Could not open input file: test/test/p.php
PHP Warning: unlink(test/test/p.php): No such file or directory in /root/orgytest/test/p.php on line 17
Copying to test2/test/p.php
PHP Warning: copy(test2/test/p.php): failed to open stream: No such file or directory in /root/orgytest/test/p.php on line 15
Could not open input file: test2/test/p.php
PHP Warning: unlink(test2/test/p.php): No such file or directory in /root/orgytest/test/p.php on line 17
Finished. Rewrote 9 files. Don't forget to delete test/p.php.
Copying to test2/p.php
<!-- Generated %T by %h (%s) -->Finished. Rewrote 8 files. Don't forget to delete p.php.
What's weird to me is that it's trying to do things like test/test/p.php rather than test/p.php. I assume it has something to do with the fact that it's running from a higher up directory when it reaches that point.
Anyone know how I can fix this?
The value of $_SERVER['SCRIPT_NAME'] is probably not what you expect, and the reason for constructing a path like test/test/p.php. My guess is when you exec php test/p.php then that's the value php places into SCRIPT_NAME. You could use the basename() function to get around that.
Also, you should be using escapeshellarg() when dynamically creating shell commands.
Alternatively...
$self = realpath(__FILE__);
$ritit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__));
foreach ($ritit as $splFileInfo) {
$fileName = $splFileInfo->getRealPath();
if ($fileName !== $self) {
file_put_contents($fileName, '<!.....stuff');
}
}
The problem stems from LS returning the contents of the base directory, not necessarily the one that houses your script. I honestly would avoid exec, and just try to abstract your copying into a function, use php filesystem functions, and turn it into a recursive algorithm instead of trying to exec ls processes.
SPL's recursive iterator's are ideally suited for this, I'd use something like the following
<?php
// get scriptname from $argv[0]
$scriptname = basename(array_shift($argv));
// optional argument indicating path to run this script in (defaults to current path)
if (!empty($argv[0])) {
$workspace = $argv[0];
}else {
$workspace = getcwd();
}
// Recursively iterate over files in the specified workspace folder and all subfolders
try {
$count = 0;
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($workspace)) as $file) {
// ignore the folders, and this script if present
if ($file->isDir() || $file->getFilename() == $scriptname) continue;
// write the file
echo "Writing to $file\n";
file_put_contents($file, '<!-- Generated %T by %h (%s) -->');
$count++;
}
echo "Rewrote $count files";
} catch (Exception $e) {
// oops, likely invalid path, or unreadable folder
echo "Problem reading $workspace";
}
?>
SPL Manual:
RecursiveIteratorIterator
RecursiveDirectoryIterator
Try with something like this:
Codingforums
or try to search on google for "php recursive directory listing" or anything similar.
With readdir() function you will get files and subdirectories in specific directory. So the key point is to figure out if it's just a file or it is a subdirectory with is_dir() function. Also make sure you will use full path to files in subdirectories when you want to open and edit it. So like i said try to use google and find something useful.

How to copy all contents in a folder to a dir in php

I am trying to copy all the files from a directory to another directory in php.
$copy_all_files_from = "layouts/";
$copy_to = "Website3/";
Can someone help me do this please.
Something like this(untested):
<?php
$handle = opendir($copy_all_files_from);
while (false !== ($file = readdir($handle))) {
copy( $file, $copy_to);
}
edit:
To use Amadan's method, you should be able to use this php function:
shell_exec();
Not sure since I never need to use server commands
Easiest:
`cp -r $copy_all_files_from $copy_to`
Unless you're on Windows. Without shelling, it's a bit more complex: read directory, iterate on files (if it's a directory, recurse), open each, iterate while not end of file, read block and write it.
UPDATE: doh, PHP has copy...

Categories