i have a php script that generates a text file. the code is as follows. the text file is being is being created.

<?php
    session_start();
    /**
    * @author FreeUser
    * @copyright 2013
    */

    set_time_limit(0); // override the maximum execution time in php.ini file
    require_once 'includes/mysql_connect.php';
    require_once 'includes/functions.php';

    if ( isset( $_POST['btnProcess'] ) ) {
        $errors = array();

        if ( $_POST['txtStartDate'] == "" ) {
            $errors[] = 'Select the start date.';
        } else {
            $startDate = $_POST['txtStartDate'];
        }

        if ( $_POST['txtEndDate'] == "" ) {
            $errors[] = 'Select the end date.';
        } else {
            $endDate = $_POST['txtEndDate'];
        }

        if ( $_POST['authorityID'] == "" ) {
            $errors[] = 'Select the paying authority.';
        } else {
            $authorityID = (int)$_POST['authorityID'];
        }

        if ( empty( $errors ) ) {
            $sql = "SELECT policyNumber, ECNumber, totalContribution as premium FROM policydetails WHERE authorityID = {$authorityID} ";
            $sql .= "AND ( dateCreated >= '$startDate' AND dateCreated <= '{$endDate}' )";
            // $sql .= "AND dateCaptured BETWEEN '$startDate' AND '{$endDate}'";
            $result = mysql_query( $sql );
            $authority = getAuthorityName( $authorityID ); 
            $authorityCode = getAuthorityCode( $authorityID );
            $file = 'files/' . strtolower( $authorityCode ) . time() . '.txt';
            $handle = fopen( $file, 'w' );
            if ( !$handle ) {
                $errors[] = 'Could not create file for writing.';
            }
            $len = strlen( $authority ); // assign the lenght of $authority to $len
            if ( $len > 30 ) {
                $authority = substr( $authority, 0, 30 );  
            } elseif ( $len < 30 ) {
                $authority = str_pad( $authority, 30, " ", STR_PAD_RIGHT ); // pad white space to the right of $authority
            }
            $startDate = str_replace("-", "", $startDate );
            $endDate = str_replace("-", "", $endDate );
            $currentDate = date( "Y-m-d" );
            $newDate = str_replace("-", "", $currentDate );
            $header = 'HDR' . $authority . $newDate . "\n"; // build the header for the fileh
            fwrite( $handle, $header ); // append the header to the file
            $count = 0; // initialize $count to 0
            $amount = 0; // initialize $amount to 0
            // echo $sql . '<br />';
            while( $row = mysql_fetch_array( $result ) ) {
                if ( strlen( $row['ECNumber'] ) > 8 ) {
                    $ECNumber = substr( $$row['ECNumber'], 0, 8 );
                } else {
                    $ECNumber = str_pad( $row['ECNumber'], 8, " ", STR_PAD_RIGHT );
                }
                $string = 'DED' . $ECNumber . 'N' . 8008 . 81115;
                if ( strlen( $row['policyNumber'] ) < 12 ) { // policyNumber is less than 12 characters long
                    $policy = str_pad( $row['policyNumber'], 12, " ", STR_PAD_RIGHT ); // pad white space to the right of $row['policyNumber'] and assign to $policyNumber
                }
                $string .= $policy . $startDate . $endDate;
                $premium = str_pad( ( $row['premium'] * 100 ), 12, "0", STR_PAD_LEFT );
                $string .= $premium . "\n";
                $count++; // increment $count by 1
                $amount = $amount + $row['premium']; // increase $amount by policy's totalContribution
                fwrite( $handle, $string ); // write the row's data to the file
                // echo $policy . "<br />";
            }
            $numberRecords = str_pad( $count, 6, "0", STR_PAD_LEFT );
            $totalAmount = str_pad( ( $amount * 100 ) , 18, "0", STR_PAD_LEFT );
            $trailer = 'TRL' . $numberRecords . $totalAmount; // build the string for the trailer
            fwrite( $handle, $trailer ); // write the trailer to the end of the file
            fclose( $handle ); // close the file
            header( "Location: $file" );
            exit;
        }
    }
