Perhaps this, avoiding the manipulation of the URL parameters, is not solvable and cannot be avoided, but an insecurity that has been brought to my attention.
Which anyone can add products to the shopping cart by modifying the value of the url for example:
http://example.com/updatecart.php?itemId=1
http://example.com/updatecart.php?itemId=11
http://example.com/updatecart.php?itemId=10
http://example.com/updatecart.php?itemId=20
http://example.com/updatecart.php?itemId=9
In this way, a user directly adds products to the shopping cart, it may not be so vulnerable, but there is some way to avoid these manipulations
This is my code:
<?php
session_start();
$itemId = isset($_GET['itemId']) ? $_GET['itemId'] : "";
if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['qtyupdate'])) {
for ($i = 0; $i < count($_POST['qtyupdate']); $i++) {
$key = $_POST['arr_key_' . $i];
$_SESSION['qty'][$key] = $_POST['qtyupdate'][$i];
}
} else {
$qty = isset($_POST['qty']) ? $_POST['qty'] : 1;
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
$_SESSION['qty'][] = array();
}
if (in_array($itemId, $_SESSION['cart'])) {
$key = array_search($itemId, $_SESSION['cart']);
$_SESSION['qty'][$key] = $_SESSION['qty'][$key] + $qty;
} else {
array_push($_SESSION['cart'], $itemId);
$key = array_search($itemId, $_SESSION['cart']);
$_SESSION['qty'][$key] = $qty;
}
}
header('location:cart.php');
?>
You can do it using a "key" or "token" like this:
We create the php file "crearkey.php":
This will create a txt with the key, the name of the txt can be modified in the $keytxt variable.
Now we create the "key.php" file that will read the txt and save the variable with the key
Now it is enough to include this in our page " http://example.com/updatecart.php ", that is, in your file "updatecart.php"
To the links of your cart you must add one more id, you have "itemId" and you must add one more that will be "key", example: " http://example.com/updatecart.php?itemId=1&key=lakeycreada " Example :
Then from the cpanel of your host you must create a scheduled task or cron job that enters " http://example.com/ruta/crearkey.php " every x time, it can be minutes, like hours or days, the recommended would be 1 or 2 minutes...
Edit: How to create the scheduled task?
1.- Open cPanel and look for the option "Cron Jobs"
2.- We choose with which domain the scheduled task will be carried out
3.- We press "alter crons"
4.- We put every few minutes or hours the task will be executed (enter crearkey.php to create a new key) and put the url where the php file is
5.- We give add cron
And ready! You would have everything solved.