PHP Docs

Last updated: Jan 20th, 2022

Download

Welcome to the mine useful documentation for daily work on web developer and computer programming. Thanks to PrettyDocs for theme template layout; download it at the page linked in the button below.

Download PrettyDocs

PrismJS

PrismJS is used as the syntax highlighter here. You can build your own version via their website should you need to.

Microtime

Return current Unix timestamp with microseconds. Useful for count execution time.


$start = microtime(true);
while (...){

}
$time_elapsed_sec = microtime(true) - $start;
                                    

Prepared Statement

Prepared Statement to prevent SQL injection.


$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();
                                    

Login System

User login system tutorial using HTML, PHP, MySql, Session and CSS on which user can log in to the profile page and log out.

Login form (index.php)

<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
    header("location: profile.php"); // Redirecting To Profile Page
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Login Form in PHP with Session</title>
        <link href="style.css" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id="login">
        <h2>Login Form</h2>
        <form action="" method="post">
            <label>UserName:</label>
            <input id="name" name="username" placeholder="username" type="text">
            <label>Password:</label>
            <input id="password" name="password" placeholder="**********" type="password"><br><br>
            <input name="submit" type="submit" value=" Login ">
            <span><?php echo $error; ?></span>
        </form>
        </div>
    </body>
</html>
                                    
Php code for login (login.php)

session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
    if (empty($_POST['username']) || empty($_POST['password'])) {
        $error = "Username or Password is invalid";
}
else{
    // Define $username and $password
    $username = $_POST['username'];
    $password = $_POST['password'];
    // mysqli_connect() function opens a new connection to the MySQL server.
    $conn = mysqli_connect("localhost", "root", "", "company");
    // SQL query to fetch information of registerd users and finds user match.
    $query = "SELECT username, password from login where username=? AND password=? LIMIT 1";
    // To protect MySQL injection for Security purpose
    $stmt = $conn->prepare($query);
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $stmt->bind_result($username, $password);
    $stmt->store_result();
    if($stmt->fetch()) //fetching the contents of the row {
        $_SESSION['login_user'] = $username; // Initializing Session
        header("location: profile.php"); // Redirecting To Profile Page
    }
    mysqli_close($conn); // Closing Connection
}
                                    
Php code for user session (session.php)

// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "", "company");
session_start();// Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$query = "SELECT username from login where username = '$user_check'";
$ses_sql = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($ses_sql);
$login_session = $row['username'];
                                    
Php code for user profile (profile.php)

<?php
include('session.php');
if(!isset($_SESSION['login_user'])){
    header("location: index.php"); // Redirecting To Home Page
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Your Home Page</title>
        <link href="style.css" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id="profile">
            <b id="welcome">Welcome: <i><?php echo $login_session; ?></i></b>
            <b id="logout"><a href="logout.php">Log Out</a></b>
        </div>
    </body>
</html>
                                    
Php code for logout (logout.php)

session_start();
if(session_destroy()) // Destroying All Sessions {
    header("Location: index.php"); // Redirecting To Home Page
}
                                    
MySQL code for creating databases and table for login system

CREATE DATABASE company;

CREATE TABLE login(
    id int(10) NOT NULL AUTO_INCREMENT,
    username varchar(255) NOT NULL,
    password varchar(255) NOT NULL,
    PRIMARY KEY (id)
);
                                    

Password Reset

One very important feature of any good membership website is a password reset system because some users are bound to forget their password.

The whole process of implementing such a system can be broken down into 3 main steps. To ease the explanation, let's analyze these steps in terms of the forms that we will present for the user to fill:

  1. Login Form: This form takes the username and password combination of a user and logs them in if they are registered on the system. On this form we provide a "Forgot your password?" link in case the user forgot their password and need to reset it.
  2. Email Form: If the user has forgotten their password, they can click on the "Forgot your password?" link on the login page to reset it. Clicking on this link will take them to another page that prompts them to enter the email. When the email address they provide is not in our users table in the database, we will display and error message which says "No such user exists on our system". If on the other hand the user exists, we will generate a unique token (a unique random string) and store this token together with that email address in the password_resets table in the database. Then we will send them an email that has that token in a link. When they click on the link in the email we sent them, they will be sent back to our website on a page that presents them with another form.
  3. New password Form: Once the user is back on our website again, we will grab the token that comes from the link and store it in a session variable. Then we will present them with a form that asks them to enter a new password for their account on our website. When the new password is submitted, we will query the password_resets table for the record that has that token that just came from the link in the mail. If the token is found on the password_resets table, then we are confident that they user is who they are and they clicked on the link in their mail. At this point now we grab the user's email from the password_resets (remember we had saved the token alongside their email address) table and use that email fetch the user from the users table and update their password.

