简体   繁体   English

如何在结帐页面后将用户重定向回 index.php?

[英]How to redirect user back to index.php after checkout page?

How do I prevent the user to return back to the payment page even after checking out?如何防止用户在结帐后返回支付页面? Currently, after user has checkout, and when I click on the browser back button, the user is still able to return back to the payment page with all info still on the form.目前,在用户结帐后,当我点击浏览器后退按钮时,用户仍然能够返回到付款页面,所有信息仍在表单上。 How do I redirect the user back to the main page such that after the user has checkout, and when they click on the back button, instead of going back to the payment page, they will be redirected back to the main page(index.php) instead?如何将用户重定向回主页,以便在用户结帐后,当他们点击后退按钮时,而不是返回支付页面,他们将被重定向回主页(index.php ) 反而?

Currently, under the saveOrderToTable function, I am calling the session array that store all the product user has purchased.目前,在 saveOrderToTable function 下,我调用 session 数组来存储用户购买的所有产品。 I am able to delete the array once the button has been submitted but not the value in the payment form.提交按钮后,我可以删除数组,但不能删除付款表单中的值。

My current payment page code:我当前的付款页面代码:

<html>
 <head>
    <title>PAYMENT PAGE</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/header_footer.css">
    <link rel="stylesheet" href="css/process_payment.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
    <script src="js/bootstrap.min.js"></script>   
</head>

