PHP - How to unlink a file with no file extention - php

This work great to delete php, txt and images but I recently starting using an image resize that inserts temp images in to my trash folder.
* example name 2616cf442b6cd3e1313161551fad6078 *
File type: text/x-generic
Permission: 0644
Tried renaming to .txt with no luck
$cleantrash =(DOCROOT."/woobe/myfiles/trash/");
$cleantrash = opendir($cleantrash);
while (($filex_clean = readdir($cleantrash)) !== false) {
if($filex_clean != "." && $filex_clean != ".." && $filex_clean != "index.php") {
echo "<b>Cleaing Trash...</b> $filex_clean<br>";
unlink($filex_clean);
}
}
closedir($cleantrash);
*EDIT *
$newname = basename($filename, ".bmp").".jpg";
rename($filename, $newname);
and the files are gone lol. No unlink useds? so where did they go?

The readdir() function returns file names without their paths (relative to the resource directory parameter you pass it).
The unlink() function expects the full file path. My guess would be that you need to save the $cleantrash path instead of overwriting it with the resource from opendir(), and then do something like:
unlink($cleantrash . $filex_clean);

Related

Copy() function can't detect destination path php [duplicate]

Anyone know why this:
<?PHP
$title = trim($_POST['title']);
$description = trim($_POST['description']);
// Array of allowed image file formats
$allowedExtensions = array('jpeg', 'jpg', 'jfif', 'png', 'gif', 'bmp');
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
echo '<div class="error">Invalid file type.</div>';
}
}
}
if (strlen($title) < 3)
echo '<div class="error">Too short title</div>';
else if (strlen($description) > 70)
echo '<div class="error">Too long desccription.</div>';
else {
move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/');
}
Gives:
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in C:\wamp\www\upload.php on line 41
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\wamp\tmp\php1AB.tmp' to 'c:\wamp\www\uploads\images/' in C:\wamp\www\upload.php on line 41
It's because you're moving a file and it thinks you're trying to rename that file to the second parameter (in this case a directory).
it should be:
move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:/wamp/www/uploads/images/'.$file['name']);
You are specifying to move a file to a directory; neither PHP's move_uploaded_file nor its copy is as smart as a shell's copy -- you have to specify a filename, not a directory, for the destination.
So, one simple solution would be to take the basename of the source file and append that to the destination directory.
It sounds like the second argument to move_uploaded_file should be a full file name instead of just the directory name. Also, probably only a style issue, but you should use consistent slashes in 'c:\wamp\www\uploads\images/'
Because PHP is not a shell. You're trying to copy the file into the c:\wamp\www\uploads\images directory, but PHP doesn't know you mean that when you execute (within the move_uploaded_file function):
copy($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/');
This command tells it to rename the file to c:\wamp\www\uploads\images/, which it can't do because that's the name of an existing directory.
Instead, do this:
move_uploaded_file($_FILES['userfile']['tmp_name'],
'c:\wamp\www\uploads\images/' . basename($_FILES['userfile']['tmp_name']));
if you want just copy the file in two Dir different, try this :
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target.$pic1))
{
copy("C:/Program Files (x86)/EasyPHP-5.3.9/www/.../images/".$pic1, "C:/Program Files (x86)/EasyPHP-5.3.9/www/.../images/thumbs/".$pic1)
}
You should write the complete path "C:/..."
Try adding the extension to the name file.
$filename = $_FILES['userfile']['tmp_name'].".jpg";
It will be like below in phalcon 3.42
if ($this->request->hasFiles() == true) {
// Print the real file names and sizes
foreach ($this->request->getUploadedFiles() as $file) {
//Print file details
echo $file->getName(), " ", $file->getSize(), "\n";
//Move the file into the application
$file->moveTo($this->config->application->uploadsDir.$file->getName());
}
}
FIRSTLY FIND YOUR CURRENT DIRECTORY echo getcwd(); IF YOU FIND THE CURRENT DIRECTORY SO MOVE THEM ANOTHER DIRECTORY
FOR EXAMPLE = echo getcwd(); these output is "your live directory name" like that -> /opt/lampp/htdocs/product and create new directory anywhere but your current directory help to go another directory ***
plz read carefully very thinking answer

