开发者

Writing data to file adds ^M at end of line

开发者 https://www.devze.com 2023-02-06 16:02 出处:网络
Using PHP i\'m writing content to a .htaccess file using fwrite, this all works correctly but when i view the .htaccess in Vim afterwards it displays ^M at the end of each line that has been added. Th

Using PHP i'm writing content to a .htaccess file using fwrite, this all works correctly but when i view the .htaccess in Vim afterwards it displays ^M at the end of each line that has been added. This doesn't seem to cause any issues but i'm unsure quite whats happening to cause this and whether it can be prevented?

this is the 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,$replaceWi开发者_如何转开发th,$contents);
    $filename = SITE_ROOT.'/public_html/.htaccess';
    $handle = fopen($filename,'w');
    if (fwrite($handle, $newcontents) === FALSE) {
    }
    fclose($handle);

When i check in Vim afterwards i will see something like this:

#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

The server is running CentOS and i'm working locally on a Mac


Your newlines are incoming as \r\n, not as \n.

Before writing to the file, you should replace the invalid input:

$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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号