PHP rename directory failed - php

Well my PHP script generated an error with a hyperlink in it.
Does anyone know what's wrong?
PHP Warning: rename(./uploads/temp/00013/,./uploads/orders/39/) [<a href='function.rename'>function.rename</a>]: No such file or directory
update:
actual code in PHP
if(!file_exists('uploads/orders/')) {
mkdir('uploads/orders/'); // ensuring the orders folder exist
}
rename('uploads/temp/' . $u . '/', 'uploads/orders/' . $i . '/');
update:
Sorry, my fault. I coded to delete previous temp folder before this code execute. Thanks!

It seems that one (or both) of these directories don't exist:
uploads/temp/00013
uploads/orders/39
Have you checked that:
these directories exist?
Apache/PHP has permission to read/write in these directories?
Your current directory is really the parent directory of your "upload" directory?

When a computer tells you
No such file or directory
the first thing you should check is if the file/directory exists. This is not a random error message, it's given only in the specific situation when a file or directory you try to use does not exist.
In this case in particular, both ./uploads/temp/00013/ and ./uploads/orders/ have to exist. If orders doesn't exist it's not created for you.

Related

Handling images with php

I saw on internet a piece of php code to handle images, it goes like this:
$directory="books";
$dirint = dir($directory);
while (($archivo = $dirint->read()) !== false)
{
if (eregi("gif", $archivo) || eregi("jpg", $archivo) || eregi("png", $archivo))
{
echo '<img src="'.$directory."/".$archivo.'">'."\n";
}
}
$dirint->close();
The thing is that the code works ok if directory "books" is in the same directory as the php file, but I tried changing directory "books" to another directory, let´s say C:\Users\User and when I run the php file I get the following error:
Warning: dir(books): failed to open dir: No such file or directory in
C:\xampp\htdocs\PHP_Course\galeria.php on line 16
I´m beginning to believe that I can´t move the images directory, it has to be in the same directory as the php file.
Can anyone confirm this or I´m wrong and I´m not using the right path to point to the right directory?
Thanks in advance for any tips.
You can debug this by using the php function getcwd()
Can you try using
$dirint = dir(__DIR__ . DIRECTORY_SEPARATOR . $directory);
(also not that eregi() is deprecated and has been replaced by preg_match())
I´m beginning to believe that I can´t move the images directory, it
has to be in the same directory as the php file.
Can anyone confirm this?
No. Changing the directory should not be a problem, but you have to make sure it exists and your PHP code references the correct path.
If you move the directory books to another path, you have to adjust your variable:
$directory = 'C:\Users\User\books';
Keep in mind you have to change this if you ever plan to run the script on a different machine, especially on Linux. You might want to create a config file for the definition of this path.

PHP create folder if it does not exist

