How to delete files with multibyte characters in the file name? - php

I accidentally created a file with PHP and now I can't delete or re-name it.
The file is called â€%C2%9Dâ2™j299t™93.gif
Edit: I only have access via FTP, the host is Linux based
Edit 2: I can't even delete the directory it is in.

In the command line, write:
ftp to.target.server
del *93.gif
If you are the owner of the file, this should work (permissions were 644)

From PHP you can use the unlink function as follows:
<?php
$filename="â€%C2%9Dâ2™j299t™93.gif";
unlink($filename);
?>
The problem you have been having is probably to do with the ™ symbol being translated. If you copy the code above and paste it into your editor and then run it, this should delete the file, assuming it is run from the same directory as the file.

Download Filezilla and set site encoding to enforced utf-8. Then try to delete your file via it.

I guess you don't know the exact filename (as your ftp client does not show it in a proper way). You can iterate thru files. This example deletes all files with the character % in it. Use it carefully:
$d = dir(".");
while (false !== ($entry = $d->read())) {
if (strpos ($entry, '%') !== false) {
unlink ($entry);
}
}
$d->close();

Related

Why I can't write files using php in xampp?

I'm using xampp in Windows for local developing environment. I tried to create a simple logger which appends to a text file.
function Logger ($logmessage)
{
$filename = '/errorlog-' . date('Ymd') . '.txt';
file_put_contents($filename, $logmessage, FILE_APPEND | LOCK_EX);
}
I've tried to echo the $filename, and it says '/errorlog-20140427.txt' which means it already has valid filename (I think).
But when I call this logger function, there's no error raised, but I can't find the file everywhere. I tried to search for the whole htdocs for *.txt but no files found. Do you know why I can't write file using php? Do I need to use fopen first? As I refer to another help, I can just use file_put_contents directly without fopen. Thanks for the help.
You're trying to write to the root of your filesystem, e.g.
$file = '/error-log-' etc...
is essentially the same as
$file = 'c:/error-log' etc...
The webserver account is highly unlikely to have the rights to do anything in C:\.
If you'd bothered checking the return value of file_put_contents, you'd have seen it was returning a boolean false to indicate failure.

PHP - Creating .txt document in Ubuntu

I am having trouble using fopen() to create a text document for later use as a cookie file.
I have read the documentation for this function, but to no avail.
Notes:
Ubuntu
read / writable ("w+")
I have tried several storage locations including:
/home/jack/Desktop/cookie
/var/www/cookie
/home/jack/Documents/cookie
PHP
echo "debug";
echo "\r\n";
$cookie = fopen("/home/jack/Documents/cookie", "w+");
fclose($cookie);
if(!file_exists($cookie) || !is_writable($cookie))
{
if(!file_exists($cookie))
{
echo 'Cookie file does not exist.';
}
if(!is_writable($cookie))
{
echo 'Cookie file is not writable.';
}
exit;
}
Result
file is not created
Output to browser: debug Cookie file does not exist.Cookie file is not writable.
Other Fun Facts
I have tried using fopen(realpath("/home/jack/Documents/cookie"), "w+")
echo "\r\n" gives a space. Why not a newline?
I believe the problem must be something to do with my permissions to create the file, but I have no problem "right-click" creating the text document on the Desktop.
THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS
echo "debug";
echo "\n";
$jack = "jack";
$cookie = "/home/jack/Documents/cookie";
touch($cookie);
chmod($cookie, 0760);
if(!file_exists($cookie) || !is_writable($cookie))
{
if(!file_exists($cookie))
{
echo 'Cookie file does not exist.';
}
if(!is_writable($cookie))
{
echo 'Cookie file is not writable.';
}
exit;
}
fclose($cookie);
THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS
Instead of fopen()..
touch() to create
chmod() for permissions
I also added user name jack to www-data group.
chmod($path, 0760) group read / write
Reference
chmod() octal values here.
Look at the documentation for file_exists again. It does not take a file handle as an argument, it takes a string filename. The same is true for is_writable. Even if it did, you are opening the file handle and then immediately closing it, so I'm not sure why you're trying to use the file pointer at all after it's been closed.
You may be correct in that you have improper permissions set, but I would start here, first.
Also, if you're only trying to create the file, you may look into using the touch method, instead:
if( touch( $filename ) ) {
// It worked!
} else {
// It didn't work...
}
The web server is not executing as your user. touch /home/jack/Documents/cookie && chmod 777 /home/jack/Documents/cookie to allow the web server user to access the file.
Note this is BAD in production environments.
It looks like a permission issue. What user is PHP running as? It's likely running as www-data or something similar. You should make sure that the folders you are trying to write to are writable by either the user or group that PHP is running as. If you created those folders while logged in a jack, they probably belong to jack:jack and are not accessible by www-data:www-data.
You can also add jack to the www-data group, to make things a bit easier for development.

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');
?>

Path to a file in a different drive?

My php file is here:
D:/Appserv/www/x/y/file.php
I want to load stuff from this folder:
E:/foldie
I don't know what path will lead me there.
$somePath="HELP ME HERE!!!!"
$dir=opendir($somePath);
//looping through filenames
while (false !== ($file = readdir($dir))) {
echo "$file\n";
}
Use full Windows path to the file it should be working: "E:\folder\file.txt"
or just copy the file in the local/project directory for testing purpose.
Set $somePath = "e:\\foldie". If that doesn't work, please indicate to us how it fails.
[Edit:: make sure you escape your backslashes in strings]

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