For some reason all folders created dynamically using my PHP upload script get permission 1354 and then it's not possible to save files inside them.
if(!file_exists($options['uploadDir']) && !is_dir($options['uploadDir'])
&& mkdir($options['uploadDir'], 0750, true))
{
$this->data['hasWarnings'] = true;
$this->data['warnings'] = "A new directory was created in " .
realpath($options['uploadDir']);
}
if(!is_writable($options['uploadDir']))
#chmod($options['uploadDir'], 0750);
I don't know what am I doing wrong.
Check parameters of your http server especially the profile of the user running it and the default user profile of the system. There may be a "umask" set somewhere forcing another permission.
You can try to change the umask with a php command umask.
Also you can check the permission of the parent folders and also check the ownership of your folder.
Related
My goal :
I want to create Registration Form, when the registration is success so I direct to 'user profile -> index page'.
Directory :
Registration page in : myproject/account/create.php
User profile -> index page in : myproject/profile/nameuser/index.php
Step How it work :
1. Fill registration form
2. Submit form
3. If fail, fill again until success
4. When success, go to folder profile, then create a unique new folder for new user (it mean user folder), then create index page in user folder, then bring each user to access their each index page.
My problem :
I am trying to using method mkdir() in PHP but it can't solve because permission is denied
If any configuration in Linux to solve, I don't know what is the way
My Code :
if (empty($err)) {
if ($insert_stmt = $mysqli->prepare("INSERT INTO member (uname, mail, pwd) VALUES (?, ?, ?)")) {
$insert_stmt->bind_param('sss', $uname, $mail, $pwd);
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: INSERT');
}
}
$directory = "../profile/$uname";
if(!is_dir($directory)) {
mkdir("$directory");
touch('$directory/index.php');
}
header('Location: $directory . index.php');
}
Hope someone can help me to solve my problem.
before proceeding to create the directory try to change the permissions of the project folder to 755 or 777
chmod -R 755 myproject/
if its still not working try it with permission 777
chmod -R 777 myproject/
and also while creating directory with mkdir you should assign permissions simultaneously
mkdir("$directory", 0755);
Usualy your server run on a user account different from your user account on the machine. Apache can read your file to send it to your client but it doesn'T have write permission over your files.
Options:
Option one, make you folder writable using http://php.net/manual/en/function.chmod.php but this can be a security issue and some host will serve a 500 (internal) error if they find any 777 folder in your user folder. One trick is to use chmod(0777), write the file and re chmod(0755 or 0644) after write. check linux permission if you need a lead on the 'code' https://www.linux.com/learn/understanding-linux-file-permissions. You don'T provide the right code to make it haappend for you but it would be something like
$perm=substr(sprintf('%o', fileperms('../profile/')), -4); //current perm
chmod ("../profile/", "0777"); //make the parent folder writable
mkdir("$directory");
touch('$directory/index.php');
chmod ("../profile/", $perm); // make it back to old perms.
Another option is to add you and apache to a group ad then give write permission to this group but that would be for another stack exchange site.
You could also create a folder and chown (change onwership) to apache, but again it has it's flaw as when you will want to write on it yourself.
NOTE: all solution to your probem are subject to the operating system file permission. and you need to under stand the difference bewteen your user, apache user and even some host are using a user for php.
I am trying to make a directory when a new account is created.
The directory should be in my images folder and is used to better separate uploaded images.
//get the ID of the new account that was just created/inserted
$accountID = mysqli_insert_id($dbc);
//create a new directory path for that account
$directoryPath = "../images/" . $accountID;
// check if the directory exists
if (!is_dir($directoryPath)) {
//create the directory
mkdir($directoryPath, 0777); //breaking here
}
I had no problem getting this to work a few days ago, however when testing it today I am having problems.
I have included ini_set('display_errors', 'On'); in my page to see what error I am being thrown and it is a permission error.
Warning: mkdir(): Permission denied
The images folder has full read/write permissions for all users and groups as well as any parent folders so I don't understand how that would be an issue, that and it had worked several times before.
I am working on windows if that matters.
Any ideas?
To avoid spending too much time on permissions problems between the CLI user and the Apache user, an easy configuration is to use same user for both processes.
Get your user id and group by doing
$ id
uid=1000(my_user), gid=1000(my_group), ...
And then:
$ sudo service apache2 stop
$ sudo vi /etc/apache2/envvars
export APACHE_RUN_USER=my_user
export APACHE_RUN_GROUP=my_group
$ sudo chown -R my_user /var/lock/apache2
it's better and safer than to change you whole directory permission to 777
I think you should try this -
mkdir("../images/".$accountID, 0777, 'R');
Recursive folder creation may causing the problem.
Also get more information from - mkdir
Also check for folder permission.
You have to be sure that the parent directory allows you to create folder, and not the folder it self that is being created with 0777 rights...
Also, check with which user the Apache server is launched
Check if directory is already exist before using mkdir()
if (!is_dir ($directoryPath) ) {
mkdir($directoryPath, 0777);
}
I am working on windows if that matters.
It does.
Try changing this
if (!is_dir($directoryPath)) {
//create the directory
mkdir($directoryPath, 0777); //breaking here
}
To this
if (!is_dir($directoryPath)) {
//create the directory
mkdir($directoryPath); //breaking here
}
You are on a Windows box so it will ignore the chmod mode. Also try using the full paths and not relative.
The mode is 0777 by default, which means the widest possible access.
For more information on modes, read the details on the chmod() page.
Note:mode is ignored on Windows.
http://php.net/manual/en/function.mkdir.php
We are using a linux dedicated server in our company.
Whenever we create a folder with php script, apache is owning the folder and each time I have to connect to server via root in order to change the owner to the user and the permissions
But I don't know which setting I should change in order to fix this.
I tried to switch the safe mode on/off but it didn't work.
I'd be glad if someone could help me
Thanks in advance
Have you tried using the chown PHP command and chmod PHP command?
There are 2 ways to do this:
chown() where you can change the file permissions via executing that function.
or if you are able to move files around using an FTP, you can drag the file outside of the document root (public_html/), and right click -> change file permissions on the file.
CHMODs are what you want to be looking at. 777 will give anyone and everything access to your file, which you can use as a test to make sure you have file permissions. I don't recommend keeping the permissions on 777 at all though.
This is a portability issue and depends on your server configuration (i.e. mod_php or FCGI with SuExec).
You can try using the chown function right after you created the file, but that will only work if you know who the actual owner should be (which is not always the case). To overcome this issue, I wrote a simple method that tries to find the best possible file mode that always assures reading and writing (as well as execution for directories) without giving excessive permissions:
function xChmod($path, $chmod = null) // adapted from phunction
{
if (file_exists($path) === true)
{
if (is_null($chmod) === true)
{
$chmod = (is_dir($path) === true) ? 777 : 666;
if (extension_loaded('posix') === true)
{
$user = posix_getpwuid(posix_getuid());
if (array_key_exists('name', $user) === true)
{
$chmod -= (in_array($user['name'], explode('|', 'apache|httpd|nobody|system|webdaemon|www|www-data')) === true) ? 0 : 22;
}
}
}
return chmod($path, octdec(intval($chmod)));
}
return false;
}
Basically, if you omit the second $chmod argument, it will use 0777 for folders and 0666 for files by default, however, if PHP is being run under a non-standard user, it will decrement the mode by 22, yielding 0755 for folders and 0644 for files. Bare in mind that this will only work for files that already exist, so if you're creating a directory you'll need to have additional precautions.
i was using this basic script:
$folderPath = "../path/to/$folder/";
mkdir("$folderPath");
i create this directory and then upload photos to it. I've been doing this for a good 4-5 months now and suddenly i start getting 'FORBIDDEN' errors when I attempt to view the contents of the folder via web browser
The directory is being created the same and the photos are still uploading without a problem, but I cannot access the photos
I tried rewriting the script and using chmod to change the permissions but I'm having no luck at all
All the older folders were being created with: -w- rwx r-x r-x
and I can't get this recreated
I've tried adding a chmod line into my script:
$folderPath = "../sales/inventory/$folder/";
mkdir("$folderPath");
chmod("$folderPath", 0755);
but I can't recreate the same permissions, I'm trying to understand how chmod works, but I can't figure out how to get this very basic function working properly again
Try looking out for a HTAccess file, where the "Options -Indexes" option will be mentioned, as this is mostly used for not showing the contents of a folder in a web browser. The file needs to be searched in the following manner:-
In the folder "root_folder/sales/inventory/$folder/", where "$folder" is as mentioned in your code.
If not found, try in the folder "root_folder/sales/inventory/".
If not found, try in the folder "root_folder/sales/".
If not found, try in the folder "root_folder/".
When you get the code of "Options -Indexes" written in the HTAccess file, you can remove / comment that line of code from there, or you can also write another HTAccess file in your required folder of "$folder", where the code will be "Options Indexes".
Also in the PHP page, the logic must be like this:-
<?php
$folderPath = "../sales/inventory/$folder/";
mkdir("$folderPath");
chmod("$folderPath", 0755);
// Use of "copy()" / "move_uploaded_file()" function here, using some "$targetFile" variable.
chmod($targetFile, 0755);
?>
This will help you when you will be unlinking / deleting the uploaded files from the "$folder" folder.
Hope it helps.
If your $folder variable includes some sub-directories your parent directories are maybe not being chmoded to the right permissions. This was the problem I was having on a hired OVH Gentoo server.
Imagine that $folder = '/store1/ally23/shelf42'; so your final directory structure is
../sales/inventory/store1/ally23/shelf42, and you want 0777 permisions.
You do:
mkdir($folderPath, 0777, true) || chmod($folderPath, 0777);
Only the final directory shelf42 is chmoded to 0777. The intermediary directories are created with default permissions (in my case 0744).
There is no recursive option in PHP's chmod command, so you have to loop over the intermediary directories and chmod them individually.
If you're in a shared environment, you may also want to chown after upload, to be on the safe side. Especially if you're running your web server under a user other than your virtual host has permission to access (EG: "nobody" vs "mysite".) This is common with cPanel servers, FWIW.
Simply umask means the default permissions for new files/directories:
<?php
umask(022);
?>
This sets the default permissions for user, groups, and others respectively:
0 - read, write and execute
1 - read and write
2 - read and execute
3 - read only
4 - write and execute
5 - write only
6 - execute only
7 - no permissions
I have an easy script to create and delete a folder, but when I try to delete a folder, it brings up and error.
The code:
<?php
if ($_POST['hidden']) {
$key = "../g_test/uploads";
$new_folder = $_POST['nazevS'];
$new_dir_path = $key."/".$new_folder;
$dir = mkdir($new_dir_path);
if($dir)
chmod ($new_dir_path, 0777);
}
if ($_POST['hiddenSS']) {
$key = "../g_test/uploads";
$new_folder = $_POST['nazevS'];
rmdir($key."/".$new_folder);
}
?>
The error msg:
Warning: rmdir(../g_test/uploads/) [function.rmdir]: Permission denied in /home/free/howto.cz/m/mousemys/root/www/g_test/upload.php on line 51
Does anyone know how to delete the folder (hopefuly with everything inside) ?
Also if you see any other improvments, the code could have, feel free to tell me. :-)
Thanks, Mike.
Generally speaking PHP scripts on Unix/Linux run as user "nobody", meaning they need the "all" privileges so it's a permissions problem with the directory. Also, to delete a file or directory in Linux/Unix you need write privileges on the parent directory. That might be your problem.
If you have problems with the files or directories you create, use chmod() on them to set the right permissions.
Also it might not be empty.
Also, it's worth mentioning that
$new_folder = $_POST['nazevS'];
$new_dir_path = $key."/".$new_folder;
is really bad from a security point of view. Sanitize that input.
For the purpose of this answer, I will put the security risks of allowing any and all uploads in a directory aside. I know it's not secure, but I feel this issue is outside the scope of the original question.
As everybody said, it can be a permission problem. But since you've created the directory in your code (which is most likely running as the same user when deleted). It doubt it is that.
To delete a directory, you need to make sure that:
You have proper permissions (as everyone pointed out).
All directory handles must be closed prior to deletion.
(leaving handles open can cause Permission denied errors)
The directory must be empty. rmdir() only deletes the directory, not the files inside. So it can't do its job if there is still stuff inside.
To fix number 2, it is extremely simple. If you are using something like this:
$hd = opendir($mydir);
Close your handle prior to deletion:
closedir($hd);
For number 3, what you want to do is called a recursive delete. You can use the following function to achieve this:
function force_rmdir($path) {
if (!file_exists($path)) return false;
if (is_file($path) || is_link($path)) {
return unlink($path);
}
if (is_dir($path)) {
$path = rtrim($path, DIR_SEPARATOR) . DIR_SEPARATOR;
$result = true;
$dir = new DirectoryIterator($path);
foreach ($dir as $file) {
if (!$file->isDot()) {
$result &= force_rmdir($path . $file->getFilename(), false, $sizeErased);
}
}
$result &= rmdir($path);
return $result;
}
}
It looks like you need access rights on the folder you're trying to edit.
To change this:
chmod ug+rw /home/free/howto.cz/m/mousemys/root/www/g_test/
or maybe you'll need to do
sudo chmod ug+rw /home/free/howto.cz/m/mousemys/root/www/g_test/
Make sure that this is what you want to do and that your application is secure. Don't give write rights to any application since it could lead to security issues.
The webserver requires write access to the folder you're trying to delete. You can provide this with:
chgrp -R www-data g_test/uploads
chmod g+w g_test/uploads
where www-data is the user that the webserver runs under (may be apache or some variation depending on your OS and server installation). After this you can run rmdir (or rm -r if the directory isn't empty).
Also, keep in mind that giving the web server the ability to write to a directory posses security problems. In certain situations, this could allow a malicious user to run arbitrary code (i.e. take over your machine), or modify your website (i.e. server spyware).
For these reasons, you should only give dirs write perms that:
absolutely need them
don't contain source code
are outside the dir containing scripts
owned by the server
In this setup on a production machine, you could set up a separate directory just for this type of file, that only Apache can write to. If you have to deploy files to this directory, use sudo or the root account to do so to limit the accounts that have access.
For a more complete description of what I mean, have a look at the security tips section in the Apache documentation.