Search code examples
phphtmlformssession-variableshidden

Can I eliminate use of hidden form fields in html to pass data between pages where the data is row id of all table rows


I am developing an web app in which user should click on a link dislayed next to an order to generate an order details pdf The page showing the orders by a particular user as a table with two columns:- time of order and pdf link for each order is having this snippet

echo '<table class="table"><tr>
<th>Order Submitted on</th>
<th>Get Details</th>
</tr>';
while ($row = $ordersByUser->fetch(PDO::FETCH_ASSOC)) {
    echo '<tr><td>'.$row['timestamp'].'</td>';

    echo '<td><form method="POST" action="generateorderpdf.php">
    <input type ="hidden" name="orderid" value='.$row['id'].'>
    <input type="submit" value="CLICK" class="btn btn-dark">
    </form></td></tr>';
}
echo '</table>';

I am storing the primary key of each order

$row['id']
in a hidden field which is then sent to the generateOrderPdf.php page to generate the order pdf through a form using post method. My problem is that users can change the hidden input field using some browser developer tools and generate pdfs for other users which i definity don't want users to do (and its the reason why i am sending post request to the generate pdf page since anyone can edit the get url and see other people's orders). So is there any way in which I can eliminate the dependency on hidden input fields to send order id to the generateOrderPdf.php page?

I've read that i can use sessions to store sensitive data which then eliminates the need to use hidden form fields but I don't know is it even possible to use session variables to solve this problem and if possible how since this is a table of data?


Solution

  • Actually, you can do this with a session variable.

    Put all the order IDs in an array in the session. Instead of putting the order ID in the hidden input, put the array index.

    $myorders = [];
    $order_index = 0;
    echo '<table class="table"><tr>
    <th>Order Submitted on</th>
    <th>Get Details</th>
    </tr>';
    while ($row = $ordersByUser->fetch(PDO::FETCH_ASSOC)) {
        $myorders[$order_index] = $row['id'];
        echo '<tr><td>'.$row['timestamp'].'</td>';
    
        echo '<td><form method="POST" action="generateorderpdf.php">
        <input type ="hidden" name="orderid" value="'.$order_index.'">
        <input type="submit" value="CLICK" class="btn btn-dark">
        </form></td></tr>';
        $order_index++;
    }
    echo '</table>';
    $_SESSION['myorders'] = $myorders;
    

    Then in generatorderpdf.php, you use $_SESSION['myorders'][$_POST['orderid']] to get the order ID.