Reputation: 103
I have simple script who writing data to the text file from MySQL and drop the file to download instant and i have few post parameters in my form select inputs, so if i change something and press submit button to sort my data and write into file, i get file with old data, which was before, so the main problem is if i wanna get good info after i change my filter i need do always two submits and second submit gives me good file with last info. How i can prevent this problem?
public function all()
{
$this->load->helper('file');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="orders_all.txt"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: '.filesize('./assets/downloads/orders_all.txt'));
$data = array(
'customer_id' => $this->input->post('customer_id', TRUE), // Params from select inputs
'product_id' => $this->input->post('product_id', TRUE),
'state' => $this->input->post('state', TRUE),
'date' => $this->input->post('date', TRUE)
);
$result = $this->orders_model->get_orders_by_filter($data);
$str = '';
foreach ($result as $row)
{
$str .= $row['customer_title'] . ';' . $row['product_title'] . ';' . $row['product_code'] . ';' . $row['quantity'] . ';' . $row['created_at']."\r\n";
}
if (write_file('./assets/downloads/orders_all.txt', $str))
{
readfile('./assets/downloads/orders_all.txt');
}
}
Upvotes: 0
Views: 846
Reputation: 17710
Your content-length
will be wrong, as it's reading a file that's not there.
If you are only writing the file for someone to download, then skip that step all together (it will also cause problems if two people call the script at the same time!):
Instead you can do:
header('Content-Length: ' . strlen($str));
echo $str;
i.e. move the content length header to after you calculate the string, and only send the string without writing the file.
If you must write the file then just move the header into the "if" at the bottom
if (write_file('./assets/downloads/orders_all.txt', $str))
{
header('Content-Length: '.filesize('./assets/downloads/orders_all.txt'));
readfile('./assets/downloads/orders_all.txt');
}
Upvotes: 3