What are the best practices for handling user input in PHP to prevent SQL injection vulnerabilities in a news system?
To prevent SQL injection vulnerabilities in a news system, it is important to properly sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which separate the SQL code from the user input, making it impossible for malicious input to alter the SQL logic.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=news_db", "username", "password");
// Sanitize and validate user input
$title = filter_var($_POST['title'], FILTER_SANITIZE_STRING);
$content = filter_var($_POST['content'], FILTER_SANITIZE_STRING);
// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("INSERT INTO news (title, content) VALUES (:title, :content)");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':content', $content);
// Execute the query
$stmt->execute();
Related Questions
- Can the visibility of a cookie set in a PHP script be changed to make it immediately accessible?
- What are potential pitfalls when using PHP to store and retrieve cookies based on user input?
- What are the benefits of using SQL queries with IF statements in PHP for assigning user ranks based on post count?