Search code examples
phplinuxfopenfwrite

Forcing fwrite to use \n instead of \r\n in PHP


I'm running PHP on a Linux server and I'm generating bash scripts for use on a Mac computer with PHP's fopen/fwrite. It's working fine except the line endings are being written as \r\n instead of just \n, which causes error when I try to run the script on the Mac.

How can I force fwrite to use \n instead of \r\n for line endings? I've tried utf8_encoding my text and forcing binary mode but I can't seem to figure it out!

   $scriptFile = "/path/to/my/script.sh";
   $fh = fopen($scriptFile, 'w');
   fwrite($fh, "$script");
   fclose($fh);

$script is the content from a text field in mysql, and looks a bit like this, typically:

   # comment
   echo "numphotos 1"

   # comment
   /opt/local/bin/gphoto2 --capture-image-and-download -F 1 

   # comment
   echo "696969"

Solution

  • Somewhere in your code, you're writing the line endings yourself, because fwrite() doesn't put them in for you. Instead of writing "\r" or "\n" or "\r\n", change the code to use PHP_EOL instead... this will write the appropriate line endings for the operating system on which the PHP script is running.