Upload File

In this section we will see how it works the $_FILES superglobal variable which is used as a vector for transferring files from the client to the server.

Configure upload options correctly

Before proceeding it is good to remember that inside the php.ini file there are several options that relate to the upload of files to which it is good to pay attention. If you do not have direct access to the php.ini file I remind you that you can view the various settings of your PHP installation using the phpinfo() function.

Below are the affected options:

  • file_uploads: if set to 0 (or "off") the file upload is disabled (by default it is set to 1 or "on");
  • upload_tmp_dir: it is the temporary directory that PHP will use to transit files during upload; if it is not specified the system will use a default folder;
  • upload_max_filesize: indicates the maximum file size you can upload (default 2MB);
  • max_file_uploads: maximum number of files that can be uploaded simultaneously.

In addition to these there are other parameters that affect file uploads, namely:

  • post_max_size: indicates the maximum size of data that can be sent through the POST method (its value should be greater than upload_max_filesize);
  • memory_limit: sets the maximum memory size that can be occupied by the execution of a script (in recent versions of PHP it is set to 128MB). In order not to interfere with uploads, this parameter should be greater than post_max_size.
Create the upload form

<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="30000">
    Upload this file: <input name="userfile" type="file"></br>
    <input type="submit" value="Send File">
</form>
                                    
The PHP code that realizes the upload

// Verify that the file has actually been uploaded
if (!isset($_FILES['userfile']) || !is_uploaded_file($_FILES['userfile']['tmp_name'])) {
    echo 'You have not sent any files...';
    exit;
}

// Folder location where to put files uploaded by users
$uploaddir = '/var/www/myupload/';

// Retrieving the temporary path of the file
$userfile_tmp = $_FILES['userfile']['tmp_name'];

/* The $_FILE superglobal variable is an array containing all the information about the uploaded file:
    $_FILES['userfile']['name']
    $_FILES['userfile']['type']
    $_FILES['userfile']['size'] */
// Retrieving the original name of the uploaded file
$userfile_name = $_FILES['userfile']['name'];

// Copy the file from its temporary location to my upload folder
if (move_uploaded_file($userfile_tmp, $uploaddir . $userfile_name)) {
    // If the operation was successful...
    echo 'File sent successfully.';
}
else {
    // If the operation failed...
    echo 'Invalid Upload!';
}
                                    
Techniques for the uploads validation

Check if the file has been uploaded


if (!isset($_FILES['userfile']) || !is_uploaded_file($_FILES['userfile']['tmp_name'])) {
    echo 'You have not sent any files...';
    exit;
}
                                    

Check that the file is not too large


if ($_FILES['userfile']['size'] > 4194304) {
    echo 'The file is too big!';
    exit;
}
                                    

Verify that the upload does not overwrite another file


$target_file = '/var/www/myupload/' . $_FILES['userfile']['name'];
if (file_exists($target_file)) {
    echo The file already exists';
    exit;
}
                                    

Check the extension of the uploaded file


$ext_ok = array('doc', 'docx', 'pdf');
$temp = explode('.', $_FILES['userfile']['name']);
$ext = end($temp);
if (!in_array($ext, $ext_ok)) {
    echo 'The file has an unacceptable extension!';
    exit;
}
                                    

Check if the file is actually an image


$is_img = getimagesize($_FILES['userfile']['tmp_name']);
if (!$is_img) {
    echo 'You can only send pictures';
    exit;
}
                                    

FPDF Library

FPDF is a PHP class that allows you to generate PDF files directly from PHP.

FPDF also has other advantages: high-level functions.
Here is a list of its main features:

  • Choice of measurement unit, page size and margins
  • Using header and footer
  • Automatic page change
  • Word wrap and text justification
  • Support for images (JPEG, PNG e GIF)
  • Colors
  • Links
  • TrueType, Type1 and support coding
  • Page compression

