0

I was wondering if anyone know why the code after the header(Content-disposition: ...) will not run? It writes and downloads the file, but it will not run the unlink() line...

This code is within a few other if statements originally.

Here is the code:

$form1Array = array($_POST["namn"], $_POST["stad"]);
$form1String = serialize($form1Array);
$form1Fil = $_POST["namn"].".txt";
$midMappe = "midlertidig\\";
$fo_form1Fil = fopen($midMappe.$form1Fil, "w");
//
if (fwrite($fo_form1Fil, $form1String)) {
    ignore_user_abort(true);
    //
    header("Content-type: text/plain");
    header("Content-disposition: attachment; filename=".$form1Fil);
    //
    unlink($midMappe.$form1Fil);
    } else {
       echo "Could not save the file for download.";    
    }

Thank you. :)

ravo10
  • 895
  • 9
  • 18
  • 1
    I bet it runs the line, but it's unable to unlink the file. Check your error log (and make sure warnings are actually written to it) – Maxim Krizhanovsky Nov 10 '13 at 12:10
  • 1
    You have an open `fopen` handle on the file, so it naturally can’t be unlinked at this point … D’oh! – CBroe Nov 10 '13 at 12:35
  • @CBroe: Haha, I did not know you needed to close it with `fclose()` before you could `unlink()` on it. Everything now works fine when I `fclose()` it first. Thank you. :) – ravo10 Nov 10 '13 at 12:46

2 Answers2

1

The code will be correctly executed and as someone pointed out in the comments, it is very likely that the problem is in the unlink() function. I recommend you to do a quick debug and see what unlink() returns. More in particular, see if it return false (it will if it fails to unlink the file).

Here an example of what i mean

jnardiello
  • 699
  • 8
  • 15
0

I figured it out with the help of 'CBroe', thank you.

I also added a connection_abort() line which I found out about here.

Here is the updated code:

$form1Array = array($_POST["namn"], $_POST["stad"]);
$form1String = serialize($form1Array);
$form1Fil = $_POST["namn"].".txt";
$midMappe = "midlertidig\\";
$fo_form1Fil = fopen($midMappe.$form1Fil, "w");
//
if (fwrite($fo_form1Fil, $form1String)) {
    fclose($fo_form1Fil); // ** Here is the updated/added line 1 **
    //
    ignore_user_abort(true);
    //
    header("Content-type: text/plain");
    header("Content-disposition: attachment; filename=".$form1Fil);
    //
    if (connection_abort()) { // ** Here is the updated/added line 2 **
        unlink($midMappe.$form1Fil);
    } else {
        unlink($midMappe.$form1Fil);
    }
    } else {
       echo "Could not save the file for download.";    
    }
Community
  • 1
  • 1
ravo10
  • 895
  • 9
  • 18