简体   繁体   中英

Strange error regarding Warning: Cannot modify header information - headers already sent by when there is no white space PHP

I am trying to download CSV file using Header function but due to some reasons it is not downloading in browser.

Error is:

Warning: Cannot modify header information - headers already sent by (output started at /xxx/fruitapp/report-admin/common/header.php:156) in /xxx/fruitapp/report-admin/pages/createCSVdamage.php on line 434

My header.php file line 156 which error refers to have error is look like this:

<div class="container-fluid">
<div class="row-fluid">
<?php if($title[0] != 'reports' && $title[0] != 'damage_reports' && $title[0] != 'Byconsignee_reports' && $title[0] != 'Byhold_reports' && $title[0] != 'general_reports'){?>
<div class="span3" id="sidebar">
  <ul class="nav nav-list bs-docs-sidenav nav-collapse collapse">
    <?php if($title[0]=='dashboard'){?>
    <li class="active"><a href="index.php?select=dashboard"><i class="icon-chevron-right"></i>Dashboard</a></li>
    <?php }if($title[0]=='report_entry' || $title[0]=='add_report_entry' || $title[0]=='edit_report_entry'){?>
    <li><a href="index.php?select=report_entry"><i class="icon-chevron-right"></i>Manage Report Entry</a></li>
    <li><a href="index.php?select=add_report_entry"><i class="icon-chevron-right"></i>Add Report Entry</a></li>
    <?php }if($title[0]=='damage_entry' || $title[0]=='add_damage_entry' || $title[0]=='edit_damage_entry'){?>
    <li><a href="index.php?select=damage_entry"><i class="icon-chevron-right"></i>Manage Damage Entry</a></li>
    <li><a href="index.php?select=add_damage_entry"><i class="icon-chevron-right"></i>Add Damage Entry</a></li>
    <?php }if($title[0]=='edit'){?>
    <li><a href="index.php?select=edit"><i class="icon-chevron-right"></i>Manage Edit</a></li>
    <?php }if($title[0]=='search'){?>
    <li><a href="index.php?select=search"><i class="icon-chevron-right"></i>Manage Search</a></li>
    <?php }if($title[0]=='users' || $title[0]=='add_user' || $title[0]=='edit_user'){?>
    <li><a href="index.php?select=users"><i class="icon-chevron-right"></i>Manage User</a></li>
    <li><a href="index.php?select=add_user"><i class="icon-chevron-right"></i>Add Users</a></li>
    <?php }?>
  </ul>
</div>
<?php }?>

Apprently there is no white space in or even I tried using BOM as well but nothing is working.

Moreover, If i adds ob_start(); it only export empty file when the file on ftp is full of data.

Code that is present in the end of my file is - I am using this code to download it in browser.

