Write to Directory using PHP: Is this a permissions problem?

Asked
Active3 hr before
Viewed126 times

9 Answers

directoryusing
90%

The user php runs as actually doesn't have permission to write files and therefor not to create directories. Thank you for the reduced version, it looks good. :) – Abs Mar 24 '09 at 17:49 ,I have put this script on a new server however the image never gets saved. The permission of the folder it saves to is 755 but it does not own it. Last time, I think I fixed the issue by changing the directory owner to apache as this is what PHP runs as. I can not do the same again because I am not root., Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,Firstly., Is there another fix? Secondly, If I could change the owner of the directory like last time will this fix the issue?

BTW. you can reduce following code:

fopen($newfile.
   '.jpg', 'wb');
fwrite($handle, $GLOBALS['HTTP_RAW_POST_DATA']);
fclose($handle);
print $newfile.
'.jpg';

to:

file_put_contents($newfile.
   '.jpg',
   file_get_contents('php://input',
      FILE_BINARY),
   FILE_BINARY)
load more v
88%

2 I am not sure what problem you are trying to solve? If you can access the directory where file is located and have execute permission in it you can write to files and directories with those permissions. – Karlson Apr 4 '12 at 15:19 ,Once you know which is the user executing the scripts, and which's the owner of the files you mention, it is up to you to set appropriate permissions. Keep in mind that giving write access (even read) to every user on your system can be potentially disastrous.,It is better to be more specific and give permissions to just you and Apache. Change the group of your files to give the full control on your files to the web server. To do this, change the owner recursively:, 1 If you see documentation suggesting that you use 666 or 777 in relation to web files, you should probably ignore it unless there is a good reason explained. It's usually something written by someone who couldn't figure out how to set up the right permissions, and gave up and gave everyone read or write access to the files. – jsbillings Apr 4 '12 at 19:44

To check it out, try:

ps aux | grep - E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep - v root | head - 1 | cut - d\ - f1
load more v
72%

My PHP script writes to a file so that it can create a jpg image.,I have put this script on a new server however the image never gets saved. The permission of the folder it saves to is 755 but it does not own it. Last time, I think I fixed the issue by changing the directory owner to apache as this is what PHP runs as. I can not do the same again because I am not root., Piping email to php script I've been searching for an answer for 2 days now and have found so much, but still can't get this to work. I have a WHM server with a cPanel account. I have cre... ramon.lueilwitz · saved on 4 months ago ,I've been searching for an answer for 2 days now and have found so much, but still can't get this to work. I have a WHM server with a cPanel account. I have cre...

My PHP script writes to a file so that it can create a jpg image.

fwrite($handle, $GLOBALS['HTTP_RAW_POST_DATA']);
fclose($handle);
print $newfile.
'.jpg';
load more v
65%

Attempts to change the mode of the specified file to that given in permissions. , Note that permissions is not automatically assumed to be an octal value, so to ensure the expected operation, you need to prefix permissions with a zero (0). Strings such as "g+w" will not work properly. , The current user is the user under which PHP runs. It is probably not the same user you use for normal shell or FTP access. The mode can be changed only by user who owns the file on most systems. ,fileperms() - Gets file permissions

load more v
75%

and you (and the rest of the neighborhood!) should have write access so you can write/delete anything in your files and images directory via shell/FTP again. Modify the command as needed. ,Take care doing this though. These are the kind of tasks where it pays to practice them on your test instance first - you do have a test instance right?,I guess I should just ask this question directly: Is the problem that Drupal is having modifying the files and directories it creates on the webserver related to suEXE or suPHP? What do I need to do to eliminate the numerous error messages I receive each time a change is made? ,With these techniques you should be able to get the webserver to do anything the Unix shell can do. Some hosts however limit your ability to use shell-level commands like this, in which case you must approach them to ask for the appropriate fix.

Use a drupal PHP-format page (eg just a php code snippet) to run

`chmod -R a+w sites/default/files`;

Important: this code should only be used if you remember to delete it immediately after use. As above, its use may put your site into an insecure state.

file_fix_directory(dirname(__FILE__));

