ILOveCoDe
ILOveCoDe

Reputation: 45

Redirect to another page in PHP after performing form action on same page

So I have my page as downloads.php and that is where my form is located as well as it's form action. The downloads.php's contents are as shown below

<form method="POST" action="">
<td><button type="submit" name="download" value="<?php echo $g['filename'];?> ">Download</button></td>
</form>
<?php
    if( isset($_POST['download']) ){
        $file = $_POST["download"];


        $sql = "UPDATE files SET downloads=1+downloads WHERE filename ='$file'";
        $conn->query($sql);


    //I want to redirect users to portal after updating my database
        header("Location: portal.php");

    }
?>

I've used header though I'm absolutely puzzled why it doesn't work.

Upvotes: 1

Views: 51

Answers (2)

ILOveCoDe
ILOveCoDe

Reputation: 45

I found a quick way to do it with javascript and that is


    <?php
        if( isset($_POST['download']) ){
            $file = $_POST["download"];
            $sql = "UPDATE files SET download=1+download WHERE filename ='$file'";
            $conn->query($sql);
    ?>
    <script>
    var str1 = 'https://www.example.com/portal.php';
    window.location.href = str1;
    </script>

    <?php
    }
    ?>

Upvotes: 1

Grant C.
Grant C.

Reputation: 356

Note in the PHP docs for header() that header() must be executed before any HTML is output. Try putting all your PHP code at the top of the document and it should work

Upvotes: 2

Related Questions