-3

Actually I have created a PHP Script where .htaccess file is required. But problem is that: When I my script on Ipage server, This server don't upload .htaccess file automatically.

Although I can create .htaccess file from server by "Create File" button. In this situation, I want: My script will create automatically .htaccess file, if not found .htaccess file in my directory.


My .htaccess file's code is

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
Saiful Islam
  • 332
  • 6
  • 15

1 Answers1

1

Use PHP's bool file_exists ( string $filename ) method to check if the files exists. If not create it and write your contents to it (e.g. using file_put_contents).

if(!file_exists('.htaccess'))
{
    $content = 'RewriteEngine On' . "\n"
    $content .= 'RewriteCond %{REQUEST_FILENAME} !-d' . "\n"
    $content .= 'RewriteCond %{REQUEST_FILENAME} !-f' . "\n"
    $content .= 'RewriteCond %{REQUEST_FILENAME} !-l' . "\n\n"
    $content .= 'RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]';

    file_put_contents('.htaccess', $content);
}
sigy
  • 2,408
  • 1
  • 24
  • 55
  • 2
    The PHP5 function [`file_put_contents`](https://secure.php.net/file_put_contents) is easier, shorter and cleaner. The PHP4 file functions have their existence right, especially when it's about buffered reading and writing. But this question is no such case. – Charlotte Dunois Nov 24 '16 at 11:31
  • yup, thanks for the hint – sigy Nov 24 '16 at 11:36