【问题标题】:How can I make .htaccess file by PHP? If not found .htaccess file in my directory [duplicate]如何通过 PHP 制作 .htaccess 文件?如果在我的目录中找不到 .htaccess 文件 [重复]
【发布时间】:2017-04-08 15:42:54
【问题描述】:

实际上我已经创建了一个需要 .htaccess 文件的 PHP 脚本。但问题是:当我在 Ipage 服务器上的脚本时,该服务器不会自动上传 .htaccess 文件。

虽然我可以通过“创建文件”按钮从服务器创建 .htaccess 文件。在这种情况下,我想要:如果在我的目录中找不到 .htaccess 文件,我的脚本将自动创建 .htaccess 文件。


我的 .htaccess 文件的代码是

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

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

【问题讨论】:

  • 你使用的脚本/代码是?
  • @SuperDJ 使用了哪个脚本,这不是事实 - 我认为。我只是想知道。如果我运行 index.php 文件,它将检查 .htaccess 文件是否存在。如果不存在 - index.php 文件将自动创建新的 .htaccess 文件。
  • 它如何知道必须写入.htaccess 的内容?
  • 好的,我的 .htaccess 文件代码是:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
  • @SaifulIslam 将该代码放在问题中而不是在评论中

标签: php apache .htaccess mod-rewrite


【解决方案1】:

使用 PHP 的 bool file_exists ( string $filename ) 方法检查文件是否存在。如果不创建它并将您的内容写入其中(例如使用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);
}

【讨论】:

  • PHP5 函数file_put_contents 更简单、更短、更简洁。 PHP4 文件函数有其存在的权利,尤其是当它涉及缓冲读写时。但是这个问题不是这样的。
  • 是的,谢谢提示
猜你喜欢
  • 1970-01-01
  • 2016-02-28
  • 2013-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 2014-03-15
相关资源
最近更新 更多