简体   繁体   中英

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.

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

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
    }
    ?>

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