Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryGenerators and Converters

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Converting Line Endings of Plain Text Files for Specific Operating Systems

In the not-distant past, it was imperative to pay attention to the line endings expected by various operating systems.

Linux and Unix use ASCII character 10 to indicate a plain text line ending.

Mac OS9 uses ASCII character 13. Max OS X uses ASCII character 10.

Windows uses the ASCII character pair 13 and 10,

Trying to view a plain text file on a Mac that had Windows line endings resulted in little black boxes for the unrecognized half of the line-ending pair. Vice versa, the Windows computer displayed the entire text file as one long line because it found only half of the line-ending pairs.

Uploading a script to a server could break the script if it had line endings different than what the server expected.

Nowadays, lots of software automatically converts line endings according to the operating system that will use or display the file. But not all do that.

The converter accompanying this article can be used for the few situations that don't automatically convert line endings of plain text files.

You are welcome to use the converter embedded in this article. Alternatively, you may download the source code and run it on your own website.

The converter:

  1. Accepts an uploaded file.
  2. Processes the file for line ending changes.
  3. Initiates a download of the converted file.

Neither the uploaded file nor the converted file are permanently stored on the server.

Here is the converter.

The converter is there for your use.

Convert only plain text files. Converting image files, Word files, or any other files that aren't composed only of plain text is likely to break the file.

When viewed in software that correctly displays plain text regardless which line ending characters are used, the file being converted will visually appear the same before and after conversion. Only the line ending characters change during conversion, and they are invisible.

If you prefer to download the source code and install it on your own web site, you're welcome to do so. Here it is.

<?php
/*
   Plain Text File Line Endings Converter
   Version 1.0
   November 17, 2018

   Will Bontrager Software LLC
   https://www.willmaster.com/
   Copyright 2018 Will Bontrager Software LLC
*/
if( isset($_POST['submitter']) )
{
    $type = $fname = $retfile = '';
    $lftype = isset($_POST['leconversion']) ? $_POST['leconversion'] : 'unix';
	$type = $_FILES['uploaded']['type'];
	$fname = $_FILES['uploaded']['name'];
    $retfile = file_get_contents($_FILES['uploaded']['tmp_name']);
    if( strlen($_FILES['uploaded']['error']) > 1 )
    {
        $type = 'text/plain';
        $fname = 'ErrorMessage.txt';
        $retfile = $UploadErrorMessage($_FILES['uploaded']['error']);
    }
    $retfile = strpos($retfile,"\n") ? str_replace("\r",'',$retfile) : str_replace("\n",'',$retfile);
    switch( $lftype )
    {
        case 'win' : $retfile = str_replace("\n","\r\n",$retfile); break;
        case 'os9' : $retfile = str_replace("\n","\r",$retfile);
    }
    header("Content-Type:application/octet-stream");
    header("Content-Disposition:attachment; filename=\"$fname\"");
    echo($retfile);
$retfile = str_replace("\r","[R]",$retfile);
$retfile = str_replace("\n","[N]",$retfile);
file_put_contents('LineEndingsConverter'.'-'.time().'-'.str_replace('/','_',$type).'.txt',$retfile);
    exit;
}

function UploadErrorMessage($num)
{
	switch($num)
	{
		case UPLOAD_ERR_OK         : /* 0 */ return "There is no error, the file uploaded with success."; /* 0, Introduced in PHP 4.2.0. */
		case UPLOAD_ERR_INI_SIZE   : /* 1 */ return "The uploaded file exceeds the upload_max_filesize directive in php.ini."; /* 1, Introduced in PHP 4.2.0. */
		case UPLOAD_ERR_FORM_SIZE  : /* 2 */ return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form."; /* 2, Introduced in PHP 4.2.0. */
		case UPLOAD_ERR_PARTIAL    : /* 3 */ return "The uploaded file was only partially uploaded."; /* 3, Introduced in PHP 4.2.0. */
		case UPLOAD_ERR_NO_FILE    : /* 4 */ return "No file was uploaded."; /* 4, Introduced in PHP 4.2.0. */
		case UPLOAD_ERR_NO_TMP_DIR : /* 6 */ return "Missing a temporary folder."; /* 6, Introduced in PHP 4.2.0. */
		case UPLOAD_ERR_CANT_WRITE : /* 7 */ return "Failed to write file to disk."; /* 7, Introduced in PHP 4.3.10 and PHP 5.0.3. */
		case UPLOAD_ERR_EXTENSION  : /* 8 */ return "A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help."; /* 8, Introduced in PHP 5.2.0. */
	}
	return "";
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Plain Text File Line Endings Converter</title>
<style type="text/css">
body { font-size:110%; font-family:sans-serif; margin:0; }
div > :first-child { margin-top:0; }
div > :last-child { margin-bottom:0; }
.nowrap { white-space:nowrap; }
input { font-size:1em; }
input[type="radio"] { margin:0 .15em 0 0; vertical-align:.15em;}
#content { max-width:6in; margin:0 auto; background-color:transparent; border:1px solid #ccc; border-radius:1em; padding:1em; }
</style>
</head>
<body><div id="content">
<h3>Plain Text File Line Endings Converter</h3>
<form method="post" enctype="multipart/form-data" action="<?php echo($_SERVER['PHP_SELF']); ?>">
<p>
Convert line endings to:<br>
<label class="nowrap"><input type="radio" name="leconversion" value="win">Windows</label> 
<label class="nowrap"><input type="radio" name="leconversion" value="unix">Unix/Linux</label> 
<label class="nowrap"><input type="radio" name="leconversion" value="unix">Mac OS&thinsp;X</label> 
<label class="nowrap"><input type="radio" name="leconversion" value="os9">Mac OS9</label>
</p>
<p>
<input type="file" name="uploaded">
</p>
<p>
<input type="submit" name="submitter" value="Upload and Process">
</p>
</form>
<p>
After processing, a download of the converted file is initiated.
</p>
</div>
</body>
</html>

Save it as LineEndingsConverter.php or other *.php file name you prefer and upload it. (No customization required.)

The plain text line endings converter can convert the line endings to the expected format of the most popular desktop computer operating systems.

(This article first appeared with an issue of the Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC