Reputation:
I have a ticket system.
Ticket ID is in $_GET which allows users to type any number into the parameter thus even accessing tickets belonging to a different user.
How to avoid this situation? Can't figure it out.
TO GET ALL TICKETS FOR USER:
<?php
// Connect to MySQL using the below function
$pdo = pdo_connect_mysql();
// MySQL query that retrieves all the tickets from the databse
$stmt = $pdo->prepare('SELECT * FROM tickets WHERE user=:user ORDER BY created DESC');
$stmt->bindParam(":user", $_SESSION['name']);
$stmt->execute();
$tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
AND VIEW PAGE
<?php
// Connect to MySQL using the below function
$pdo = pdo_connect_mysql();
// Check if the ID param in the URL exists
if (!isset($_GET['id'])) {
exit('No ID specified!');
}
// MySQL query that selects the ticket by the ID column, using the ID GET request variable
$stmt = $pdo->prepare('SELECT * FROM tickets WHERE id = ?');
$stmt->execute([ $_GET['id'] ]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC);
// Check if ticket exists
if (!$ticket) {
exit('Invalid ticket ID!');
}
// Update status
if (isset($_GET['status']) && in_array($_GET['status'], array('open', 'closed', 'resolved'))) {
$stmt = $pdo->prepare('UPDATE tickets SET status = ? WHERE id = ?');
$stmt->execute([ $_GET['status'], $_GET['id'] ]);
header('Location: view.php?id=' . $_GET['id']);
exit;
}
// Check if the comment form has been submitted
if (isset($_POST['msg']) && !empty($_POST['msg'])) {
// Insert the new comment into the "tickets_comments" table
$stmt = $pdo->prepare('INSERT INTO tickets_comments (ticket_id, msg) VALUES (?, ?)');
$stmt->execute([ $_GET['id'], $_POST['msg'] ]);
header('Location: view.php?id=' . $_GET['id']);
exit;
}
$stmt = $pdo->prepare('SELECT * FROM tickets_comments WHERE ticket_id = ? ORDER BY created DESC');
$stmt->execute([ $_GET['id'] ]);
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
Upvotes: 0
Views: 82
Reputation: 422
Add condition into SQL which retrieves ticket from MySQL:
$stmt = $pdo->prepare('SELECT * FROM tickets WHERE id = ? AND user = ?');
$stmt->execute([ $_GET['id'], $_SESSION['name']]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC);
This is the fastest and efficient solution.
Alternatively, you can fetch the ticket first and then check for the user:
$stmt = $pdo->prepare('SELECT * FROM tickets WHERE id = ?');
$stmt->execute([ $_GET['id'] ]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC);
// Check if ticket exists
if (!$ticket) {
exit('Invalid ticket ID!');
}
// Check if ticket belongs to correct user
if ($ticket['user'] !== $_SESSION['name']) {
exit('Not your ticket!');
}
Upvotes: 2