PHP Delete all files that are empty in a Directory and any sub directories

This is what I have but its not working nor giving me an errors:
$MyDir = "C:/some_folder/";
// DELETE ALL EMPTY FILES
$filesDVA = glob($MyDir.'*'); // get all file names
foreach($filesDVA as $file){ // iterate files
if(empty($file))
unlink($file); // delete file
}
I would like to delete the empty files that are in the main directory and sub directories and if possible check if the directory is empty also and if it is delete it too.
UPDATE:
foreach (glob($MyDir . '*') as $file) {
if (is_writable($file) && filesize($file) < (1024 * 1)) {
unlink($file);
}
}
It removes the empty files (or files that are less than 1kb but it gives me an error when trying to access the directories saying Permission denied for each directory, so it will NOT delete the empty directories or the files that are within the sub directories.
empty($file) doesn't check that the file referenced by $file is empty, it checks that the variable $file is empty. I.e., if $file contains an empty string "" or null then empty($file) will return true. Since your $file contains a non-empty string (the name of the file), empty($file) will always return false, regardless of the file contents. You want to check that filesize($file) is zero.

How to get file name from full path with PHP

This is my upload php:
if (trim($_FILES['path_filename']['name']))
{
if (File::upload($_FILES['path_filename'], dirname(realpath(__FILE__)) . '/../tests'))
{
$test->setPathFilename('../tests/' . $_FILES['path_filename']['name']);
}
}
}
else
{
if ($aux)
{
$aux = str_replace("\\", "/", $aux);
$aux = preg_replace("/[\/]+/", "/", $aux);
$test->setPathFilename($aux);
}
}
$_POST["upload_file"] = $test->getPathFilename();
This above code is working well, I mean, upload to server is working and also getting Path File Name and insert into sql table is working too.
Example: When I upload a file for example: ABC.jpg , it will upload to tests folder and also Path File Name is (( ../tests/ABC.jpg )) and it will insert to sql table.
The problem is here:
I changed global function to rename files automatically by using this following code:
Before It was:
$destinationName = $file['name'];
I changed it to:
$ext = pathinfo($file["name"], PATHINFO_EXTENSION);
$destinationName = sha1_file($file["tmp_name"]).time().".".$ext;
Now, After upload file to tests folder, it will be renamed automatically, but still Path File name is same, It's ABC.jpg not renamed file in tests folder.
How to get Renamed Path File Name ???
I really appreciate your help on this issue.
Thanks in advance
Use basename() to get the filename from a path.
$filename = basename('/path/to/file.ext');
This will give you: file.ext
To rename the path file name you could use this:
if ( !file_exists( $path ) ) {
mkdir( $path, 0777, true );
}
This will make sure the path exist and if it doesn't it will created. Now we can rename()
rename( __FILE__ "/new/path/".$file_name );
This will move it between directories if necessary.

delete folder with all content with php

