使用php写入.htaccess



我正在尝试使用一个简单的php脚本向.htaccess文件添加行。我知道这很危险——这是为了开发、测试和学习,而不是为了生产。我想添加这样的页面重定向行。htaccess:

Redirect /url1.html https://exampleredirecturl.com/page1
Redirect /url2.html https://exampleredirecturl.com/page2

我使用的脚本是:

<?php
if( $_SERVER["REQUEST_METHOD"] === "POST" ){
$text = trim($_POST['all_redirects']);
if($text == ""){die("invalid input");}
$textAr = explode("n", $text);
$textAr = array_filter($textAr, 'trim'); 
$file = fopen('.htaccess', 'a') or die('Fail to open .htaccess file');
foreach ($textAr as $line) {
echo $line."<br>";
fwrite($file, $line);
} 
fwrite($file, "n");
fclose($file);
}
?>

<form action="" method="POST">
<textarea name="all_redirects" rows="35" cols="150"></textarea>
<br><br>
<input type="submit" name="" value="Save to htaccess">
</form>

问题是,当我运行脚本并输入重定向行列表(如上所述(并保存到htaccess时,在代码编辑器,但无法按预期工作,因为换行符似乎有问题。如果我手动编辑文件,并在每行后点击回车并保存,那么一切都很好。有什么关于发生了什么的建议吗?我应该怎么做才能解决它?非常感谢。

好的-这就是答案-感谢JustBaron提出了解决方案,Álvaro González也为我研究了它:

<?php
if( $_SERVER["REQUEST_METHOD"] === "POST" ){
$text = trim($_POST['all_redirects']);
if($text == ""){die("invalid input");}
$textAr = explode("n", $text);
$textAr = array_filter($textAr, 'trim'); 
$file = fopen('.htaccess', 'a') or die('Fail to open .htaccess file');
foreach ($textAr as $line) {
echo $line.PHP_EOL;
fwrite($file, $line.PHP_EOL);
} 
fwrite($file, "n");
fclose($file);
}
?>
<form action="" method="POST">
<textarea name="all_redirects" rows="35" cols="150"></textarea>
<br><br>
<input type="submit" name="" value="Save to htaccess">
</form>

我不知道Apache对任何EOL样式都有偏好。但您的脚本根本没有插入行尾,只是在文件末尾插入一个尾随的行尾:

foreach ($textAr as $line) {
fwrite($file, $line);
} 
fwrite($file, "n"); // <--- Just this one!

假设explode()保留分隔符。事实并非如此:

var_dump(explode("n", "AnBnCn"));
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[2]=>
string(1) "C"
[3]=>
string(0) ""
}

更新:我错过了"在代码编辑器中查看时显示正常"部分。这可能表明您的输入包含Windows EOL("\r\n"(,而您剥离了("\n"(,因此您最终使用的是传统的MacOS风格("\r"(。也许Apache不喜欢那些。:-?

最新更新