function file_fix_directory($dir, $nomask = array('.', '..')) {
  if (is_dir($dir)) {
     // Try to make each directory world writable.
     if (@chmod($dir, 0777)) {
       echo "<p>Made writable: " . $dir . "</p>";
     }
  }
  if (is_dir($dir) && $handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
      if (!in_array($file, $nomask) && $file[0] != '.') {
        if (is_dir("$dir/$file")) {
          // Recurse into subdirectories
          file_fix_directory("$dir/$file", $nomask);
        }
        else {
          $filename = "$dir/$file";
            // Try to make each file world writable.
            if (@chmod($filename, 0666)) {
              echo "<p>Made writable: " . $filename . "</p>";
            }
        }
      }
    }

    closedir($handle);
  }

}
load more v
40%

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.,How to execute PHP code using command line ?,How to remove the first character of string in PHP?,Step 3: This line restores the umask to what it was originally.  

  • Example 1: 
     
For example, a mask 0022 means that you don 't want 
group and others modify the file.

default 0666 rw - .rw - .rw -
   umask 0022-- - . - w - . - w -
   Final 0644 rw - .r--.r--

That means any file from now will have 0644 permissions.
load more v
22%

there is a strong likelihood that you have problems with the permissions and/or ownership of the files and folders on your Mautic instance.,Problems with permissions and ownership generally occur because:,File ownership and permissions,If your file and folder permissions are incorrect, you can run the following commands to reset them:

If you experience errors like the following:

mautic.WARNING: PHP Warning - require(/mautic/var / cache / prod / doctrine / orm / Proxies / __CG__MauticCategoryBundleEntityCategory.php): failed to open stream: No such file or directory - in file / mautic / vendor / doctrine / common / lib / Doctrine / Common / Proxy / AbstractProxyFactory.php - at line 209
load more v
60%

Permission errors are usually associated with Linux and macOS installations. In these kinds of systems, files and directories have three operation privileges available: read (r), write (w) and execute (x). A system user can perform different operations depending on their operation privileges and the groups this user belongs to. For more information about permissions, see this guide. A permission issue occurs when an application (or system user) is performing an unauthorized operation in the filesystem.,Temporarily change the permissions of the destination folder or file, upload the files, and then restore the file or folder to its original state. To do this, follow the steps below:,You must edit the file with superuser privileges. Execute the command in the file you want to edit (replace TARGETFILE with the proper path). In this example we will use nano as the editor:,If the bitnami system user wants to edit a file, it must obtain super-user privileges. To improve user-experience, the bitnami user can have ownership (with write privileges) of certain folders (for example, WordPress htdocs folder).

Detecting permission issues is quite straightforward. It usually implies an application crashing or showing errors (either in the logs or in the standard output) such as the following:

Error: [...] open
for write: permission denied

Or:

[...](errno: 13 * Permission denied)

Or:

Error: EACCES: permission denied[...]

If you see an error like this when uploading a file:

[...] permission denied

Execute the command in the target folder where you want to upload the file to (replace TARGETFOLDER with the proper path):

  $ sudo stat TARGETFOLDER

If you want to upload a file, replace the TARGETFOLDER placeholder with the full path to the file. The following is an example:

  $ sudo stat / opt / bitnami / apps / wordpress / htdocs / wp - config.php

You will see an output like this:

  Access: (0775 / drwxrwxr - x) Uid: (1000 / daemon) Gid: (1 / daemon)

Change the owner of the folder or file to bitnami (remember to replace the TARGETFOLDER placeholder with the proper path):

  $ sudo chown bitnami TARGETFOLDER
  $ sudo chmod + w TARGETFOLDER

You should now be able to upload files to the folder or replace the file. When you are finished, restore the original permissions. For the case above, the commands are as follows:

  $ sudo chown daemon: daemon TARGETFOLDER
  $ sudo chmod 0775 TARGETFOLDER

If you are getting an error like this when trying to edit a file inside your SSH session:

[...] permission denied

You must edit the file with superuser privileges. Execute the command in the file you want to edit (replace TARGETFILE with the proper path). In this example we will use nano as the editor:

$ sudo nano TARGETFILE

If your application crashes or shows an error like the following:

[...] permission denied

Check the command history for permission change operations:

  $ history

Check the output. Examples of this kind of operation are as follows:

  $ sudo chown bitnami: bitnami - R / opt / bitnami / apps / magento / htdocs /
     $ sudo chmod 777 - R / opt / bitnami / apps / magento / htdocs /

