Search code examples
phpwindowsshellline-endings

What is changing my line breaks?


I am trying to read some binary data from a command line tool with PHP on Windows. Initially the tool was git show, but I can reproduce the problem with type as well (to make sure there is no Git autocrlf happening).

I am not sure what is going on, but somewhere on the way the line endings seem to be converted. Observe...

On the command line:

# dir temp
18.01.2015  03:24             1.362 temp

In PHP:

$data = `type d:\\temp`;
echo strlen($data);                            // outputs "1302"
echo strlen(str_replace("\n", "\r\n", $data)); // outputs "1362"
echo strlen(file_get_contents('d:\\temp'));    // outputs "1362"

What is going on? How can I get the verbatim data?


Solution

  • The file_get_contents() will get you the verbatim data, binary safe. Avoid OS-specific things like type you used.

    Try using other methods instead of backticks, like passthru for example:

    ob_start();
    passthru("git command blah blah");
    $var = ob_get_clean();
    echo strlen($var);