?>
<html>
    <head>  
        <title>Process EDI Sending</title>
        <style> 
            .error {
                color: #FF0000;
                font-weight: bold;   
            }

            h2 {
                font-family: Arial, Helvetica, sans-serif;
                font-size: x-large;
                color: blue;
                font-weight: bold;
            }
            h3 {
                font-family: Arial, Helvetica, sans-serif;
                font-weight: normal;  
                font-size: 18px;  
            }

            li {
                list-style: none;
                padding-top:5px;   
            }
        </style>
        <script type="text/javascript" src="js/jquery-1.5.2.min.js"></script>
        <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
        <script type="text/javascript" src="js/jquery-ui.js"></script>
        <link rel="stylesheet" type="text/css" media="screen" href="js/jquery-ui.css" />
        <script language="javascript">
            $(function() {
                $( ".datepicker" ).datepicker({
                    dateFormat : 'yy-mm-dd',
                    changeMonth : true,
                    changeYear : true,
                    yearRange: '-100y:c+nn',
                    maxDate: '1000d'
                });
            });
        </script>
        <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
    <h2>Process EDI Sending</h2>
        <?php
            if ( !isset( $_SESSION['loggedUserID'] ) ) {
                header( 'Location: login.php');
                exit;    
            }

            if ( isset( $errors )  && is_array( $errors ) ) {
                // there are form submission errors, which must be displayed
                echo '<ul>';
                foreach ( $errors as $warning ) {
                    echo "<li class='error'>$warning</li>";
                }
                echo '</ul>';
            }
        ?>
        <form method="post" action="">
            <table>
                <tr>
                    <td><b>Paying Authority:</b></td>
                    <td>
                        <select name="authorityID">
                            <option value="">Select Paying Authority</option>
                            <?php
                                $sql = "SELECT authorityID, payingAuthorityName AS authority FROM tblpayingauthorities WHERE EDI = ";
                                $sql .= "'yes' ORDER BY authority ASC";
                                $result = mysql_query( $sql );
                                while( $row = mysql_fetch_array( $result ) ) {
                                  if ( isset( $_POST['authorityID'] ) && ( $_POST['authorityID'] == $row['authorityID'] ) ) {
                                    $selectedAuthority = ' Selected ';
                                  } else {
                                    $selectedAuthority = '';
                                  }
                                  ?>
                                    <option value="<?php  echo $row['authorityID']; ?>"<?php echo $selectedAuthority; ?> ><?php echo $row['authority']; ?></option>
                                  <?php
                                }
                            ?>
                        </select>
                    </td>
                    <td><b>Start Date:</b></td>
                    <td><input type="text" class="datepicker" name="txtStartDate" value="<?php if ( isset( $_POST['txtStartDate'] ) ) echo $_POST['txtStartDate']; ?>"/></td>
                </tr>
                <tr>
                    <td><b>End Date:</b></td>
                    <td><input type="text" class="datepicker" name="txtEndDate" value="<?php if ( isset( $_POST['txtEndDate'] ) ) echo $_POST['txtEndDate']; ?>"/></td>
                </tr>  
                <tr>
                    <td colspan="4" align="right">
                        <input type="submit" value="Process EDI Sending" name="btnProcess" />  <a href="index.php">«Back</a>
                    </td>
                </tr>  
            </table>
        </form>
    </body>
</html>

the problem i want to enable the user to be able to download the generated text file. what changes do i need to make to my code to achieve this

Dani AI

Generated

Two simple options.

As pointed out, a direct URL to the new file works if the file is placed in a web‑accessible folder — the browser will open or download it depending on its settings. If you want the browser to prompt the user to download immediately after the script finishes (or if you keep generated files outside the web root for safety), stream the file from PHP and send a Content-Disposition header that forces download.

A minimal, safe pattern to stream a file:

$path = __DIR__ . '/files/' . $filename; // build server path, not user input

if (!is_file($path) || !is_readable($path)) {
    http_response_code(404);
    exit;
}

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));

if (ob_get_level()) { ob_end_clean(); }
readfile($path);
exit;

Troubleshooting & best practices:

  • Close the write handle (you already call fclose) before streaming.
  • Ensure the webserver user can read the file and the path is correct.
  • If you get "headers already sent", check included files for stray whitespace or a UTF‑8 BOM; remove closing PHP tags in includes or use output buffering (ob_start).
  • For very large files consider reading in chunks instead of readfile() to keep memory low.
  • If you choose redirect (header("Location: …")) the target must be web‑accessible; redirects do not force download reliably.

Also review a couple of logic issues in your processing code: the ECNumber line uses $$ (likely a typo) and your policy padding only assigns $policy inside the short‑length branch. Finally, the mysql_* API is deprecated — migrate to mysqli or PDO when convenient.

Recommended Answers

All 2 Replies

If the text file is publicly available, you could provide a direct download link to the user. Just turn the path into a valid URL.

how do i do that? want it to be downloaded just after the file has been processed

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.