PHP rename(<from>, <to>) gives warning: "Is a directory" - php

I have the following function:
function move($currentPath, $newPath)
{
if (!$this->_createFolder($newPath))
return false;
if (!rename($currentPath, $newPath))
return false;
return true;
}
where _createFolder() checks if the directory exists, and if it doesn't, creates it. I'm consistently getting the following warning:
"rename(/home/user/folder/folder/app/webroot/img/listings/incomplete/15/0/picture1.png,/home/user/folder/folder/app/webroot/img/listings/130/picture1.png): Is a directory "
The file is successfully copied to the second directory, but is not deleted from the first directory. rename() returns false and this warning is given. I thought it might be something with permissions, but after trying a bunch of things I couldn't seem to figure it out.
Any help would be appreciated.

your code is creating a folder using the $newpath
if (!$this->_createFolder($newPath))
return false;
then $newpath becomes a directory.

Related

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 and Creating Directories

Quick question. I'll start off with an example.
I have a social site similar to Facebook. When a user signs up my PHP script creates a directory named after his username and a custom sub-directory for this user called "photos".
The "photos" directory is never created when someone signs up. I assume it is because the actual server hasn't created the actual username directory in the first place.
My solution is that anytime i need to execute the photo function on my site for a user I should check if the folder exists and if not create it, which works fine. Is this standard procedure? Or is there a better way to create multiple directories at the same time while running checks.
When someone signs up I run this code, and the latter if statement doesn't successfully create the photos folder, so i check these two statements anytime I am editing something that would go in photos as a check for if the folder exists.
if (!file_exists("user/$username")) {
mkdir("user/$username", 0755);
}
if (!file_exists("user/$username/photos"))
{
mkdir("user/$username/photos", 0755);
}
The directories are created sequentially/synchronously thus once execution of the first mkdir() is finished the folder should be there with the indicated permission set.
As stated here the mkdir()
Returns TRUE on success or FALSE on failure.
and
Emits an E_WARNING level error if the directory already exists.
Emits an E_WARNING level error if the relevant permissions prevent
creating the directory.
So you can go:
if (!file_exists("user/$username")) {
if(mkdir("user/$username", 0755))
{
//directory created
if (!file_exists("user/$u/photos"))
{
mkdir("user/$username/photos", 0755);
}
}
else
{
//directory not created
}
}
If the mkdir() returns false - check the logs or handle the error.
You can do a quick directory 'exists' check like this
function check($images_dir) {
if($handle = opendir($images_dir)) {
// directory exists do your thing
closedir($handle);
} else {
// create directory
}
}
Where $images_dir = path/directory/user/$username

Silverstripe 3.1 - mkdir() issue bug or local issue?

I seem to get this error on my local server when the site is loaded for the first time e.g. in the morning. Once I do a refresh it's gone...
I'm using silverstripe 3.1.
Is there a way to prevent this locally or is this a bug?
Warning: mkdir(): File exists in /framework/core/manifest/ManifestCache.php on line 19
Looks like line 19 is trying to create a TEMP folder but it already exists...
function __construct($name) {
$this->folder = TEMP_FOLDER.'/'.$name;
if (!is_dir($this->folder)) mkdir($this->folder);
}
Should that function check if the folder exists first e.g.
if (!is_dir($this->folder) || !file_exists($this->folder)) mkdir($this->folder);
Seems that there exists a file with the same name as the directory. That's why is_dir() returns false but mkdir() fails because the file exists.
You can change this to:
if (!file_exists($this->folder)) mkdir($this->folder);
This should work so far.
However it is necessary to mention that such file existence tests are vulnerable against race conditions by design. That's why you need to additionally check the return value of mkdir():
if (!file_exists($this->folder)) {
if(#mkdir($this->folder) === FALSE) {
throw new Exception('failed to create ' . $this->folder);
}
}
This may not being required if you (or the framework) has registered a global error handler which turns warning into exceptions, because mkdir() will throw a warning on errors.

PHP: How to check if file not exists or permission is denied?

I want to check if file do not exists. When file_exists() function returns false I can't be sure if the file do not exist or I don't have permission to the file.
How to discern that two possibilities?
Maybe is_readable is what you want?
Well, you could first try file_exists(). In the event that fails, you could try fopen() with the +a flag. If that fails, you don't have permission.
I want to check if file do not exists. When file_exists() function returns false I can't be sure if the file do not exist or I don't have permission to the file.
No, you must have understood something wrong. file_exists() will return TRUE if the file exists and FALSE if not. That has nothing to do with permissions of that file.
E.g. a file of which my script does not have permissions to read will make file_exists return TRUE because it exists.
However if I test with is_readable on that file, it will return FALSE. I don't have permissions to read the file.
Example:
$file = 'unreadable';
var_dump(file_exists($file), is_readable($file));
Output:
bool(true)
bool(false)
Edit: Naturally, this is bound to the underlying system-libraries that PHP makes use of to obtain the information for file existence and file permissions. If PHP is not allowed to obtain the status about whether a file exists or not, it will tell you that the file does not exists. That's for example the case if you've got a directory which exists, but is not readable to the user:
$dir = 'unreadable';
$file = $dir.'/unreadable.ext';
var_dump(file_exists($dir), is_readable($dir));
# bool(true)
# bool(false)
var_dump(file_exists($file), is_readable($file));
# bool(false)
# bool(false)
As you would like to obtain the existence status of $file, the underlying permissions don't allow you to obtain it. Therefore the file does not exist for you. That's equally correct and you should be more precise what you actually need to find out. Because for you, the file does not exists. That's how directory permissions work (all examples are run on windows here, but these things are that common, that you have it in every common file-system implementation).
I hope that sheds some light into your issue.
I wrote function which check if file can exists. It return false if there is no such file in filesystem, otherwise it returns true. My function checks (bottom-up) directory structure. One should be fairly sure that $root directory exists.
private function fileCanExists($root, $path) {
$root .= '/';
if (file_exists($root . $path))
return true;
while ($path != '.') {
$path = dirname($path);
if (file_exists($root . $path)) {
if (is_readable($root . $path))
return false;
else
return true;
}
}
return false;
}
That is what mean when I wrote:
I want to check if file do not exists.
Check with is_readable and if return false, check with file_exists

Check if directory is created (Wordpress and/or PHP)

I'm relatively new to PHP and I'm trying to write my own plugin. Upon plugin activation it will run the following function:
function kb_create_uploadfolder () {
global $wpdp;
$upload_dir = wp_upload_dir();
$upload_dir = $upload_dir['basedir'] . "/plugin_uploads";
$upload_dircheck = wp_mkdir_p($upload_dir);
}
I didn't bother to check whether the directory already exists before creating it since I figured it won't overwrite anything or delete the contents if it does. Correct me if I'm wrong.
The thing is however, I would like to check if the creation of the directory was succesful or not but I can't figure out how to get this information.
Use is_dir():
if(is_dir($upload_dircheck))
{
echo "It is a dir";
}
else
{
echo "Sorry, non-existent or not a dir";
}
Also, mkdir() doesn't delete or overwrite existing contents, it just creates a directory if it does not yet exist.
If you're using PHP 4 or newer then you can use the is_dir() function.
Try is_dir().

Categories