The scripts section is available and provides some useful extensions.

PHPMailer

A full-featured email creation and transfer class for PHP. Check on GitHub.

Why you might need it

Many PHP developers need to send email from their code. The only PHP function that supports this directly is mail(). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments.

The PHP mail() function usually sends via a local mail server, typically fronted by a sendmail binary on Linux, BSD, and macOS platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP client allows email sending on all platforms without needing a local mail server. Be aware though, that the mail() function should be avoided when possible; it's both faster and safer to use SMTP to localhost.

A Simple Example

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';

// Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;   // Enable verbose debug output
    $mail->isSMTP();   // Send using SMTP
    $mail->Host = 'smtp.example.com';   // Set the SMTP server to send through
    $mail->SMTPAuth = true;   // Enable SMTP authentication
    $mail->Username = 'user@example.com';   // SMTP username
    $mail->Password = 'secret';   // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;   // Enable implicit TLS encryption
    $mail->Port = 465;   // TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    // Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');   // Add a recipient
    $mail->addAddress('ellen@example.com');   // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    // Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');   // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');   // Optional name

    // Content
    $mail->isHTML(true);   // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: {$mail->ErrorInfo}';
}
                                    

Absolute Path

Simple one line PHP script to find the absolute path of the directory on web server.


<?php echo getcwd(); ?>
                                    

Manipulate JSON

JSON is the string notation of JavaScript object. It takes up simple to complex forms and stores data as (key, value) pairs.
This is the example of a json file:


[
    {
        "Code": "1",
        "Name": "June Zupers",
        "Sports": "Base Ball"
    },
    {
        "Code": "2",
        "Name": "Fred Cortez",
        "Sports": "Soccer"
    },
    {
        "Code": "3",
        "Name": "Kevin Burks",
        "Sports": "Tennis"
    }
]
                                        

Read JSON File in PHP

To read json file with php, you must first get the json data stored in the file, decode json and finally parse through the array or object.
For that you'll need two php functions - one is file_get_contents() and the other is json_decode().


// load file
$data = file_get_contents('results.json');

// decode json to associative array
$json_arr = json_decode($data, true);

foreach ($json_arr as $key => $value) {
    echo $json_arr[$key] . " - " . $json_arr[$value] . "<br/>";
}
                                    

If you know the specific key name, then you can simply access it like this:


echo $json_arr[0]['Code'];
                                    

Note: The function json_decode() decodes the given json string into an array or object. For example the statement json_decode($data, true); in above code will return associative array. You can ignore the second parameter 'true' to make it return as an object.

Add to JSON File in PHP

To add additional records to json file you have to simply append it to the end of file. Here let's see an example for adding new data. The following php snippet takes up a json file, decode it, add extra records and again encode to json and save it into a new file.


// read json file
$data = file_get_contents('results.json');

// decode json
$json_arr = json_decode($data, true);

// add data
$json_arr[] = array('Code'=>4, 'Name'=>'Jeff Darwin', 'Sports'=>'Cricket');

// encode json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
                                    
Update JSON File in PHP

As for updating json file you can either modify single value or in bulk. Here's an example for modifying value for a specific json attribute.


// read file
$data = file_get_contents('results.json');

// decode json to array
$json_arr = json_decode($data, true);

foreach ($json_arr as $key => $value) {
    if ($value['Code'] == '2') {
        $json_arr[$key]['Sports'] = "Foot Ball";
    }
}

// encode array to json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
                                    
Delete JSON Data from File in PHP

JSON deletion is little complex since it is easy to mess up doing the process. You must be clear what you need to delete first, a specific key pair from all rows or a complete row.


// read json file
$data = file_get_contents('results.json');

// decode json to associative array
$json_arr = json_decode($data, true);

// get array index to delete
$arr_index = array();
foreach ($json_arr as $key => $value) {
    if ($value['Code'] == "2") {
        $arr_index[] = $key;
    }
}

// delete data
foreach ($arr_index as $i) {
    unset($json_arr[$i]);
}

// rebase array
$json_arr = array_values($json_arr);

// encode array to json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
                                    

The deletion script uses two foreach loops. The first one is for determining the array index we need to delete from json.
And the second is what actually deletes from array using unset() function.
Finally it rebases the array, encode it to json and store it in a new file.