2

.htaccessPHPを使用して、を使用してファイルにコンテンツを書き込んでいますfwrite。これはすべて正しく機能しますが、.htaccess後でVimで表示すると、追加された各行の最後に^Mが表示されます。これは問題を引き起こさないようですが、これを引き起こすために何が起こっているのか、そしてそれを防ぐことができるかどうかはよくわかりませんか?

これは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 に答える