0

I know the problem of "headers already sent" when trying to redirect after readfile. My question is how to handle such a situation so I get the website focus back or redirect to other website. I've created a simple example of what I'm dealing with. I've created a form and after the user gives a name and an email address, he can download a file, but after I can't do other things or redirect to other url. I can't find a way and think of a solution how should I rewrite my script and create things in proper way. How these download forms should be build in a right way?

<body>
<?php

$errors = [];
$name = "";
$email = "";

if (isset($_POST["submit"])) {
    $name = htmlspecialchars(stripslashes(trim($_POST["name"])));
    $email = htmlspecialchars(stripslashes(trim($_POST["email"])));

    if(!preg_match("/^[A-Za-z .'-]+$/", $name)){
      $errors[] = "Invalid name";
    }     
    if(!preg_match("/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/", $email)){
      $errors[] = "Invalid email";
    }

            if (empty($errors)) {                           

                    $file = "files/live.pdf";

                    header('Content-Description: File Transfer');
                    header('Content-Type: application/pdf');
                    header('Content-Disposition: attachment; filename=' . basename($file));
                    header('Content-Transfer-Encoding: binary');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                    header('Pragma: public');
                    header('Content-Length: ' . filesize($file));
                    ob_clean();
                    flush();                
                    readfile($file);

                    echo "ok"; 
                    header("Location: http://something.com");
            }

        }
?>  

<form method="POST">
    <label for="name">Name</label>
    <input type="text" id="name" name="name" value="<?= $name ?>" required><br>
    <label for="email">Email</label>
    <input type="email" id="email" name="email" value="<?= $email ?>" required><br>
    <button type="submit" name="submit">Download</button><br>
</form>

<p>
    <?php if (!empty($errors)) : ?>
            <ul>
                    <?php foreach ($errors as $error) : ?>
                            <li><?= $error ?></li>
                    <?php endforeach; ?>
            </ul>
    <?php endif; ?>
</p>            

</body>
felixRo
  • 187
  • 1
  • 1
  • 14
  • 1
    Does this answer your question? [How to download a file then redirect to another page in php?](https://stackoverflow.com/questions/15872534/how-to-download-a-file-then-redirect-to-another-page-in-php) – Mohammad Zare Moghadam Apr 09 '20 at 14:45
  • I'm not really sure. I managed the way with JS and settimeout function but not sure if it's reliable referring to the internet connection or the size of a downloaded file. – felixRo Apr 09 '20 at 19:07

0 Answers0