Look at the original application configuration (you can launch a new fresh cloud instance of the application). Check the writable folders and check that the permissions are correct. The following is an example of Magento’s writable folders:

  $ ls / opt / bitnami / apps / magento / htdocs /
     var / cache / -la
  total 76
  drwxrwsrwx 19 bitnami bitnami 4096 Oct 26 12: 17.
  drwxrwsrwx 7 bitnami bitnami 4096 Oct 26 15: 28..
  drwxrwxrwx 2 bitnami bitnami 4096 Oct 26 12: 17 mage--0
  drwxrwxrwx 2 bitnami bitnami 4096 Oct 26 15: 15 mage--1
  drwxrwxrwx 2 bitnami bitnami 4096 Oct 26 12: 19 mage--2
  drwxrwxrwx 2 bitnami bitnami 4096 Oct 26 12: 17 mage--3
  drwxrwxrwx 2 bitnami bitnami 4096 Oct 26 12: 17 mage--4
  drwxrwxrwx 2 bitnami bitnami 4096 Oct 26 12: 19 mage--5
  drwxrwxrwx 2 bitnami bitnami 4096 Oct 26 15: 14 mage--6

  $ ls / opt / bitnami / apps / magento / htdocs /
     var / -la
  total 44
  drwxrwsrwx 7 bitnami bitnami 4096 Oct 26 15: 28.
  drwxrwxrwx 13 bitnami bitnami 4096 Oct 18 13: 45..
  drwxrwx-- * 2 daemon bitnami 4096 Oct 26 15: 14 backups
  drwxrwsrwx 19 bitnami bitnami 4096 Oct 26 12: 17 cache
  drwxrwsrwx 3 bitnami bitnami 4096 Oct 18 13: 47 composer_home -
     rwxrwxrwx 1 bitnami bitnami 152 Oct 18 13: 21.htaccess
  drwxrwsrwx 2 bitnami bitnami 4096 Oct 26 12: 16 log
  drwxrwsrwx 4 bitnami bitnami 4096 Oct 26 12: 17 page_cache -
     rw - rw - r - * 1 daemon bitnami 6783 Oct 26 15: 28.setup_cronjob_status -
     rwxrwxrwx 1 bitnami bitnami 148 Oct 26 15: 28.update_cronjob_status

If the files' permissions are wrong, use the chmod or chown commands to restore them to their initial state. Following the example above, do the following:

  $ sudo chown daemon: daemon - R / opt / bitnami / apps / magento / htdocs /
     var / opt / bitnami / apps / magento / htdocs /
     var / cache

If your stack uses MySQL, check and reset the permissions of the MySQL data directory:

  $ sudo chown mysql: root - R / opt / bitnami / mysql / data

If your stack uses MariaDB, check and reset the permissions of the MariaDB data directory:

  $ sudo chown mysql: root - R / opt / bitnami / mariadb / data

If your stack uses Apache, reset the permissions of the Apache directory:

  $ cd / opt / bitnami
  $ sudo cp - rp. / apache2 {
     , .back
  }
  $ sudo chown root: root - R. / apache2
  $ sudo chmod + x. / apache2 / bin
  /*
    $ sudo chmod +x ./apache2/scripts/ctl.sh
    $ sudo chown bitnami:root -R ./apache2/conf
    $ sudo chown root:root ...

If you are trying to execute a command inside your stack and you get an error like this:

[...] permission denied

Load the application environment by executing the following command. Replace APPNAME with the name of your application:

  $ sudo / opt / bitnami / use_APPNAME
load more v
48%

For example, if you create a new file for writing, PHP automatically grants the read and write permissions.,Use the chmod() function to set permissions for a file.,File permissions specify what a user can do with a file, e.g., reading, writing, or executing it. Notice that PHP automatically grants appropriate permissions behind the scenes.,To change the file permission or mode, you use the chmod() function:

Let’s take a look at the following example:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   } < ? php

$filename = 'readme.txt';

$functions = [
   'is_readable',
   'is_writable',
   'is_executable'
];

foreach($functions as $f) {
   echo $f($filename) ? 'The file '.$filename.$f : '';
}
Code language: HTML, XML(xml)
load more v

Other "directory-using" queries related to "Write to Directory using PHP: Is this a permissions problem?"