if ((isset($_REQUEST['date_from']) && $_REQUEST['date_from'] != "") || (isset($_REQUEST['date_to']) && $_REQUEST['date_to'] != "")) {
    fputcsv($file, array(
        'Report Number',
        'Consignee',
        'Pallet ID',
        'Label/Mark',
        'Fruit/Variety',
        'Deck',
        'Type',
        'Damage Description',
        'Pieces Damage',
        'Category'
    ));
    $sql = mysql_query("SELECT * FROM damage") or die('Error In Query');
    while ($rows = mysql_fetch_object($sql)) {
        $sqaal = mysql_query("SELECT
                                                    damage_entry.report_ID,
                                                    damage_entry.consignee,
                                                    damage_entry.pallet_ID,
                                                    damage_entry.label,
                                                    damage_entry.variety,
                                                    CONCAT(damage_entry.hold,damage_entry.deck),
                                                    damage_entry.type,
                                                    damage_entry.damage_desc,
                                                    damage_entry.pieces,
                                                    damage_entry.category_code
                                                FROM
                                                    damage_entry
                                                WHERE
                                                    damage='" . $rows->damage_name . "'  " . $cond . "") or die(mysqli_error(self::get_Conn()));
        $a = mysql_num_rows($sqaal);
        if ($a > 0) {
            fwrite($file, $rows->damage_name);
            fwrite($file, "\r\n");
            $valuesArray = array();
            $as          = 0;
            $sd          = array();
            $gggg        = array();
            while ($row = mysql_fetch_assoc($sqaal)) {
                $array = array(
                    $row['report_ID'],
                    $row['consignee'],
                    $row['pallet_ID'],
                    $row['label'],
                    $row['variety'],
                    $row['CONCAT(damage_entry.hold,damage_entry.deck)'],
                    $row['type'],
                    $row['damage_desc'],
                    $row['pieces'],
                    //$objadminViewFunctions->getCategoryLetter($row['category_code'])
                );
                array_push($sd, $row['pieces']);
                array_push($gggg, $row['pallet_ID']);
                fputcsv($file, $array);
            }
            fwrite($file, "\r\n");
            fputcsv($file, array(
                "",
                "Sub Total",
                count($gggg),
                "",
                "",
                "",
                "",
                "",
                array_sum($sd),
                "",
                ""
            ));
            fwrite($file, "\r\n");
        }
    }
} else {
    fputcsv($file, array(
            'Report Number',
            'Consignee',
            'Pallet ID',
            'Label/Mark',
            'Fruit/Variety',
            'Deck',
            'Type',
            'Damage Description',
            'Pieces Damage',
            'Category'
        ));
    $sql = mysql_query("SELECT * FROM damage") or die('Error In Query');
    while ($rows = mysql_fetch_object($sql)) {
        $sqaal = mysql_query("SELECT
                                                    damage_entry.de_ID,
                                                    damage_entry.report_ID,
                                                    damage_entry.consignee,
                                                    damage_entry.pallet_ID,
                                                    damage_entry.label,
                                                    damage_entry.variety,
                                                    CONCAT(damage_entry.hold,damage_entry.deck),
                                                    damage_entry.type,
                                                    damage_entry.damage_desc,
                                                    damage_entry.pieces,
                                                    damage_entry.category_code
                                                FROM
                                                    damage_entry
                                                WHERE
                                                    damage='" . $rows->damage_name . "'") or die(mysqli_error(self::get_Conn()));
        $a = mysql_num_rows($sqaal);
        if ($a > 0) {
            fwrite($file, $rows->damage_name);
            fwrite($file, "\r\n");
            $valuesArray = array();
            $as          = 0;
            $sd          = array();
            $gggg        = array();
            while ($row = mysql_fetch_assoc($sqaal)) {
                $array = array(
                    $row['report_ID'],
                    $row['consignee'],
                    $row['pallet_ID'],
                    $row['label'],
                    $row['variety'],
                    $row['CONCAT(damage_entry.hold,damage_entry.deck)'],
                    $row['type'],
                    $row['damage_desc'],
                    $row['pieces'],
                    //$objadminViewFunctions->getCategoryLetter($row['category_code'])
                );
                array_push($sd, $row['pieces']);
                array_push($gggg, $row['pallet_ID']);
                fputcsv($file, $array);
            }
            fwrite($file, "\r\n");
            fputcsv($file, array(
                "",
                "Sub Total",
                count($gggg),
                "",
                "",
                "",
                "",
                "",
                array_sum($sd),
                "",
                ""
            ));
            fwrite($file, "\r\n");
        }
    }
}
fclose($file);
$filename = $FileName;
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ){
    case "pdf": $ctype="application/pdf"; break;
    case "exe": $ctype="application/octet-stream"; break;
    case "zip": $ctype="application/zip"; break;
    case "doc": $ctype="application/msword"; break;
    case "xls": $ctype="application/vnd.ms-excel"; break;
    case "csv": $ctype="text/csv"; break;
    case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
    case "gif": $ctype="image/gif"; break;
    case "png": $ctype="image/png"; break;
    case "jpeg":
    case "jpg": $ctype="image/jpg"; break;
    default: $ctype="application/force-download";
}
header("Content-Type: application/octet-stream");
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));

PS: I have also used hex editor to check for BOM in my code but all code is clean and cleared. Nothing is outputting in header nor it is case in my question as it was not related to echo statement before header function.

My problem is that it is not downloading in browser.

Your initial problem is that you are somehow calling header.php , which contains a bunch of html - NO output of any kind can be sent to the browser before the headers. The solution to that is to just call createCSVdamage.php directly.

Regarding your empty csv, you never actually send the csv data to the oputput stream. You can do that via readfile function after you set headers:

header("Content-Type: application/octet-stream");
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));

//send the data to the browser
readfile($filename);

To move the file you can use the rename and pathinfo functions after sendingh the data:

$fileData = pathinfo($filename);
$nameWithoutDirectory = $fileData['basename'];

rename($filename, 'some/directory/' . $nameWithoutDirectory);

Or alternatively just create the file in the correct directory in the first place!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM