Display PHP Errors + 15 Other Useful PHP snippets

Here is the 2 lines of codes you need to show PHP errors directly in the browser, and some powerful and frequently used boilerplate code snippets.

Display PHP Errors in Browser

To display PHP errors directly in the browser, you can use the error_reporting function and set the display_errors directive to On in your PHP script. 

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');

// your PHP code goes here
?>

By setting the error_reporting function to E_ALL, you are telling PHP to report all errors, warnings, and notices. And by setting the display_errors directive to On, you are telling PHP to display these errors directly in the browser.

However, it's important to note that displaying errors directly in the browser can be a security risk, as it can expose sensitive information about your server and code to potential attackers. Therefore, it's recommended to only enable this feature in a development environment and disable it in a production environment.

PHP File Headers

Adding a file header to your PHP files can help you identify the author, date of creation, and purpose of the file.

<?php
/**
 * File Name: my_script.php
 * Author: John Doe
 * Date: 2023-04-15
 * Description: This script does XYZ.
 */

Autoloading

Autoloading can help you automatically load your PHP classes without the need for explicit include or require statements. Here's an example using the PSR-4 autoloading standard:

<?php
// define the namespace and path to your classes
namespace MyApp;
define('APP_PATH', __DIR__.'/src/');

// autoload your classes using the PSR-4 standard
spl_autoload_register(function ($class) {
    $prefix = 'MyApp\\';
    $base_dir = APP_PATH;
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    if (file_exists($file)) {
        require $file;
    }
});

Error Handling

Proper error handling can help you debug and diagnose problems in your PHP code. Here's an example of how to catch and handle exceptions:

<?php
try {
    // your PHP code goes here
} catch (Exception $e) {
    // handle the exception
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

Database Connection

Establishing a database connection is a common task in PHP web applications. Here's an example of how to connect to a MySQL database with PDO:

<?php
// define the database connection parameters
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabase";

try {
    // create a PDO connection to the database
    $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);
    
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

In this example, we're creating a new PDO connection to a MySQL database using the mysql:host and dbname options. We're also setting the PDO::ATTR_ERRMODE option to PDO::ERRMODE_EXCEPTION to enable error handling.

Once the connection is established, we can perform various database operations using the PDO object, such as executing queries and fetching results.

If you prefer to use mysqli, here is the boilerplate sample code for that as well:

<?php
// define the database connection parameters
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabase";

// create a connection to the database
$conn = new mysqli($servername, $username, $password, $dbname);

// check the connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

Form Validation

Validating user input from HTML forms is important to prevent security vulnerabilities and ensure data integrity. Here's an example of how to validate an email input:

<?php
$email = $_POST['email'];

// check if the email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format";
}

While validating user input in backend is important for security reasons, having a proper input validation in the front UI is vital for the user experience.

Session Handling

Sessions allow you to store user-specific data across multiple requests. Here's an example of how to start a session and set a session variable:

<?php
session_start();
$_SESSION['username'] = 'john.doe';

File Uploads