I am creating a medium size application.
This application consists of a lot of products.
Now these products have many images (one product can have 5 - 6 images)
To try and make some sort of ordering I want to create one folder for each product this folder contains all images that is bound to the product.
Now so far I have tried the following:
move_uploaded_file($file, APP.'product_images/'.$product_id.'/'.$image['name']);
However when I try this I get the following error:
Warning (2): move_uploaded_file(/var/www/udlejnings-priser/cake/app/product_images/22/afterClick.png): failed to open stream: No such file or directory [APP/Controller/ImagesController.php, line 56]
Warning (2): move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/php472ci6' to '/var/www/udlejnings-priser/cake/app/product_images/22/afterClick.png' [APP/Controller/ImagesController.php, line 56]
Now I am not a complete noob and know that this means that I am missing permissions to the folder.
However the problem is that if the folder does not exist (i.e this is the first time an image for that product is uploaded) then a new folder should be created.
My question is two parted.
Does this automatically create a new folder if it doesn't already exist?
How can I give permission to a newly created folder so that I avoid this problem?
[I] know that this means that i am missing permission to the folder.
Actually no =). The error message reads:
failed to open stream: No such file or directory
Which makes no reference to permissions the problrm is: the containing-folder you're trying to write to doesn't exist.
Does this automatically create a new folder if it doesn't already exist?
No.
How can i give permission to a newly created folder?
It's not necessary to do so - anything created will have the correct permissions to permit the webserver user to read the files. However first it's necessary to try and create a folder, which in the question isn't the case.
Using CakePHP, the Folder class can be used to do that:
App::uses('Folder', 'Utility');
$dir = new Folder('/path/to/folder', 2);
The second parameter is used to create a new folder if it doesn't exist. In the context of the question that means the code would look something like this:
function whatever() {
if ($this->request->data) {
...
$unused = new Folder(APP.'product_images/'.$product_id, true);
if (move_uploaded_file($file, APP.'product_images/'.$product_id.'/'.$image['name'])) {
...
} else {
...
}
}
}
The folder APP/product_images should already exist, and must have permissions such that the webserver user (e.g. apache) can write to it otherwise it will not be possible to create the sub-folders/upload files. Assuming APP/product_images exists and the webserver user has permissions to write to it, there is no need to modify permissions of uploaded files - files created by a user are by default readable by that user.
Try this:
if (!file_exists('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
1) Does this automaticly create a new folder if it doesnt already exist. => file_exists and mkdir
2) how can i give permission to a newly created folder so that i avoid this problem => 0777
No, it won't create the folder dynamically.
Use chmod() to change permissions.
For checking the existence of some folder you can use is_dir() too.
It's always a good idea too add the magic constant
__DIR__
to the file or directory path.
( __DIR__
gives out the path to the directory in which your script is located). In the errormessages "APP" is highlighted in a different colour than the path name. This could be a hint that the path cannot be located.

permission denied - php unlink

