PHP Best Practices
- Sean Gobson
- Jan 29, 2018
- 3 min read

PHP is an open source language and has several twists and turns you will need to discover through several means. It is an inconsistent means of development and a requirement when building sites meant for different purposes. Each version has certain features used, which are relevant and used where required.
In addition, the flaws relating to different versions of the tool are also difficult to discover and are necessarily taken care of when a need to execute this program is further required. It is a means of suggesting best directions to take when facing a common low-level development task a PHP developer might encounter which is unclear because of several options PHP has to offer.
An example to connect to databases is common with a large number of available solutions in PHP, not all being good ones include in the document. Looking like a series of short, initial solutions. Examples get you up and run with basic settings, and you should carry out your own research to flesh them into something you feel is important.
PHP provides a built-in password-hashing library, having uses as a bcrypt algorithm, currently considered as the best algorithm for password hashing.
<?php
// Hash the password. $hashedPassword will be a 60-character string.
$hashedPassword = password_hash('my super cool password', PASSWORD_DEFAULT);
// You can now safely store the contents of $hashedPassword in your database!
// Check if a user has provided the correct password by comparing what they typed with our hash
password_verify('the wrong password', $hashedPassword); // false
password_verify('my super cool password', $hashedPassword); // true
?>
PHP Practices for Beginners
The built-in PHP password-hashing library not there in a version of PHP has installation with version 12.04. Instead, use an open-source phpass library, providing the same bcrypt-based methods that are an easy to initiate class.
<?php
// Include the phpass library
require_once('phpass-0.3/PasswordHash.php');
// Initialize hasher without portable hashes (this is more secure)
$hasher = new PasswordHash(8, false);
// Hash the password. $hashedPassword will be a 60-character string.
$hashedPassword = $hasher->HashPassword('my super cool password');
// You can now safely store the contents of $hashedPassword in your database!
// Check if a user has provided the correct password by comparing what they typed with our hash
$hasher->CheckPassword('the wrong password', $hashedPassword); // false
$hasher->CheckPassword('my super cool password', $hashedPassword); // true
?>
PHP Practices That You Must Follow
There are several ways connecting to a MySQL database in PHP. PDO (PHP Data Objects) is the newest and most robust. PDO has consistent interfaces across different types of database, uses object-oriented approach, supporting more features offered by new databases.
<?php
try{
// Create a new connection.
// You'll probably want to replace hostname with localhost in the first parameter.
// Note the declaration of charset to be utf8mb4. This alerts connection for passing UTF-8
data. This is not a requirement depending on configuration, but it saves you headaches down the road if you are trying to store Unicode strings in the database. See "Gotchas".
// The PDO options we pass do following:
// \PDO::ATTR_ERRMODE enables exceptions for errors. This is optional but can be handy.
// \PDO::ATTR_PERSISTENT disables persistent connections, which can cause concurrency
issues in certain cases. See "Gotchas".
$link = new \PDO( 'mysql:host=your-hostname;dbname=your-db;charset=utf8mb4',
'your-username',
'your-password',
array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false
)
);
$handle = $link->prepare('select Username from Users where UserId = ? or Username = ? limit ?');
// PHP bug: if you don't specify PDO::PARAM_INT, PDO may enclose the argument in quotes.
This can mess up some MySQL queries that don't expect integers to be quoted.
// See: https://bugs.php.net/bug.php?id=44639
// If you're not sure whether values you are passing is integer, use the is_int() function.
// (This bug was fixed in Oct. 2016, but the fix is not applied to the version of PHP used in this document; see https://bugs.php.net/bug.php?id=73234)
$handle->bindValue(1, 100, PDO::PARAM_INT);
$handle->bindValue(2, 'Bilbo Baggins');
$handle->bindValue(3, 5, PDO::PARAM_INT);
$handle->execute();
// Using the fetchAll() method might as resource-heavy if you're selecting a truly massive number of rows.
// If that's the case, you can use a fetch() method and loop through each result row one by one.
// You can return arrays and other things instead of objects. See the PDO documentation for details.
$result = $handle->fetchAll(\PDO::FETCH_OBJ);
foreach($result as $row){
print($row->Username);
}
}
catch(\PDOException $ex){
print($ex->getMessage());
}
?>
Comments