2

使用PHP我正在.htaccess使用. 这似乎不会引起任何问题,但我不确定是什么导致了这种情况以及是否可以预防?fwrite.htaccess

这是PHP:

    $replaceWith = "#SO redirect_301\n".trim($_POST['redirect_301'])."\n#EO redirect_301";
    $filename = SITE_ROOT.'/public_html/.htaccess';
    $handle = fopen($filename,'r');
    $contents = fread($handle, filesize($filename));
    fclose($handle);
    if (preg_match('/#SO redirect_301(.*?)#EO redirect_301/si', $contents, $regs)){
    $result = $regs[0];
    }
    $newcontents = str_replace($result,$replaceWith,$contents);
    $filename = SITE_ROOT.'/public_html/.htaccess';
    $handle = fopen($filename,'w');
    if (fwrite($handle, $newcontents) === FALSE) {
    }
    fclose($handle);

当我之后签入 Vim 时,我会看到如下内容:

#SO redirect_301
Redirect 301 /from1 http://www.domain.com/to1^M
Redirect 301 /from2 http://www.domain.com/to2^M
Redirect 301 /from3 http://www.domain.com/to3
#EO redirect_301

服务器正在运行 CentOS,我在 Mac 上本地工作

4

1 回答 1

3

您的换行符是作为\r\n,而不是作为\n

在写入文件之前,您应该替换无效输入:

$input = trim($_POST['redirect_301']);
$input = preg_replace('/\r\n/', "\n", $input);    // DOS style newlines
$input = preg_replace('/\r/', "\n", $input);      // Mac newlines for nostalgia
于 2011-01-26T12:32:25.677 回答