Anonymous
29
Comment sécuriser php mysql

Answer

To secure PHP MySQL, it is recommended to use prepared statements in your PHP scripts. Prepared statements can be executed using PHP Data Objects (PDO)
1
2
.
PDO is included in the latest version of PHP and was introduced in PHP 5.1 and available as a PECL extension in PHP 5.0. It is not accessible for earlier PHP versions
1
.
It is also recommended to avoid using the mysql and mysqli extensions in your PHP code as they are deprecated/outdated but still often used. You can rewrite the code to use PDO instead
1
.
Here's an example of how to use prepared statements with PDO:
php
// Establish a connection to the database $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // Set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Prepare a statement $stmt = $conn->prepare("SELECT * FROM MyGuests WHERE lastname=:lastname"); // Bind parameters $stmt->bindParam(':lastname', $lastname); // Set parameters and execute $lastname = "Doe"; $stmt->execute(); // Fetch results $result = $stmt->fetchAll(); } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } // Close the connection $conn = null;
In this example, a connection to the database is established using PDO. A prepared statement is then created with a placeholder :lastname. The bindParam() method is used to bind the value of $lastname to the placeholder. The statement is then executed using execute(), and the results are fetched using fetchAll()
1
.
Other security best practices for PHP include updating your PHP version regularly, being aware of XSS attacks (Cross-site scripting), disabling directory listing, restricting file and directory access, hiding version and OS identity, and more
2
3
.

Related

Comment éviter les attaques XSS en PHP
Comment sécuriser une base de données MySQL
Comment mettre à jour la version de PHP sur un serveur web