I have two files:
b.php and test.txt
<?php
$b = "test.txt";
unlink($b);
?>
and the error is: Warning: unlink(test.txt) [function.unlink]: Permission denied
why? b.php and test.txt is 777 and the same group/login
if I set 777 on the parent directory I can execute unlink but i have to set 777 and back to 755?
You (as in the process that runs b.php, either you through CLI or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.
Note that if you use the PHP chmod() function to set the mode of a file or folder to 777 you should use 0777 to make sure the number is correctly interpreted as an octal number.
You'll first require to close the file using fclose($handle); it's not deleting because the file is in use. So first close the file and then try.
in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink() , u will encounter with a wrong Warning message that says "permission denied"
however u can make folders & files by mkdir() but the way u delete folders (rmdir()) is different from the way you delete files(unlink())
eventually as a fact:
in many programming languages, any permission related error may not
directly means an actual permission issue
for example, if you want to readSync a file that doesn't exist with node fs module you will encounter a wrong EPERM error
// Path relative to where the php file is or absolute server path
chdir($FilePath); // Comment this out if you are on the same folder
chown($FileName,465); //Insert an Invalid UserId to set to Nobody Owner; for instance 465
$do = unlink($FileName);
if($do=="1"){
echo "The file was deleted successfully.";
} else { echo "There was an error trying to delete the file."; }
Try this. Hope it helps.
The file permission is okay (0777) but i think your on the shared server, so to delete your file correctly use;
1. create a correct path to your file
// delete from folder
$filename = 'test.txt';
$ifile = '/newy/made/link/uploads/'. $filename; // this is the actual path to the file you want to delete.
unlink($_SERVER['DOCUMENT_ROOT'] .$ifile); // use server document root
// your file will be removed from the folder
That small code will do the magic and remove any selected file you want from any folder provided the actual file path is collect.
In Windows and before PHP version 7.3.0, check that your file has been closed before unlinking it,
as said in https://www.php.net/manual/en/function.unlink.php :
On Windows, it is now possible to unlink() files with handles in use, while formerly that would fail. However, it is still not possible to re-create the unlinked file, until all handles to it have been closed.
As an exemple :
$fullFilePath = 'C:\Users\MyUserName\www\myApp\public\test.txt';
$handle = fopen($fullFilePath , 'w+');
fopen($filePath, 'w+');
fputs($handle, 'Some text in the file');
fclose($handle);
unlink(realpath($insertedLinesFilePath));

scandir fail to open directory

I am having trouble with scandir(). I am trying to display the files in my snaps-directory on a page under the subdomain in my cloud.
This is the PHP I used.
$files = scandir('./snaps');
print_r($files);
and this is the error.
Warning: scandir(./snaps) [function.scandir]: failed to open dir: No such file or directory in /home/u703778423/public_html/cloud/index.php on line 39
Warning: scandir() [function.scandir]: (errno 2): No such file or directory in /home/u703778423/public_html/cloud/index.php on line 39
I have no idea what else to do.
You probably assume, that the current work directory is next to the script scandir() is written in, which (in many cases) isn't.
scandir(__DIR__ . '/snaps');
Given that error, your snaps directory would have to have the absolute path of
/home/u703778423/public_html/cloud/snaps
Make sure that this is the correct location for the directory, and that the webserver has the rights to access it.
First off you're trying to display a few files that will not render as images... ex. (.zip).
Also are you making sure you're not trying to display the first two index values " . " and " .. "? I'm thinking this part of your code might not be the issue...

Weird behaviour of rename() in PHP

I am having a weird problem with my php. Whenever I try to move a file with rename(), not only the file is not moved, but also the directory to which it should be copied is deleted, together with all files within it. The original code is:
rename('temp.odt', 'tmp/report.odt');
but I have already tried other path delimiters like
rename('temp.odt', 'tmp\report.odt');
rename('temp.odt', 'tmp\\report.odt');
rename('temp.odt', 'tmp' . DIRECTORY_SEPARATOR . 'report.odt');
rename('C:\wamp\www\zaiko\temp.odt', 'C:\wamp\www\zaiko\tmp\report.odt');
all to no avail. The code comes from a 3rd-party module which is used in the system I am working on.
Points well checked:
The file 'temp.odt' does exist in the current directory;
The directory 'tmp' does exist and there are several files in it. Also it is not read only.
The target file does not already exist (the actual file name has a timestamp, I reduced it here for simplicity)
After running rename(), the 'temp.odt' file is intact in its original location, while the folder 'tmp' is vanished as well as everything inside it. The following warning is issued:
( ! ) Warning: rename(temp.odt,tmp\report.odt) [function.rename]: The system couldn't find the specified path*. (code: 3) in C:\wamp\www\zaiko\modules\mod_deliver.php on line 192
*translated from Portuguese
Running: Apache 2.2.17 with PHP 5.3.5 on Windows XP with NTFS
Editing:
Just found the cause of the problem. It turns out that the module used by the application uses, in turn, a compression library; this library uses a temporary folder with exactly the same name as the one used by the application.
It must use some sort of cache, which would explain why the error didn't appear 100% times.
Problem solved by changing the name of the 'tmp' folder to anything else.
Thank you all for your time, and sorry for bothering you with such a stupid thing that, as it turns out, had absolutely nothing to do with my initial guess and, consequently, with the question formulated.
The example on PHP.net tells you exactly what to do - use the ROOT PATH to the file - normally this can be got by using $_SERVER['DOCUMENT_ROOT'] (but this only goes to the htdocs/public_html directory - you need to specify the rest) or by manually typing the path in (but try to avoid this).
<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>
At a guess, the following should work (assuming this is your path) - this also checks that your file actually exists so it can be renamed - you need to make sure that tmp/ actually exists in the first place, but you will get an error popping out if it didn't:
<?php
$root = getcwd().DIRECTORY_SEPARATOR; // Obtain the current working dir
$srcpath = $root."temp.odt"; // The file you want to rename
$destpath = $root."tmp/report.odt"; // Where you want to rename the file to
// make sure file exists and its movable
if(is_writable($srcpath)){
// if it exists, rename it
rename($srcpath, $dstpath);
echo "File was renamed!";
} else {
echo "It seems that the specified file doesn't exist!";
}
?>
You were escaping characters by using backslashes - always use forward slashes (I know this is within a single quote, which is ok, but if you use double quote then you would wonder what's gone wrong)!

Categories