Bootstrap FreeKB - PHP - Create a file using fopen
PHP - Create a file using fopen

Updated:   |  PHP articles

The fopen function can be used to create a file in PHP. PHP is typically being run as the apache or www-data user, thus the apache or www-data user will need to have the write permission to the directory. For example, let's say you want to create /var/www/html/foo.php file on a Linux system. In this example, the www-data user has rwx (read, write, execute) permissions to the /var/www/html directory, so the www-data user should be able to create the foo.php file in the /var/www/html directory.

~]$ ls -ld /var/www/html
drwxr-xr-x. 2 www-data  www-data  6 Feb  5 07:59 /var/www/html

 

Here is how you would create /var/www/html/foo.php using fopen.

fopen("/var/www/html/foo.php", "w");

 

It's probably also a good idea to use the file_exists function to first ensure the file does not exist before attempting to create the file.

if (!file_exists("/var/www/html/foo.php")) {
  fopen("/var/www/html/foo.php", "w");
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 557779 in the box below so that we can be sure you are a human.