Uploading files from HTML forms is a common task in web applications. Here's an example of how to upload a file and save it to a directory:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// check if the file is an image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// check if the file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// check the file size
if ($_FILES["file"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// move the file to the uploads directory
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
} else {
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file ". htmlspecialchars( basename( $_FILES["file"]["name"])). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

Redirects

Redirecting users to different pages or URLs is a common task in web applications. Here's an example of how to redirect to a different page:

<?php
// redirect to a different page
header("Location: https://www.example.com/newpage.php");
exit;

When you use the header("Location: ...") function in PHP without specifying an HTTP response code, the default response code is 302 Found.

This HTTP response code indicates that the requested resource has been temporarily moved to a new location. It's often used for temporary redirects, such as when a site is undergoing maintenance or a page is being moved temporarily to a new location.

However, it's generally considered good practice to explicitly specify the HTTP response code when using a redirect. This makes it clear to clients and search engines what type of redirect is being used, and can also help with SEO by passing on link juice and maintaining the relevance of the redirected page:

<?php
// redirect to a different page with an HTTP response code
header("Location: https://www.example.com/newpage.php", true, 301);
exit;

In this example, we're using the header function to send an HTTP Location header to the client, which tells the client to redirect to a different page. We're also setting the optional third parameter of the header function to 301, which specifies the HTTP response code for the redirect as 301 Moved Permanently.

This type of redirect should be used when you want to permanently redirect the client to a new location, and you want search engines and other clients to update their bookmarks and links to your site. For example, if you change the URL structure of your site or move a page to a new location, you might want to use a 301 redirect to ensure that clients can still access the content and search engines can update their indexes.

It's important to note that when you use a redirect, the client's browser will make a new request to the new URL, so any data stored in the client's session or cookies may be lost. Therefore, you should be careful when using redirects and ensure that any necessary data is passed along in the redirect URL or stored in a database.

Date and Time + Set time zone

Working with dates and times is a common task in web applications. Here's an example of how to get the current date and time:

<?php
// set the default timezone
date_default_timezone_set('Europe/Oslo');

// get the current date and time
$date = date('Y-m-d H:i:s');
echo "The current date and time is: " . $date;

Pagination

Displaying large amounts of data in a web application often requires pagination. Here's an example of how to paginate a set of data:

<?php
// set the number of records per page
$records_per_page = 10;

// get the current page number
if (isset($_GET['page'])) {
    $current_page = $_GET['page'];
} else {
    $current_page = 1;
}

// calculate the offset
$offset = ($current_page - 1) * $records_per_page;

// query the database for the records
$sql = "SELECT * FROM mytable LIMIT $offset, $records_per_page";
$result = mysqli_query($conn, $sql);

// display the records
while ($row = mysqli_fetch_assoc($result)) {
    // display the record
}

// display the pagination links
$sql = "SELECT COUNT(*) AS total_records FROM mytable";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$total_records = $row['total_records'];
$total_pages = ceil($total_records / $records_per_page);

echo "<ul class='pagination'>";
for ($i = 1; $i <= $total_pages; $i++) {
    echo "<li><a href='?page=$i'>$i</a></li>";
}
echo "</ul>";

Email Handling

Sending emails is a common task in web applications for tasks such as user registration or password reset requests. Here's an example of how to send an email using PHP's built-in mail function:

<?php
$to = "recipient@example.com";
$subject = "Test email";
$message = "This is a test email.";
$headers = "From: sender@example.com\r\n" .
           "Reply-To: sender@example.com\r\n" .
           "X-Mailer: PHP/" . phpversion();

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully.";
} else {
    echo "Email sending failed.";
}

Hashing and Salting Passwords

Storing user passwords securely is an important aspect of web application security. Here's an example of how to hash and salt a password using PHP's password_hash function:

<?php
$password = "mypassword";
$hash = password_hash($password, PASSWORD_DEFAULT);
echo "Hashed password: " . $hash;

To verify a password, you can use PHP's password_verify function:

<?php
$hashed_password = "hash-from-database";
$password = "mypassword";
if (password_verify($password, $hashed_password)) {
    echo "Password is valid.";
} else {
    echo "Password is invalid.";
}

What's the difference between password_hash() and crypt()

Both password_hash() and crypt() are functions in PHP that are used for hashing and storing passwords securely. However, there are some differences between them that can affect which one you should use in a given situation.

Here are some of the key differences between password_hash() and crypt():

  1. Algorithm: password_hash() uses the bcrypt algorithm by default, which is considered to be a strong and secure algorithm for password hashing. crypt(), on the other hand, can use a variety of different algorithms, depending on the options you pass to it.
  2. Salt: password_hash() automatically generates and includes a random salt with the hashed password, which makes the hash more resistant to attacks like rainbow tables. crypt(), on the other hand, requires you to generate and provide your own salt.
  3. Complexity: password_hash() is designed to be easy to use, and provides a simple interface for hashing and verifying passwords. crypt(), on the other hand, is more complex and requires you to manually generate and manage salts and other parameters.

Based on these differences, it's generally recommended to use password_hash() for most password hashing needs, as it provides a simple and secure interface that's easy to use. crypt() can be useful in situations where you need more control over the hashing process, such as when you're using a specific algorithm or need to customize the hashing parameters.

In general, you should avoid using insecure or outdated password hashing functions like md5() and sha1(), as these algorithms are vulnerable to attacks and can be easily cracked. Instead, use a strong, modern hashing algorithm like bcrypt or Argon2, and make sure to use a unique salt for each password to further increase the security of the hash.

User Authentication

Implementing user authentication is a common task in web applications. Here's an example of how to authenticate a user based on their username and password:

<?php
$username = $_POST['username'];
$password = $_POST['password'];

// query the database for the user
$sql = "SELECT * FROM users WHERE username = :username";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $username);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// verify the password
if ($user && password_verify($password, $user['password'])) {
    // password is valid
    // start a session and set the user ID
    session_start();
    $_SESSION['user_id'] = $user['id'];
    echo "Login successful.";
} else {
    // password is invalid
    echo "Invalid username or password.";
}

In this example, we're first retrieving the user's username and password from the login form. Then, we're querying the database using a prepared statement to retrieve the user's record based on their username.

We're using bindParam to bind the value of the $username variable to the :username parameter in the SQL query. This helps prevent SQL injection attacks by ensuring that user input is properly sanitized.

Once we have the user's record, we're using password_verify to verify the password that the user entered against the hashed password stored in the database. If the password is valid, we're starting a session and setting the user_id session variable to the ID of the authenticated user. If the password is invalid, we're displaying an error message to the user.

It's important to note that this example is just a basic demonstration of user authentication in PHP, and in a real-world application, you'll need to consider additional security measures, such as implementing CSRF protection and rate limiting to prevent brute-force attacks. You should also make sure to store passwords securely using a strong, modern hashing algorithm like bcrypt or Argon2.

Query String Handling

Working with query strings is a common task in web applications. Here's an example of how to parse a query string and extract its parameters:

<?php
$query_string = "page=2&category=books&sort=asc";
$params = [];
parse_str($query_string, $params);
echo "Page: " . $params['page'] . "<br>";
echo "Category: " . $params['category'] . "<br>";
echo "Sort: " . $params['sort'];

Regular Expressions

Regular expressions are a powerful tool for pattern matching and data validation in PHP. Here's an example of how to use a regular expression to validate an email address:

<?php
$email = $_POST['email'];

// check if the email is valid
if (!preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
    echo "Invalid email format";
}

Image Manipulation

Working with images is a common task in web applications. Here's an example of how to resize an image using the GD library:

<?php
// set the source image file and the target width and height
$src_file = "image.jpg";
$target_width = 100;
$target_height = 100;

// create a new image from the source file
$src_image = imagecreatefromjpeg($src_file);

// get the source image dimensions
$src_width = imagesx($src_image);
$src_height = imagesy($src_image);

// create a new image with the target dimensions
$target_image = imagecreatetruecolor($target_width, $target_height);

// resize the source image to fit the target dimensions
imagecopyresampled($target_image, $src_image, 0, 0, 0, 0, $target_width, $target_height, $src_width, $src_height);

// save the resized image to a file
imagejpeg($target_image, "resized_image.jpg");

 

Updated