I have main folder named "gallery". In this folder there are some sub folders like "animal", "tree", etc. folder "animal" contains some pictures and so on. suppose i want to delete "animal" folder with all pictures in it, how can do this?
i tried-
rmdirr($_SERVER['DOCUMENT_ROOT']."admin/gallery/animal");
but in server, it deleted the whole "gallery" folder with all in it. please tell me what i am doing wrong and also give me a solution. thanks in advance.
If there are no subfolders you can use glob() to empty the directory before using rmdir():
foreach( glob( "/path/to/dir/*.*" ) as $filename ) {
unlink( $filename );
}
rmdir( "/path/to/dir" );
By the way, rmdir() shouldn't delete any files. It just fails if the directory isn't empty. You might want to make sure there's nothing else in your code that causes the parent directory to be wiped out.
Just delete the directory recursively with a helper function:
rrmdir($_SERVER['DOCUMENT_ROOT']."admin/gallery/animal");
function rrmdir($path)
{
return is_file($path)
? #unlink($path)
: array_map('rrmdir', glob($path.'/*')) == #rmdir($path)
;
}
When removing a desired directory, you must first remove the files within that directory. Once that is complete, then you may remove the directory -- assuming you have the proper permissions.
Included below is code that removes the files in the directory and will then remove the specified directory itself:
<?php
$dirname = "animal";
function destroy($dir) {
$mydir = opendir($dir);
while(false !== ($file = readdir($mydir))) {
if($file != "." && $file != "..") {
chmod($dir.$file, 0777);
if(is_dir($dir.$file)) {
chdir('.');
destroy($dir.$file.'/');
rmdir($dir.$file) or DIE("Unable to delete $dir$file");
}else{
unlink($dir.$file) or DIE("Unable to delete $dir$file");
}
}
}
closedir($mydir);
}
destroyDir($dirname);
?>

The second argument to copy() function cannot be a directory

Anyone know why this:
<?PHP
$title = trim($_POST['title']);
$description = trim($_POST['description']);
// Array of allowed image file formats
$allowedExtensions = array('jpeg', 'jpg', 'jfif', 'png', 'gif', 'bmp');
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
echo '<div class="error">Invalid file type.</div>';
}
}
}
if (strlen($title) < 3)
echo '<div class="error">Too short title</div>';
else if (strlen($description) > 70)
echo '<div class="error">Too long desccription.</div>';
else {
move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/');
}
Gives:
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in C:\wamp\www\upload.php on line 41
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\wamp\tmp\php1AB.tmp' to 'c:\wamp\www\uploads\images/' in C:\wamp\www\upload.php on line 41
It's because you're moving a file and it thinks you're trying to rename that file to the second parameter (in this case a directory).
it should be:
move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:/wamp/www/uploads/images/'.$file['name']);
You are specifying to move a file to a directory; neither PHP's move_uploaded_file nor its copy is as smart as a shell's copy -- you have to specify a filename, not a directory, for the destination.
So, one simple solution would be to take the basename of the source file and append that to the destination directory.
It sounds like the second argument to move_uploaded_file should be a full file name instead of just the directory name. Also, probably only a style issue, but you should use consistent slashes in 'c:\wamp\www\uploads\images/'
Because PHP is not a shell. You're trying to copy the file into the c:\wamp\www\uploads\images directory, but PHP doesn't know you mean that when you execute (within the move_uploaded_file function):
copy($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/');
This command tells it to rename the file to c:\wamp\www\uploads\images/, which it can't do because that's the name of an existing directory.
Instead, do this:
move_uploaded_file($_FILES['userfile']['tmp_name'],
'c:\wamp\www\uploads\images/' . basename($_FILES['userfile']['tmp_name']));
if you want just copy the file in two Dir different, try this :
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target.$pic1))
{
copy("C:/Program Files (x86)/EasyPHP-5.3.9/www/.../images/".$pic1, "C:/Program Files (x86)/EasyPHP-5.3.9/www/.../images/thumbs/".$pic1)
}
You should write the complete path "C:/..."
Try adding the extension to the name file.
$filename = $_FILES['userfile']['tmp_name'].".jpg";
It will be like below in phalcon 3.42
if ($this->request->hasFiles() == true) {
// Print the real file names and sizes
foreach ($this->request->getUploadedFiles() as $file) {
//Print file details
echo $file->getName(), " ", $file->getSize(), "\n";
//Move the file into the application
$file->moveTo($this->config->application->uploadsDir.$file->getName());
}
}
FIRSTLY FIND YOUR CURRENT DIRECTORY echo getcwd(); IF YOU FIND THE CURRENT DIRECTORY SO MOVE THEM ANOTHER DIRECTORY
FOR EXAMPLE = echo getcwd(); these output is "your live directory name" like that -> /opt/lampp/htdocs/product and create new directory anywhere but your current directory help to go another directory ***
plz read carefully very thinking answer

Categories