<body>      
    <?php
        include "navbar.inc.php";
    ?>

    <article class="formvalidateOutput">
        <?php
        $key = 'qkwjdiw239&&jdafweihbrhnan&^%$ggdnawhd4njshjwuuO';
        // Constants for accessing our DB:
        define("DBHOST", ""); 
        define("DBNAME", ""); 
        define("DBUSER", ""); 
        define("DBPASS", "");  
        $custname = $custemail = $custnumber = $streetadd = $blknumber = $unitnumber = $zipcode = $deldate = $deltime = $ccname = $ccnumber = $expdate = $ccvnumber = $errorMsg = "";
        $success = true; 

        if (empty($_POST["custname"])) {
            $errorMsg .= "First name is required.<br>";     
            $success = false; 
        } else {
            $custname = sanitize_input($_POST["custname"]); 
            if (!preg_match("/^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/", $custname)) {
                $errorMsg .= "Please enter a proper first name.<br>";     
                $success = false; 
            } else {
                $custname = sanitize_input($_POST["custname"]);    
            }
        }

        if (empty($_POST["custemail"])) {     
            $errorMsg .= "Email is required.<br>";     
            $success = false; 
        } else {     
            $custemail = sanitize_input($_POST["custemail"]); // Additional check to make sure e-mail address is well-formed.     
            if (!filter_var($custemail, FILTER_VALIDATE_EMAIL)) {         
                $errorMsg .= "Invalid email format.<br>";         
                $success = false;       
            }
        } 

        if (empty($_POST["custnumber"])) {
            $errorMsg .= "Contact Number is required.<br>";     
            $success = false; 
        } else {
            $custnumber = sanitize_input($_POST["custnumber"]); 
            if (!preg_match("/^([0-9]{8})$/", $custnumber)) {
                $errorMsg .= "Please enter a valid contact number.<br>";         
                $success = false; 
            } else {
                $custnumber = sanitize_input($_POST["custnumber"]); 
            }
        }

        if (empty($_POST["streetadd"])) {
            $errorMsg .= "Address is required.<br>";     
            $success = false; 
        } else {
            $streetadd = sanitize_input($_POST["streetadd"]); 
            if (!preg_match("/^([A-Za-z0-9\.\-\s\,])+$/", $streetadd)) {
                $errorMsg .= "Please enter a valid address.<br>";         
                $success = false; 
            } else {
                $streetadd = sanitize_input($_POST["streetadd"]); 
            }
        }

        if (empty($_POST["blknumber"])) {
            $errorMsg .= "Blk number is required.<br>";     
            $success = false; 
        } else {
            $blknumber = sanitize_input($_POST["blknumber"]); 
            if (!preg_match("/^([0-9]{3})$/", $blknumber)) {
                $errorMsg .= "Please enter a valid blk number.<br>";         
                $success = false; 
            } else {
                $blknumber = sanitize_input($_POST["blknumber"]);  
            }
        }

        if (empty($_POST["unitnumber"])) {
            $errorMsg .= "Unit number is required.<br>";     
            $success = false; 
        } else {
            $unitnumber = sanitize_input($_POST["unitnumber"]); 
            if (!preg_match("/^([0-9]{2}\-[0-9]{3})$/", $unitnumber)) {
                $errorMsg .= "Please enter a valid unit number.<br>";         
                $success = false; 
            } else {
                $unitnumber = sanitize_input($_POST["unitnumber"]);
            }
        }

        if (empty($_POST["zipcode"])) {
            $errorMsg .= "Zipcode is required.<br>";     
            $success = false; 
        } else {
            $zipcode = sanitize_input($_POST["zipcode"]); 
            if (!preg_match("/^([0-9]{6})$/", $zipcode)) {
                $errorMsg .= "Please enter a valid zipcode.<br>";         
                $success = false; 
            } else {
                $zipcode = sanitize_input($_POST["zipcode"]);
            }
        }

        if (empty($_POST["deldate"])) {
            $errorMsg .= "Date is required.<br>";     
            $success = false; 
        } else {
            $deldate = sanitize_input($_POST["deldate"]); 
        }

        if ($_POST["deltime"] == "0") {
            $errorMsg .= "Please select a time.<br>";     
            $success = false; 
        } else {
            $deltime = $_POST["deltime"]; 
        }

        if (empty($_POST["ccname"])) {
            $errorMsg .= "Credit card name is required.<br>";     
            $success = false; 
        } else {
            $ccname = sanitize_input($_POST["ccname"]); 
            if (!preg_match("/^[a-zA-Z]+(([a-zA-Z ])?[a-zA-Z]*)*$/", $ccname)) {
                $errorMsg .= "Please enter a valid credit card name.<br>";     
                $success = false; 
            } else {
                $ccname = sanitize_input($_POST["ccname"]);    
            }
        }

        if (empty($_POST["ccnumber"])) {
            $errorMsg .= "Credit Card Number is required.<br>";     
            $success = false; 
        } else {
            $ccnumber = sanitize_input($_POST["ccnumber"]); 
            if (!preg_match("/^([0-9]{16})$/", $ccnumber)) {
                $errorMsg .= "Please enter a valid credit card number.<br>";         
                $success = false; 
            } else {
                $ccnumber = encryptthis(sanitize_input($_POST["ccnumber"]), $key);    
            }
        }

        if (empty($_POST["expdate"])) {
            $errorMsg .= "Exp date is required.<br>";     
            $success = false; 
        } else {
            $expdate = sanitize_input($_POST["expdate"]); 
            if (!preg_match("/^([0-9]{2}\/[0-9]{2})$/", $expdate)) {
                $errorMsg .= "Please enter a valid exp date.<br>";         
                $success = false; 
            } else {
                $expdate = encryptthis(sanitize_input($_POST["expdate"]), $key);    
            }
        }

        if (empty($_POST["ccvnumber"])) {
            $errorMsg .= "CCV number is required.<br>";     
            $success = false; 
        } else {
            $ccvnumber = sanitize_input($_POST["ccvnumber"]); 
            if (!preg_match("/^([0-9]{3})$/", $ccvnumber)) {
                $errorMsg .= "Please enter a valid ccv number.<br>";         
                $success = false; 
            } else {
                $ccvnumber = encryptthis(sanitize_input($_POST["ccvnumber"]), $key);    
            }
        }

         if ($success) {     
            saveCustomerInfoToDB();
            savePaymentInfoToDB();
            saveOrderToTable();
            echo "<h1>Your Order Has been Placed!</h1>";
            echo "<h2>Thank You For Your Support</h2>";    
            echo "<h3>Have A Nice Day</h3>"; 
            header('Refresh:3; url=index.php');
            exit();
        } else {    
            echo "<h1>Please check your payment input!</h1>";
            echo "<h4>The following input errors were detected:</h4>";     
            echo "<p>" . $errorMsg . "</p>"; 
            header('Refresh:3; url=payment_information.php');
        } 

        //Helper function that checks input for malicious or unwanted content. 
        function sanitize_input($data) {   
            $data = trim($data);   
            $data = stripslashes($data);   
            $data = htmlspecialchars($data);   
            return $data; 
        }

        function encryptthis($data, $key) {
            $encryption_key = base64_decode($key);
            $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
            $encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
            return base64_encode($encrypted . '::' . $iv);
        }

        //Save user information into database.
        function saveCustomerInfoToDB() {  
            global $custname, $custemail, $custnumber, $streetadd, $blknumber, $unitnumber, $zipcode, $deldate, $deltime, $errorMsg; 
            // Create connection     
            $conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
            // Check connection     
            if ($conn->connect_error) {            
                $errorMsg = "Connection failed: " . $conn->connect_error;         
            }
            else{ //prepared statement
                $compile = $conn->prepare("INSERT INTO customer_information (name, email, mobileNumber, streetName, blkNumber, unitNumber, zipcode, deliveryDate, deliveryTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $compile->bind_param("ssisssiss", $custname, $custemail, $custnumber, $streetadd, $blknumber, $unitnumber, $zipcode, $deldate, $deltime);
                $compile->execute();
                $compile->close();
                $conn->close();
            } 
        } 

        //Save user information into database.
        function savePaymentInfoToDB() {  
            global $ccname, $ccnumber, $expdate, $ccvnumber, $errorMsg; 
            // Create connection     
            $conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
            if ($conn->connect_error) {            
                $errorMsg = "Connection failed: " . $conn->connect_error;         
            }
            else{ //prepared statement
                $sql = "SELECT customer_id FROM customer_information ORDER BY customer_id DESC LIMIT 1";
                $idValue = $conn->query($sql);
                $idValueResult = $idValue->fetch_assoc();
                $customerID = $idValueResult['customer_id'];

                $compile = $conn->prepare("INSERT INTO customer_payment_information (customer_id, fullName, creditcardNumber, expiry, ccv) VALUES (?, ?, ?, ?, ?)");            
                $compile->bind_param("issss", $customerID, $ccname, $ccnumber, $expdate, $ccvnumber);
                $compile->execute();
                $compile->close();
                $conn->close();
            } 
        }        

        //Save user order into database.
        function saveOrderToTable() {
            session_start();
            global $errorMsg;
            $connect = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
            $array = $_SESSION['shopping_cart'];
            if ($connect->connect_error) {
                $errorMsg = "Connection failed: " . $connect->connect_error;  
            } else {
                foreach ($array as $product) {
                    if($product == "") {
                        //prevent user from returning back to payment page after checkout.
                        header('Location: index.php');
                    } 
                    else {
                        //fetch primary key value
                        $sql = "SELECT customer_id FROM customer_information ORDER BY customer_id DESC LIMIT 1";
                        $idValue = $connect->query($sql);
                        $idValueResult = $idValue->fetch_assoc();
                        $customerID = $idValueResult['customer_id'];

                        //prepared statement
                        $compile = $connect->prepare("INSERT INTO customer_order (cust_id, productName, quantity, price, pax) VALUES (?, ?, ?, ?, ?)");
                        $compile->bind_param("isiii", $customerID, $product['name'],$product['quantity'], $product['price'], $product['pax']);
                        $compile->execute();
                        $compile->close();
                    }
                }
            }
            session_destroy();
            $connect->close();
        }

    ?> 
    </article>

    <?php
        include "footer.inc.php";
    ?>
</body>

There'a pattern called PRG (POST-Redirect-GET), which deals with this annoyance with the browsers' back button.有一种称为 PRG (POST-Redirect-GET) 的模式,它通过浏览器的后退按钮来处理这种烦恼。

Essentially, you can POST to your page, do your thing, then redirect to a second page which will not perform the action again.本质上,您可以发布到您的页面,做您的事情,然后重定向到不会再次执行该操作的第二个页面。

Here's a decent article explaining it in more detail.这是一篇体面的文章,更详细地解释了它。

https://en.wikipedia.org/wiki/Post/Redirect/Get https://en.wikipedia.org/wiki/Post/Redirect/Get

After the checkout add this:结帐后添加:

<?php
header("Location: /index.php");
exit();

The location header tells the browser to redirect, exit stops the script execution, also beware that if you have sent any output to browser (eg echo or the html code you have on top), it won't work.位置 header 告诉浏览器重定向,退出停止脚本执行,还要注意,如果您已将任何 output 发送到浏览器(例如echo或 html 代码,您将无法正常工作)。

You should handle the checkout separately where nothing is sent to the browser.您应该单独处理结帐,其中没有任何内容发送到浏览器。

You could for example create a separate file with your checkout code that you will include right before the <html> tag, then if nothing is submitted, just do nothing in the script, if the form is submitted, handle it and then do the redirect.例如,您可以使用您的结帐代码创建一个单独的文件,您将在<html>标记之前包含该文件,然后如果没有提交任何内容,则在脚本中不执行任何操作,如果提交了表单,处理它然后执行重定向.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM