PHP Programming – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Sun, 12 Jun 2022 07:53:00 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg PHP Programming – Shishir Kant Singh https://shishirkant.com 32 32 187312365 CSS BACKGROUND https://shishirkant.com/css-background%ef%bf%bc/?utm_source=rss&utm_medium=rss&utm_campaign=css-background%25ef%25bf%25bc Sun, 12 Jun 2022 07:52:04 +0000 https://shishirkant.com/?p=2862 CSS background properties are used to style background of HTML element.There are 5 different CSS background property:

  1. CSS background color
  2. CSS background image
  3. background repeat
  4. background attachment
  5. CSS background position

Background Color

The background-color property is used to set the background color of an element.

The following example demonstrates how to set the background color of the whole page.

Example

body {
    background-color: #f0e68c;
}

Color values in CSS are most often specified in the following formats:

  • a color name – like “red”
  • a HEX value – like “#ff0000”
  • an RGB value – like “rgb(255, 0, 0)”

Please check out the tutorial on CSS color to learn more about specifying color values.


Background Image

The background-image property set an image as a background of an HTML element.

Let’s check out the following example which sets the background image for the whole page.

Example

body {
    background-image: url("images/tile.png");
}

Note: When applying the background image to an element, make sure that the image you choose does not affect the readability of the element’s text content.

Tip: By default browser repeats or tiles the background image both horizontally and vertically to fill the entire area of an element. You can control this with background-repeat property.


Background Repeat

The background-repeat property allows you to control how a background image is repeated or tiled in the background of an element. You can set a background image to repeat vertically (y-axis), horizontally (x-axis), in both directions, or in neither direction.

Let’s try out the following example which demonstrates how to set the gradient background for a web page by repeating the sliced image horizontally along the x-axis.

Example

body {
    background-image: url("images/gradient.png");
    background-repeat: repeat-x;
}

Similarly, you can use the value repeat-y to repeat the background image vertically along the y-axis, or the value no-repeat to prevent the repetition altogether.

Example

body {
    background-image: url("images/texture.png");
    background-repeat: no-repeat;
}

Let’s take a look at the following illustration to understand how this property actually works.

Background Repeat Illustration

Background Position

The background-position property is used to control the position of the background image.

If no background position has been specified, the background image is placed at the default top-left position of the element i.e. at (0,0), let’s try out the following example:

Example

body {
    background-image: url("images/robot.png");
    background-repeat: no-repeat;
}

In the following example, the background image is positioned at top-right corner.

Example

body {
    background-image: url("images/robot.png");
    background-repeat: no-repeat;
    background-position: right top;
}

Note: If two values are specified for the background-position property, the first value represents the horizontal position, and the second represents the vertical position. If only one value is specified, the second value is assumed to be center.

Besides keywords, you can also use percentage or length values, such as px or em for this property.

Let’s take a look at the following illustration to understand how this property actually works.

Background Position Illustration

Background Attachment

The background-attachment property determines whether the background image is fixed with regard to the viewport or scrolls along with the containing block.

Let’s try out the following example to understand how it basically works:

Example

body {
    background-image: url("images/bell.png");
    background-repeat: no-repeat;
    background-attachment: fixed;
}

The Background Shorthand Property

As you can see in the examples above, there are many properties to consider when dealing with the backgrounds. However, it is also possible to specify all these properties in one single property to shorten the code or avoid extra typing. This is called a shorthand property.

The background property is a shorthand property for setting all the individual background properties, i.e., background-colorbackground-imagebackground-repeatbackground-attachment and the background-position property at once. Let’s see how this works:

Example

body {
    background-color: #f0e68c;
    background-image: url("images/smiley.png");
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: 250px 25px;
}

Using the shorthand notation the above example can be written as:

Example

body {
    background: #f0e68c url("images/smiley.png") no-repeat fixed 250px 25px;
}

When using the background shorthand property the order of the property values should be.

background: color image repeat attachment position;

If the value for an individual background property is missing or not specified while using the shorthand notation, the default value for that property will be used instead, if any.

]]>
2862
PHP Filesystem Functions https://shishirkant.com/php-filesystem-functions/?utm_source=rss&utm_medium=rss&utm_campaign=php-filesystem-functions Tue, 26 May 2020 16:52:52 +0000 http://shishirkant.com/?p=872 PHP has a rich set of functions for working with files and directories. PHP contains both low-level and high-level filesystem functions. The fopen() function is an example of a low-level function; it is a thin wrapper of a similar C function. The file() function is an example of a high-level PHP filesystem function.

PHP file size and type

The filesize() function returns the size of the given file. The size is specified in bytes.

get_filesize.php

<?php

$filename = "fruits.txt";

$fsize = filesize($filename);

echo "The file size is: $fsize bytes\n";
?>

In the example, we determine the size of the fruits.txt file. The file is located in the current working directory, that is, in the same directory as the PHP script.

$ php get_filesize.php
The file size is: 40 bytes

The size of the fruits.txt file is 40 bytes.

The filetype() function gets the type of a file. The possible return values are: fifochardirblocklinkfilesocket and unknown.

file_types.php

<?php

echo filetype("myfile") . PHP_EOL;
echo filetype(".") . PHP_EOL;
echo filetype("/dev/tty1") . PHP_EOL;
echo filetype("/var/run/cups/cups.sock") . PHP_EOL;
?>

The script determines the types of four files.

$ php file_types.php
file
dir
char
socket

The four files are a regular file, directory, character device, and socket.


PHP check file existence

It may happen that we want to work with a file that does not exist. The file_exists() function can be used to prevent this.

file_existence.php

<?php

if ($argc != 2) {

    exit("Usage: file_existence.php filename\n");
}

$filename = $argv[1];

$r = file_exists($filename);

if (!$r) {

    exit("Cannot determine the size of the file; the file does not exist\n");
}

$fsize = filesize($filename);

echo "The file size is: $fsize bytes\n";
?>

This script checks for the existence of a given file before it computes its size.

if ($argc != 2) {

    exit("Usage: file_existence.php filename\n");
}

The $argc is a special variable which contains the number of arguments passed to script. We expect two arguments: a script name and another filename passed as a parameter.

$filename = $argv[1];

The $argv is an array of arguments passed to the script. We get the second element.

$r = file_exists($filename);

if (!$r) {

    exit("Cannot determine the size of the file; the file does not exist\n");
}

We check if the file exists with the file_exists() function. If it does not exist, we terminate the script with a message.

$ php file_existence.php fruits.txt
The file size is: 40 bytes

This is a sample output of the file_existence.php script.

In the following example we create a new file, delete it, and check for its existence. The touch() function sets access and modification time of a file. If the file does not exist, it is created. The unlink() function deletes a file.

file_existence2.php

<?php

$filename = "newfile.txt";

if (file_exists($filename)) {

    echo "The file $filename exists\n";

} else {

    echo "The file $filename does not exist\n";

    $r = touch($filename);

    if (!$r) {

        exit("Failed to touch $filename file\n");
    } else {

        echo "The file $filename has been created\n";
    }
}


$r = unlink($filename);

if ($r) {

    echo "The file $filename was deleted\n";
} else {

    exit("Failed to delete $filename file\n");
}

if (file_exists($filename)) {

    echo "The file $filename exists\n";
} else {

    echo "The file $filename does not exist\n";
}
?>

In the code example, we utilize all the three functions: file_exists()touch(), and unlink().

$r = touch($filename);

The touch() function is used to create a new file called newfile.txt.

if (!$r) {

    exit("Failed to touch $filename file\n");
} else {

    echo "The file $filename has been created\n";
}

An error message is printed if the touch() function fails. Many PHP functions return a false value when they fail.

$r = unlink($filename);

The unlink() function deletes the file.

$ php file_existence2.php
The file newfile.txt does not exist
The file newfile.txt has been created
The file newfile.txt was deleted
The file newfile.txt does not exist

This is the output of the file_existence2.php.


PHP copy and rename files

The copy() function copies a file, and the rename() renames a file. If the destination file already exists, it will be overwritten.

copy_file.php

<?php

$r = copy("myfile.txt", "myfile2.txt");

if ($r) {

    echo "Successfully copied file\n";
} else {

    exit("Failed to copy file\n");
}

The script copies a file.rename_file.php

<?php

$r = rename("myfile2.txt", "myfile_back.txt");

if ($r) {

    echo "Successfully renamed file\n";
} else {

    exit("Failed to rename file\n");
}
?>

In this script, we rename the myfile2.txt file to myfile_back.txt with the rename() function.


E_WARNING

Some of the filesystem functions issue an E_WARNING on failure. It is a run-time warning (non-fatal error). The execution of the script is not halted.

PHP is not consistent in this area; not all filesystem functions issue this warning—most functions only return an error value when they fail.

custom_error_handler.php

<?php

set_error_handler("mywarning_handler", E_WARNING);

$r = unlink('image1.png');

if ($r) {

    echo "File successfully deleted\n";
}

function mywarning_handler($errno, $errstr) {

    echo "Failed to delete file\n";
    echo "$errstr: $errno\n";
}
?>

In the script, we delete a file and provide a custom error handler.

set_error_handler("mywarning_handler", E_WARNING);

A custom error handler is set with the set_error_handler() function.

function mywarning_handler($errno, $errstr) {

    echo "Failed to delete file\n";
    echo "$errstr: $errno\n";
}

The handler receives an error number and an error string as parameters.

$ php custom_error_handler.php
Failed to delete file
unlink(image1.png): No such file or directory: 2

The custom_error_handler.php gives this output when there is no image1.png to delete.


PHP directories

The dirname() function returns the parent directory’s path. Since PHP 7, we can provide an optional levels parameter which tells the number of parent directories to go up.

parent_directories.php

<?php

$home_dir = getenv("HOME");

echo dirname($home_dir). PHP_EOL;
echo dirname("/etc/") . PHP_EOL;
echo dirname(".") . PHP_EOL;
echo dirname("/usr/local/lib", 2) . PHP_EOL;
?>

In the script, we print the parent directory of four directories.

$home_dir = getenv("HOME");

We use the getenv() function to get the current user’s home directory.

echo dirname($home_dir). PHP_EOL;

This line prints the parent directory of the user’s home directory.

echo dirname(".") . PHP_EOL;

Here, we print the parent directory of the current working directory.

echo dirname("/usr/local/lib", 2) . PHP_EOL;

In this line we print the second parent directory of the /usr/local/lib directory.

$ php parent_directories.php
/home
/
.
/usr

This is the output of the parent_directories.php.

The getcwd() function returns the current working directory, and the chdir() function changes the current working directory to a new directory.

current_directory.php

<?php

$cd = getcwd();

echo "Current directory:" . $cd . PHP_EOL;

chdir("..");

$cd2 = getcwd();

echo "Current directory:" . $cd2 . PHP_EOL;
?>

The script works with getcmd() and chdir() functions.

$ php current_directory.php
Current directory:/home/janbodnar/prog/phpfiles
Current directory:/home/janbodnar/prog

This is a sample output of the script.


PHP listing directories

In the following five examples, we list the contents of directories. There are several approaches to do this task.

list_dir1.php

<?php

$folder = '/home/janbodnar/prog';
$fh = opendir($folder);

if ($fh === false) {

    exit("Cannot open directory\n");
}

while (false !== ($entry = readdir($fh))) {
    echo "$entry\n";
}

closedir($fh);
?>

The opendir() function opens a directory handle. The readdir() function reads an entry from the directory handle. The handle of the directory is closed with the closedir() function at the end of the script.

The is_dir() function tells whether the filename is a directory, and the is_file() function tells whether the filename is a file.

list_dir2.php

<?php

$folder = '/home/janbodnar/prog/';

$fh = opendir($folder);

if ($fh === false) {

    exit("Cannot open directory\n");
}

$dirs = [];
$files = [];

while (false !== ($entry = readdir($fh))) {

    if (is_dir($folder . '/' . $entry)) {

        array_push($dirs, $entry);
    }

    if (is_file($folder . '/' . $entry)) {

        array_push($files, $entry);
    }
}

echo "Directories:\n";

foreach ($dirs as $dr) {
    echo "$dr\n";
}

echo "Files:\n";

foreach ($files as $myfile) {
    echo "$myfile\n";
}

closedir($fh);
?>

In the second example we divide the entries into subdirectories and files. The script first prints the subdirectories and then the files of the examined directory.

if (is_dir($folder . '/' . $entry)) {

    array_push($dirs, $entry);
}

It is necessary to provide the full path of the directory to the is_dir() function.

The glob() function finds pathnames matching a pattern.

list_dir3.php

<?php

foreach (glob('/home/janbodnar/*', GLOB_ONLYDIR) as $dir) {

    echo "$dir\n";
}
?>

With the GLOB_ONLYDIR flag, the glob() function returns only directory entries which match the pattern.

The scandir() is a high-level function to list files and directories inside the specified path. The function returns an array of files and directories from the directory.

list_dir4.php

<?php

$files = scandir('.', SCANDIR_SORT_DESCENDING);

print_r($files);
?>

The script prints the array of files and subdirectories of the current working directory. The SCANDIR_SORT_DESCENDING flag sorts the entries in descending alphabetical order.

In the previous examples, we have listed only the contents of one directory; we did not include the elements of the subdirectories. With the RecursiveDirectoryIterator and RecursiveIteratorIterator classes we can easily iterate over filesystem directories using recursion. In other words, we iterate over all subdirectories until all items in the directory tree are listed.

list_dir5.php

<?php

$folder = '/home/janbodnar/prog/';

$rdi = new RecursiveDirectoryIterator($folder);
$rii = new RecursiveIteratorIterator($rdi);

foreach ($rii as $filename) {

    echo "$filename\n";
}
?>

The script prints all items of the given directory for all levels of depth.


PHP paths

A path is the fully specified name of a computer file, including the position of the file in the file system’s directory structure. The realpath() function returns a canonical absolute pathname, and the basename() function returns the trailing name component of the path.

paths.php

<?php

echo realpath("myfile.txt") . PHP_EOL;

echo basename("/home/janbodnar/prog/phpfiles/myfile.txt") . PHP_EOL;
echo basename("/home/janbodnar/prog/phpfiles/myfile.txt", ".txt") . PHP_EOL;
?>

This script uses the realpath() and the basename() functions.

echo basename("/home/janbodnar/prog/phpfiles/myfile.txt", ".txt") . PHP_EOL;

If we specify the second parameter, the suffix name, it will be also removed from the path name.

$ php paths.php
/home/janbodnar/prog/phpfiles/myfile.txt
myfile.txt
myfile

This is the output of the paths.php example.

The pathinfo() function returns information about a file path.

path_info.php

<?php

$path_parts = pathinfo('myfile.txt');

echo $path_parts['dirname'] . PHP_EOL;
echo $path_parts['basename'] . PHP_EOL;
echo $path_parts['extension'] . PHP_EOL;
echo $path_parts['filename'] . PHP_EOL;
?>

The function returns an associative array containing the following elements: dirname, basename, extension (if any), and filename.

$ php path_info.php
.
myfile.txt
txt
myfile

This is the output.


PHP create file

The fopen() function opens a file or an URL. The first parameter of the function is the file name and the second is the mode in which we open the window. For instance, the 'r' mode opens for reading only and 'w' for writing only. If we open a file in a 'w' mode and it does not exist, it is created. The list of modes can be found at PHP manual for fopen().

The fopen() returns a handle to the file. This is an object that is used to manipulate the file; for instance, we pass it to the fwrite() function to write to the file.

create_file.php

<?php

$filename = "names.txt";

if (file_exists($filename)) {

    exit("The file already exists\n");
}

$fh = fopen($filename, 'w');

if ($fh === false) {

    exit("Cannot create file\n");
}

echo "Successfully created file\n";

fclose($fh);

The example creates a new file called names.txt.

if (file_exists($filename)) {

    exit("The file already exists\n");
}

First, we check if the file exists.

$fh = fopen('names.txt', 'w');

The names.txt file is created and a handle to this file is returned.

fclose($fh);
?>

We close the file handle with the fclose() function.


PHP read file

In the next examples, we will read file contents.

The fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as the length bytes have been read or the EOF (end of file) is reached.

read_file.php

<?php

$fh = fopen('balzac.txt', 'r');

if ($fh === false) {

    exit("Cannot open file for reading\n");
}

while (!feof($fh)) {

    $chunk = fread($fh, 1024);

    if ($chunk === false) {

        exit("Cannot read from file\n");
    }

    echo $chunk;
}

fclose($fh);
?>

The example reads the entire file with the fread() function and outputs it into the console.

while (!feof($fh)) {

    $chunk = fread($fh, 1024);

    if ($chunk === false) {

        exit("Cannot read from file\n");
    }

    echo $chunk;
}

The feof() tests for end-of-file on a file pointer. The fread() reads the file per 1 KB chunk until the EOF is reached.

$ php read_file.php balzac.txt
Honoré de Balzac, (born Honoré Balzac, 20 May 1799 – 18 August 1850)
was a French novelist and playwright. His magnum opus was a sequence
of short stories and novels collectively entitled La Comédie Humaine,
which presents a panorama of French life in the years after the 1815
Fall of Napoleon Bonaparte.

This is the output of the read_file.php example.

In the second example, we utilize the fgets() function, which reads one line from the file handle.

read_file2.php

<?php

$fh = fopen('balzac.txt', 'r');

if ($fh === false) {

    exit("Cannot open file for reading\n");
}

while (!feof($fh)) {

    $line = fgets($fh);

    if ($line === false) {

        exit("Cannot read from file\n");
    }

    echo $line;
}

fclose($fh);
?>

The example reads the contents of the balzac.txt file one by line.

The file() is a high-level function which reads an entire file into an array.

read_file3.php

<?php

$lines = file('balzac.txt');

if ($lines === false) {

    exit("Cannot read file\n");
}

foreach ($lines as $line) {

    echo $line;
}
?>

In this example, we read the whole file in one shot with the file() function. We traverse the returned array with a foreach loop.

The file_get_contents() is another high-level function which reads the entire file into a string.

read_file4.php

<?php

$content = file_get_contents('balzac.txt');

if ($content === false) {

    exit("Cannot read file\n");
}

echo "$content";
?>

The example reads the entire file in one shot with the file_get_contents() function. It returns the data in a string.


PHP reading formatted data

The fscanf() function parses input from a file according to a format. Each call to fscanf() reads one line from the file.

$ cat items.txt
coins 5
pens 6
chairs 12
books 20

We are going to parse the items.txt file.

read_formatted_data.php

<?php

$fh = fopen("items.txt", "r");

if ($fh === false) {

    exit("Cannot read file\n");
}

while ($data = fscanf($fh, "%s %d")) {

    list($item, $quantity) = $data;
    echo "$item: $quantity\n";
}

fclose($fh);
?>

The fscanf() function takes format specifiers to read a string and a number.


PHP reading web page

The PHP filesystem functions can be also used to read web pages.

read_page.php

<?php

$ph = fopen("http://webcode.me", "r");

if ($ph === false) {

    exit("Failed to open stream to URL\n");
}

while (!feof($ph)) {

    $buf = fread($ph, 1024);

    if ($buf === false) {

        exit("Cannot read page\n");
    }

    echo $buf;
}

fclose($ph);
?>

We read a page from a small website wecode.me.

$ph = fopen("http://webcode.me", "r");

With the fopen() function, we open a handle to a web page.

while (!feof($ph)) {

    $buf = fread($ph, 1024);

    if ($buf === false) {

        exit("Cannot read page\n");
    }

    echo $buf;
}

We read the web page until its end; the feof() is used to test the end of the web page. The page is read in 1 KB chunks with the fread() function.

$ php read_page.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My html page</title>
</head>
<body>

    <p>
        Today is a beautiful day. We go swimming and fishing.
    </p>

    <p>
         Hello there. How are you?
    </p>

</body>
</html>

This is the output of the read_page.php script.

The following example uses a high-level function to read the same web page.

read_page2.php

<?php

$page = file_get_contents('http://webcode.me');

if ($page === false) {

    exit("Cannot read page\n");
}

echo $page;
?>

The file_get_contents() reads the whole web page in one shot.

The fgetss() function reads a line from a file handle and strips HTML tags.

read_page3.php

<?php

$ph = fopen("http://webcode.me", "r");

if ($ph === false) {

    exit("Failed to open stream to URL\n");
}

while (!feof($ph)) {

    $buf = fgetss($ph, 1024);

    if ($buf === false) {

        exit("Cannot read from page\n");
    }

    echo trim($buf);
}

fclose($ph);
?>

We read the contents of the webcode.me web page and strip its HTML tags.

echo trim($buf);

The trim() function removes the leading and trailing spaces.

$ php read_page3.php
My html pageToday is a beautiful day. We go swimming and fishing.Hello there. How are you?

This is the output of the example; the output contains the title and the text in the body of the page.


PHP write to file

The fwrite() function writes a string to a file referenced by a file handle.

write_file.php

<?php

$fh = fopen('names.txt', 'w');

if ($fh === false) {

    exit("Cannot open file\n");
}

$r = fwrite($fh, 'Jane' . PHP_EOL);
check_retval($r);

$r = fwrite($fh, 'Lucy' . PHP_EOL);
check_retval($r);

$r = fwrite($fh, 'Mark' . PHP_EOL);
check_retval($r);

$r = fwrite($fh, 'Lubos' . PHP_EOL);
check_retval($r);

fclose($fh);

function check_retval($val) {

    if ($val === false) {

        exit("Cannot write to file\n");
    }
}
?>

We open a names.txt in the write mode and write four lines into it.

$fh = fopen('names.txt', 'w');

The fopen() function opens the file in the write mode. If the file does not exist, it is automatically created.

$r = fwrite($fh, 'Jane' . PHP_EOL);

With the fwrite() function we write a line to the file. The function takes the file handle as its first parameter.

$ php write_file.php
$ cat names.txt
Jane
Lucy
Mark
Lubos

We write to the names.txt file and check its contents.

We can write a string to a file in one shot with the high-level file_put_contents() method.

write_file2.php

<?php

$filename = "names.txt";

$buf = file_get_contents($filename);

if ($buf === false) {

    exit("Cannot get file contents\n");
}

$buf .= "John\nPaul\nRobert\n";

$r = file_put_contents($filename, $buf);

if ($r === false) {

    exit("Cannot write to file\n");
}
?>

In the example, we read the contents of the names.txt file with the file_get_contents() function and append new string with the file_put_contents() function.

PHP readable, writable, executable file

The is_readable()is_writable(), and is_executable() functions check if the file is readable, writable, and executable.

rwe.php

<?php

$filename = "myfile.txt";

echo get_current_user() . PHP_EOL;

if (is_readable($filename)) {

    echo "The file can be read\n";
} else {

    echo "Cannot read file\n";
}

if (is_writable($filename)) {

    echo "The file can be written to\n";
} else {

    echo "Cannot write to file\n";
}

if (is_executable($filename)) {

    echo "The file can be executed\n";
} else {

    echo "Cannot execute file\n";
}
?>

We run the three functions on the myfile.txt file. The script check these attributes for the current user.

$ php rwe.php
janbodnar
The file can be read
The file can be written to
Cannot execute file

The file can be read and written to but not executed for the janbodnar user.


PHP file times

There are three kinds of file times on Linux: last access time, last change time, and last modification time. The following PHP functions determine these times: fileatime()filectime(), and filemtime().

file_times.php

<?php

$filename = "myfile.txt";

$atime =  fileatime($filename);
$ctime =  filectime($filename);
$mtime =  filemtime($filename);

echo date("F d, Y H:i:s\n", $atime);
echo date("F d, Y H:i:s\n", $ctime);
echo date("F d, Y H:i:s\n", $mtime);
?>

The script prints the file times for the myfile.txt file.

$ php file_times.php
April 20, 2016 17:52:54
April 20, 2016 17:53:33
April 20, 2016 17:52:29

This is a sample output of the file_times.php script.


PHP file permissions

Filesystems enforce permissions on files for different users and groups of users. The fileperms() function gets file permissions; it returns the file’s permissions as a numeric mode.

file_permissions.php

<?php

$perms = fileperms("myfile.txt");

echo decoct($perms & 0777) . PHP_EOL;

$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
            (($perms & 0x0800) ? 's' : 'x' ) :
            (($perms & 0x0800) ? 'S' : '-'));

$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
            (($perms & 0x0400) ? 's' : 'x' ) :
            (($perms & 0x0400) ? 'S' : '-'));

$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
            (($perms & 0x0200) ? 't' : 'x' ) :
            (($perms & 0x0200) ? 'T' : '-'));

echo "$info\n";
?>

The script determines the file permissions for myfile.txt. The permissions are printed to the console in the Unix style.

echo decoct($perms & 0777) . PHP_EOL;

The permissions on Unix are traditionally written in octal representation. The decoct() function translates decimal representation to octal.

$info .= (($perms & 0x0100) ? 'r' : '-');

In this line, we check if the file permissions allow the owner of the file to read it.

$ php file_permissions.php
660
rw-rw----

This is a sample output of the file_permissions.php script.

File permissions can be changed with the chmod() function.

file_permissions2.php

<?php

$perms1 = fileperms("myfile.txt");

echo decoct($perms1 & 0777) . PHP_EOL;

$r = chmod("myfile", 0660);

if ($r) {

    echo "File mode successfully changed\n";
} else {

    exit("Failed to change file mode\n");
}

$perms2 = fileperms("myfile");

echo decoct($perms2 & 0777) . PHP_EOL;

?>

The script changes the permissions for the myfile.txt file.

$r = chmod("myfile", 0660);

The chmod function accepts permissions as an octal value in its second parameter. Octal values are preceded with 0.

$ php file_permissions2.php
664
File mode successfully changed
660

The permissions of the file were changed from 664 to 660.


PHP CSV file format

The fgetcsv() function reads one line from a CSV (comma-separated value) file; it returns an indexed array containing the fields read. The fputcsv() function formats one line as CSV and writes it to a file.

csv_output.php

<?php

$nums = [1, 2, 5, 3, 2, 6, 4, 2, 4,
    8, 7, 3, 8, 5, 4, 3];

$fh = fopen('numbers.csv', 'w');

if ($fh === false) {

    exit("Failed to open file\n");
}

$r = fputcsv($fh, $nums);

if ($r === false) {

    exit("Failed to write values\n");
}

echo "The values have been successfully written\n";

fclose($fh);
?>

This script writes numbers from an array into a CSV file.

$ php csv_output.php
The values have been successfully written
$ cat numbers.csv
1,2,5,3,2,6,4,2,4,8,7,3,8,5,4,3

We run the script and check the file contents.

In the following example, we read data from a CSV file.

csv_input.php

<?php

$fh = fopen('numbers.csv', 'r');

if ($fh === false) {

    exit("Failed to open file\n");
}

while (($data = fgetcsv($fh)) !== false) {

    $num = count($data);

    for ($i=0; $i < $num; $i++) {

        echo "$data[$i] ";
    }
}

echo "\n";

fclose($fh);
?>

The script reads values from the numbers.csv file using the fgetcsv() and prints them into the console.

$ php csv_input.php
1 2 5 3 2 6 4 2 4 8 7 3 8 5 4 3

This is the output of the csv_input.php script.


PHP disk space

The disk_total_space() function returns the total size of a filesystem or disk partition in bytes, and the disk_total_space() function returns available space on filesystem or disk partition in bytes.

disk_space.php

<?php

const BYTES_IN_GIGABYTE = 1073741824;

$total_space_bytes = disk_total_space("/");

if ($total_space_bytes === false) {

    exit("The disk_total_space() failed\n");
}

$free_space_bytes = disk_free_space("/");

if ($free_space_bytes === false) {

    exit("The disk_free_space() failed\n");
}

$total_space_gb = floor($total_space_bytes / BYTES_IN_GIGABYTE);
$free_space_gb = floor($free_space_bytes / BYTES_IN_GIGABYTE);

echo "Total space: $total_space_gb GB\n";
echo "Free space: $free_space_gb GB\n";
?>

The script computes the total and free space on a root partition. The space is translated into gigabytes.

$ php disk_space.php
Total space: 289 GB
Free space: 50 GB
]]>
872
PHP with MySQL https://shishirkant.com/php-with-mysql/?utm_source=rss&utm_medium=rss&utm_campaign=php-with-mysql Tue, 26 May 2020 16:33:05 +0000 http://shishirkant.com/?p=869 MySQL

MySQL is a leading open source database management system. It is a multiuser, multithreaded database management system. MySQL is especially popular on the web. It is one of the parts of the very popular LAMP platform. Linux, Apache, MySQL, and PHP. Currently MySQL is owned by Oracle. MySQL database is available on most important OS platforms. It runs on BSD Unix, Linux, Windows, or Mac OS.


PHP mysqli

The MySQLi Extension (MySQL Improved) is a relational database driver used in the PHP scripting language to provide an interface with MySQL databases. It provides both object oriented and procedural APIs. Other ways to interact with MySQL are: PDO and ORM solutions.

The pdo_mysql PHP Data Objects module is a database abstraction layer for PHP applications. This module is beneficial if we write portable database PHP scripts.

There are also ORM solutions for working with MySQL in PHP such as Doctrine or Eloquent.

PHP mysqli version

In the following example, we determine the version of the MySQL database.

version.php

<?php

$con = new mysqli("localhost", "dbuser", "s$cret", "mydb");

if ($con->connect_errno) {

    printf("connection failed: %s\n", $con->connect_error());
    exit();
}

$res = $con->query("SELECT VERSION()");

if ($res) {

    $row = $res->fetch_row();
    echo $row[0];
}

$res->close();
$con->close();
?>

The example prints the version of MySQL.

$con = new mysqli("localhost", "root", "andrea", "mydb");

A connection to the database is created. The mysqli class takes the hostname, username, password, and database name as arguments.

if ($con->connect_errno) {

    printf("connection failed: %s\n", $con->connect_error());
    exit();
}

The connect_errno contains the error code value if the connection attempt failed. It has zero if no error occurred. The connect_error() method returns the string description of the last connect error.

$res = $con->query("SELECT VERSION()");

The query() method performs a query on the database. The SELECT VERSION() statement returns the version of MySQL.

if ($res) {

    $row = $res->fetch_row();
    echo $row[0];
}

The fetch_row() returns a result row as an enumerated array. Our result contains only one value.

$res->close();
$con->close();

In the end, we release the resources.

$ php version.php
10.1.36-MariaDB

This is a sample output.

The mysqli driver also supports procedural style of programming.

version2.php

<?php

$con = mysqli_connect("localhost", "dbuser", "s$cret", "mydb");

if (mysqli_connect_errno()) {

    printf("connection failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT VERSION()";

$res = mysqli_query($con, $query);

if ($res) {

    $row = mysqli_fetch_row($res);
    echo $row[0];
}

mysqli_free_result($res);
mysqli_close($con);
?>

The example returns the version of MySQL with procedural functions.


PHP mysqli create table

The following example creates a new database table. A table is created with the CREATE TABLE statement. Rows are added to the table with the INSERT INTO statements.

create_table.php

<?php

$host = "localhost";
$user = "dbuser";
$passwd = "s$cret";
$db = "mydb";

function execute_query($query, $con)
{
    $res = $con->query($query);

    if (!$res) {

        echo "failed to execute query: $query\n";
    } else {
        echo "Query: $query executed\n";
    }

    if (is_object($res)) {

        $res->close();
    }
}

$con = new mysqli($host, $user, $passwd, $db);

if ($con->connect_errno) {

    printf("connection failed: %s\n", $con->connect_error());
    exit();
}

$query = "DROP TABLE IF EXISTS cars";
execute_query($query, $con);

$query = "CREATE TABLE cars(id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255), price INT)";
execute_query($query, $con);

$query = "INSERT INTO cars(name, price) VALUES('Audi', 52642)";
execute_query($query, $con);

$query = "INSERT INTO cars(name, price) VALUES('Mercedes', 57127)";
execute_query($query, $con);

$query = "INSERT INTO cars(name, price) VALUES('Skoda', 9000)";
execute_query($query, $con);

$query = "INSERT INTO cars(name, price) VALUES('Volvo', 29000)";
execute_query($query, $con);

$query = "INSERT INTO cars(name, price) VALUES('Bentley', 350000)";
execute_query($query, $con);

$query = "INSERT INTO cars(name, price) VALUES('Citroen', 21000)";
execute_query($query, $con);

$query = "INSERT INTO cars(name, price) VALUES('Hummer', 41400)";
execute_query($query, $con);

$query = "INSERT INTO cars(name, price) VALUES('Volkswagen', 21600)";
execute_query($query, $con);

$con->close();
?>

The example creates the cars table with eight rows.


PHP mysqli prepared statements

When we write prepared statements, we use placeholders instead of directly writing the values into the statements. Prepared statements increase security and performance. In mysqli, the prepare() function prepares an SQL statement for execution.

prepared_statement.php

<?php

$host = "localhost";
$user = "dbuser";
$passwd = "s$cret";
$db = "mydb";

$con = new mysqli($host, $user, $passwd, $db);

if ($con->connect_errno) {

    printf("connection failed: %s\n", $con->connect_error());
    exit();
}

$id = 3;

$query = "SELECT id, name, price FROM cars WHERE id = ?";

if ($stmt = $con->prepare($query)) {

    $stmt->bind_param('i', $id);

    $stmt->execute();
    $stmt->bind_result($row_id, $name, $price);
    $stmt->fetch();

    echo "$row_id $name $price\n";

    $stmt->close();
} else {

    echo "failed to fetch data\n";
}

$con->close();
?>

The example selects a specific row from the table. It uses a prepared statement.

$query = "SELECT id, name, price FROM cars WHERE id = ?";

When we write prepared statements, we use placeholders instead of directly writing the values into the statements. Prepared statements are faster and guard against SQL injection attacks. The ? is a placeholder, which will be filled later. In our case we have one value: an integer id.

$stmt->bind_param('i', $id);

The value of the $id variable is bound to the placeholder with the bind_param() method. The first parameter specifies the variable type; it is integer in our case.

$stmt->execute();

The statement is executed.

$stmt->bind_result($row_id, $name, $price);

The bind_result() binds the returned values to the specified variables.

echo "$row_id $name $price\n";

We print the variables to the terminal.

$con->close();

We close the statement.

$ php prepared_statement.php
3 Skoda 9000

This is the output.


PHP mysqli fetch_row

The fetch_row() method fetches one row of data from the result set and returns it as an enumerated array. Each column is stored in an array offset starting from 0. Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.

fetch_rows.php

<?php

$host = "localhost";
$user = "dbuser";
$passwd = "s$cret";
$db = "mydb";

$con = new mysqli($host, $user, $passwd, $db);

if ($con->connect_errno) {

    printf("connection failed: %s\n", $con->connect_error());
    exit();
}

$query = "SELECT * FROM cars";

if ($res = $con->query($query)) {

    printf("Select query returned %d rows.\n", $res->num_rows);

    while ($row = $res->fetch_row())
    {
        printf("%s %s %s\n", $row[0], $row[1], $row[2]);
    }

    $res->close();
} else {

    echo "failed to fetch data\n";
}

$con->close();
?>

The example returns all rows from the cars table.

$query = "SELECT * FROM cars";

This SELECT query selects all rows from the table.

if ($res = $con->query($query)) {

We execute the SELECT query with the query() method.

printf("Select query returned %d rows.\n", $res->num_rows);

The number of returned rows is stored in the num_rows attribute.

while ($row = $res->fetch_row())
{
    printf("%s %s %s\n", $row[0], $row[1], $row[2]);
}

With the fetch_row() in a while loop, we fetch all rows from the table.

$ php fetch_rows.php
Select query returned 8 rows.
1 Audi 52642
2 Mercedes 57127
3 Skoda 9000
4 Volvo 29000
5 Bentley 350000
6 Citroen 21000
7 Hummer 41400
8 Volkswagen 21600

This is the output.


PHP mysqli fetch_assoc

The fetch_assoc() returns an associative array of strings representing the fetched row in the result set. Each key in the array represents the name of one of the result set’s columns or NULL if there are no more rows in result set.

fetch_rows2.php

<?php

$host = "localhost";
$user = "dbuser";
$passwd = "s$cret";
$db = "mydb";

$con = new mysqli($host, $user, $passwd, $db);

if ($con->connect_errno) {

    printf("connection failed: %s\n", $con->connect_error());
    exit();
}

$query = "SELECT * FROM cars";

if ($res = $con->query($query)) {

    printf("Select query returned %d rows.\n", $res->num_rows);

    while ($row = $res->fetch_assoc())
    {
        printf("%s %s %s\n", $row['id'], $row['name'], $row['price']);
    }

    $res->close();
} else {

    echo "failed to fetch data\n";
}

$con->close();
?>

The example returns all rows from the cars table.

while ($row = $res->fetch_assoc())
{
    printf("%s %s %s\n", $row['id'], $row['name'], $row['price']);
}

When we use fetch_assoc(), we refer to the columns via array notation.


PHP mysqli fetch_object

The fetch_object() returns an object with string properties that correspond to the fetched row or NULL if there are no more rows in resultset.

fetch_rows3.php

<?php

$host = "localhost";
$user = "dbuser";
$passwd = "s$cret";
$db = "mydb";

$con = new mysqli($host, $user, $passwd, $db);

if ($con->connect_errno) {

    printf("connection failed: %s\n", $con->connect_error());
    exit();
}

$query = "SELECT * FROM cars";

if ($res = $con->query($query)) {

    printf("Select query returned %d rows.\n", $res->num_rows);

    while ($row = $res->fetch_object())
    {
        printf("%s %s %s\n", $row->id, $row->name, $row->price);
    }

    $res->close();
} else {

    echo "failed to fetch data\n";
}

$con->close();
?>

The example returns all rows from the cars table.

while ($row = $res->fetch_object())
{
    printf("%s %s %s\n", $row->id, $row->name, $row->price);
}

When we use fetch_object(), we refer to the columns via object access notation.


PHP mysqli column names

The next example prints column names with the data from the database table. We refer to column names as meta data.

column_names.php

<?php

$host = "localhost";
$user = "dbuser";
$passwd = "s$cret";
$db = "mydb";

$con = new mysqli($host, $user, $passwd, $db);

if ($con->connect_errno) {

    printf("connection failed: %s\n", $con->connect_error());
    exit();
}

$query = "SELECT * FROM cars";

if ($res = $con->query($query)) {

    $num_rows = $res->num_rows;
    $num_fields = $res->field_count;

    printf("Select query returned %d rows.\n", $num_rows);
    printf("Select query returned %d columns.\n", $num_fields);

    $fields = $res->fetch_fields();

    while ($row = $res->fetch_row()) {

        for ($i = 0; $i < $num_fields; $i++) {

            echo $fields[$i]->name . ": " . $row[$i] . "\n";
        }

        echo "*******************************\n";
    }

    $res->close();
} else {

    echo "failed to fetch data\n";
}

$con->close();
?>

The example prints all rows of the cars table with the column headers.

$num_rows = $res->num_rows;
$num_fields = $res->field_count;

The num_rows attribute returns the number of rows in the result. The field_count returns the number of fields in the result.

$fields = $res->fetch_fields();

The fetch_fields() method returns an array of objects representing the fields in a result set. These are the column names.

while ($row = $res->fetch_row()) {

    for ($i = 0; $i < $num_fields; $i++) {

        echo $fields[$i]->name . ": " . $row[$i] . "\n";
    }

    echo "*******************************\n";
}

We show the column names and the data.

$ php column_names.php
Select query returned 8 rows.
Select query returned 3 columns.
id: 1
name: Audi
price: 52642
*******************************
id: 2
name: Mercedes
price: 57127
*******************************
id: 3
name: Skoda
price: 9000
*******************************
...

This is the output.

]]>
869
PHP Object Oriented Programming -II https://shishirkant.com/php-object-oriented-programming-ii/?utm_source=rss&utm_medium=rss&utm_campaign=php-object-oriented-programming-ii Tue, 26 May 2020 15:47:33 +0000 http://shishirkant.com/?p=866 PHP static keyword

We can declare class properties and methods to be static. The static properties and methods do not belong to the instance of the class. They belong to the class itself. They are accessible through the scope resolution operator ::.

staticmethod.php

<?php

class Sys {

    public static function println($string) {
    
        echo "$string\n";
    }
}

Sys::println("PHP");
Sys::println("PERL");
Sys::println("Python");
Sys::println("Pike");
?>

In the above PHP script, we have a static println() method. It prints a string and starts a new line. This example is inspired by the Java language.

Sys::println("PHP");

We do not need an object to call println() method. We call static methods by specifying the class name, followed by double colon operator and the method name.

$ php static1.php 
PHP
PERL
Python
Pike

This is the output of the script.

staticvariable.php

<?php

class Math {

    public static $PI = 3.14159265359;
}

echo Math::$PI . "\n";
?>

And now we have an example with a static variable.

echo Math::$PI . "\n";

We access the variable by specifying the class name, followed by the scope resolution operator and the variable name.


PHP final keyword

Final methods cannot be overridden and final classes cannot be extended. The final keyword is a matter of design of the application. Some classes should not be extended and some methods should not be overridden. This behaviour is enforced by the final keyword.

finalmethod.php

<?php

class Base {

    final function say() {
        echo "Base class";
    }
}

class Derived extends Base {

    function say() {
        echo "Derived class";
    }
}
?>

This PHP script won’t compile. We get an error “Cannot override final method Base::say()”.

finalclass.php

<?php

final class Math {

    static function getPI() {
        return 3.141592;
    }
}

class DerivedMath extends Math {

    function say() {
        echo "DerivedMath class";
    }
}
?>

In the previous PHP script, we have a prototype base Math class. The sole purpose of this class is to provide some helpful methods and constants to the programmer. (In our case we have only one method for simplicity reasons.) It is not created to be extended. To prevent uninformed other programmers to derive from this class, the creators made the class final. If you try to run this PHP script, you get the following error: “Fatal error: Class DerivedMath may not inherit from final class (Math)”.


PHP deep copy vs shallow copy

Copying of data is an important task in programming. Object is a composite data type in OOP. Member field in an object may be stored by value or by reference. Copying may be performed in two ways.

shallow copy copies all values and references into a new instance. The data to which a reference is pointing is not copied; only the pointer is copied. The new references are pointing to the original objects. Any changes to the reference members affect both objects.

deep copy copies all values into a new instance. In case of members that are stored as references a deep copy performs a deep copy of data that is being referenced. A new copy of a referenced object is created, and the pointer to the newly created object is stored. Any changes to those referenced objects will not affect other copies of the object. Deep copies are fully replicated objects.

In PHP, we have a copy keyword which performs a shallow copy by default. It calls the object’s __clone() method. We can implement the method to create our custom deep copy. In PHP all objects are assigned by reference.

The next two examples perform a shallow and a deep copy on objects.

shallowcopy.php

<?php

class Object {

    public $id;
    public $size;
    public $color;

    function __construct($id, $size, $color) {
    
        $this->id = $id;
        $this->size = $size;
        $this->color = $color;
    }
}

class Color {

    public $red;
    public $green;
    public $blue;

    function __construct($red, $green, $blue) {
    
        $this->red = $red;
        $this->green = $green;
        $this->blue = $blue;
    }
}

$color = new Color(23, 42, 223);

$object1 = new Object(23, "small", $color);
$object2 = clone $object1;

$object2->id++;
$object2->color->red = 255;
$object2->size = "big";

print_r($object1);
print_r($object2);
?>

In the above PHP script, we define two custom objects: Object and Color. The Object object will have a reference to the Color object.

$color = new Color(23, 42, 223);

We create an instance of the Color object.

$object1 = new Object(23, "small", $color);

An instance of the Object object is created. It passes the instance of the Color object to its constructor.

$object2 = clone $object1;

We perform a shallow copy of the Object object.

$object2->id++;
$object2->color->red = 255;
$object2->size = "big";

Here we modify the member fields of the cloned object. We increment the id, change the red part of the color object, and change the size to “big”.

print_r($object1);
print_r($object2);

We use the print_r() function to compare the results.

$ php shallowcopy.php 
Object Object
(
    [id] => 23
    [size] => small
    [color] => Color Object
        (
            [red] => 255
            [green] => 42
            [blue] => 223
        )

)
Object Object
(
    [id] => 24
    [size] => big
    [color] => Color Object
        (
            [red] => 255
            [green] => 42
            [blue] => 223
        )

)

We can see that the ids are different: 23 vs 24. The size is different: “small” vs “big”. But the red part of the color object is same for both instances: 255. Changing member values of the cloned object did not affect the original object. Changing members of the referenced object has affected the original object too. In other words, both objects refer to the same color object in memory.

To change this behaviour, we will do a deep copy next.

deepcopy.php

<?php

class Object {

    public $id;
    public $size;
    public $color;

    function __construct($id, $size, $color) {
    
        $this->id = $id;
        $this->size = $size;
        $this->color = $color;
    }

    function __clone() {
    
        $red = $this->color->red;
        $green = $this->color->green;
        $blue = $this->color->blue;
        $this->color = new Color($red, $green, $blue);
    }
}

class Color {

    public $red;
    public $green;
    public $blue;

    function __construct($red, $green, $blue) {
    
        $this->red = $red;
        $this->green = $green;
        $this->blue = $blue;
    }
}

$color = new Color(23, 42, 223);

$object1 = new Object(23, "small", $color);
$object2 = clone $object1;

$object2->id++;
$object2->color->red = 255;
$object2->size = "big";

print_r($object1);
print_r($object2);
?>

In this PHP script, we have implemented the __clone() method.

function __clone() {
    $red = $this->color->red;
    $green = $this->color->green;
    $blue = $this->color->blue;
    $this->color = new Color($red, $green, $blue);
}

Inside the __clone() method, we copy the red, green, and blue member fields and create a new Color object. Now, the $color field points to a different Color object.

$ php deepcopy.php 
Object Object
(
    [id] => 23
    [size] => small
    [color] => Color Object
        (
            [red] => 23
            [green] => 42
            [blue] => 223
        )

)
Object Object
(
    [id] => 24
    [size] => big
    [color] => Color Object
        (
            [red] => 255
            [green] => 42
            [blue] => 223
        )

)

Now the red part of the referenced Color object is not the same. The original object has retained its previous 23 value.


PHP exceptions

Exceptions are designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution. Exceptions are raised or thrown and initiated.

During the execution of our application, many things might go wrong. A disk might get full and we cannot save our file. An Internet connection might go down and our application tries to connect to a site. All these might result in a crash of our application. To prevent happening this, we must cope with all possible errors that might occur. For this, we can use the exception handling.

Exceptions are available since PHP 5. Most PHP errors still use the old error reporting and not exceptions. With a set_error_handler() we can do a workaround for this.

zerodiv.php

<?php

set_error_handler("error_handler");

function error_handler($errno, $errstring, $errfile, $line, $trace) {
    throw new ErrorException($errstring, $errno, 0,  $errfile, $line);
}

try {

    $a = 0;
    $b = 32;
    $c = $b / $a;
} catch(ErrorException $e) {

   echo "Error occurred\n";
   echo $e->getMessage(), "\n";
}
?>

In the above PHP script, we intentionally divide a number by zero. This leads to an error. The error is not an exception and is not caught by the catch keyword.

set_error_handler("error_handler");

The set_error_handler() function sets a user defined error handler function.

function error_handler($errno, $errstring, $errfile, $line, $trace) {
    throw new ErrorException($errstring, $errno, 0,  $errfile, $line);
}

Inside the set_error_handler() function, we throw an ErrorException. This exception is later caught by the catch keyword.

try {

    $a = 0;
    $b = 32;
    $c = $b / $a;
}

The code that we are checking against an error is put inside the block following the try keyword.

} catch(Exception $e) {
   echo $e->getMessage();
}

The catch keyword is used to catch an exception. To find out more info, we call the getMessage() method on the exception object.

$ php zerodiv.php 
Error occurred
Division by zero

This is the output of our PHP script.

The Exception is a base class for all exceptions. We can create our own exceptions derived from this base class.

myexception.php

<?php

define("LIMIT", 333);

class BigValueException extends Exception {

    public function __construct($message) {
        parent::__construct($message);
    }
}

$a = 34325;

try {
    if ($a > LIMIT) {
        throw new BigValueException("Exceeded the maximum value allowed\n");   
    }
} catch (BigValueException $e) {
    echo $e->getMessage();   
}
?>

Let’s say, we have a situation in which we cannot deal with big numbers.

define("LIMIT", 333);

Numbers bigger than this constant are considered to be “big” by our PHP script.

class BigValueException extends Exception {

We have a BigValueException class. This class derives from the Exception class through the extends keyword.

public function __construct($message) {
    parent::__construct($message);
}

Inside the constructor, we call the parent’s constructor.

if ($a > LIMIT) {
    throw new BigValueException("Exceeded the maximum value allowed\n");   
}

If the value is bigger than the limit, we throw our custom exception. We give the exception a message “Exceeded the maximum value allowed”.

} catch (BigValueException $e) {
    echo $e->getMessage();   
}

We catch the exception and print its message to the console.


PHP constructor overloading

PHP does not support diret constructor overloading. In other words, each class can only have one constructor defined. Many programmers that already know Java or C# languages are looking for a similar feature in PHP. There are two ways how we can handle this.

The first solution is based on the func_get_args() function. The second solution uses a factory pattern.

constructors.php

<?php

class Book {
    
    private $author = "not specified";
    private $title = "not specified";
    private $year = "not specified";

    public function __construct() {
    
        $args = func_get_args();
    
        foreach(["title", "author", "year"] as $item) {
            
            if(empty($args)) {
                break;
            }
    
            $this->$item = array_shift($args);
        }
    }
    
    public function __toString() {
        return "Author: $this->author\nTitle: $this->title\nPublished: $this->year\n\n";
    }
}

$book1 = new Book("Stephen Prata", "C Primer Plus");
echo $book1;

$book2 = new Book("Joshua Bloch", "Effective Java", 2008);  
echo $book2;
?>

In the above script, we have a Book class. We instantiate the class with 2 and 3 parameters.

private $author = "not specified";
private $title = "not specified";
private $year = "not specified";

We have three member fields defined. Their initial value is “not specified”.

$args = func_get_args();

The func_get_args() function returns an array comprising a function’s argument list. So the idea is: the code inside the constructor is dynamic; it depends on the arguments passed to it.

foreach(["title", "author", "year"] as $item) {

We go through all member fields using the foreach keyword.

$this->$item = array_shift($args);

One of the most basic tasks in constructors is to initialize the member fields of the class. This is done by the above code line. The array_shift() function removes the first item from the array and returns it.

$book1 = new Book("Stephen Prata", "C Primer Plus");
...
$book2 = new Book("Joshua Bloch", "Effective Java", 2008);

We have two different constructors. The first takes 2 parameters, the second takes 3.

$ php constructors.php
Author: C Primer Plus
Title: Stephen Prata
Published: not specified

Author: Effective Java
Title: Joshua Bloch
Published: 2008

This is the outcome of the script.

The next code example simulates constructor overloading using the factory pattern. It is one of the creational patterns in OOP. The pattern creates objects without specifying the exact class of object that will be created. More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects.

factory.php

<?php

class Cat {

    private $name = "unspecified";
    private $age = "unspecified";

    public static function withName($name) {
    
        $cat = new Cat();
        $cat->name = $name;

        return $cat;
    }

    public static function withAge($age) {
    
        $cat = new Cat();
        $cat->age = $age;

        return $cat;
    }

    public static function fullCat($name, $age) {
    
        $cat = new Cat();
        $cat->name = $name;
        $cat->age = $age;

        return $cat;
    }

    public function __toString() {
        return "Name: $this->name, Age: $this->age\n";
    }
}

$cici = Cat::withName("Cici");
echo $cici;

$missy = Cat::withAge(6);
echo $missy;

$lucky = Cat::fullCat("Lucky", 4);
echo $lucky;
?>

We have a Cat factory class in the above PHP script. It has three different static functions. Each of them returns a specific cat object.

private $name = "unspecified";
private $age = "unspecified";

We have two member fields. Their initial value is “unspecified”.

public static function withName($name) {
    $cat = new Cat();
    $cat->name = $name;

    return $cat;
}

Here is a static withName() function. This function creates an instance of the Cat class. It sets the name member field and returns the object.

$cici = Cat::withName("Cici");
echo $cici;

We create an instance of the cat with one of the factory methods. We echo the object. i.e. call the __toString() method of the class.

$ php factory.php 
Name: Cici, Age: unspecified
Name: unspecified, Age: 6
Name: Lucky, Age: 4

The output of the script.

]]>
866
PHP Object Oriented Programming -I https://shishirkant.com/php-object-oriented-programming-i/?utm_source=rss&utm_medium=rss&utm_campaign=php-object-oriented-programming-i Tue, 26 May 2020 15:38:50 +0000 http://shishirkant.com/?p=862 Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs.

The basic programming concepts in OOP are:

  • Abstraction
  • Polymorphism
  • Encapsulation
  • Inheritance

Abstraction is simplifying complex reality by modeling classes appropriate to the problem. Polymorphism is the process of using an operator or function in different ways for different data input. Encapsulation hides the implementation details of a class from other objects. Inheritance is a way to form new classes using classes that have already been defined.


PHP Objects

Objects are basic building blocks of a PHP OOP program. An object is a combination of data and methods. In a OOP program, we create objects. These objects communicate together through methods. Each object can receive messages, send messages, and process data.

There are two steps in creating an object. First, we create a class. A class is a template for an object. It is a blueprint which describes the state and behavior that the objects of the class all share. A class can be used to create many objects. Objects created at runtime from a class are called instances of that particular class.

simpleclass.php

<?php

class Simple {}

$object = new Simple();
print_r($object);
echo gettype($object), "\n";
?>

In our first example, we create a simple object.

class Simple {}

This is a simple class definition. The body of the template is empty. It does not have any data or methods.

$object = new Simple();

We create a new instance of the Simple class. For this we have the new keyword. The $object variable is the handle to the created object.

print_r($object);
echo gettype($object), "\n";

We use the print_r() function to get information about the object and the gettype() function to get the type of the variable.

$ php simpleclass.php 
Simple Object
(
)
object

We don’t get much info, since the class definition was empty. The type of the variable is object.


PHP Object Attributes

Object attributes is the data bundled in an instance of a class. The object attributes are called instance variables or member fields. An instance variable is a variable defined in a class, for which each object in the class has a separate copy.

memberfields.php

<?php

class Person {

    public $name = "";
}

$p1 = new Person();
$p1->name = "Jane";

$p2 = new Person();
$p2->name = "Beky";

echo $p1->name . "\n"; 
echo $p2->name . "\n"; 
?>

In the above PHP script, we have a Person class with one member field.

$p1 = new Person();
$p1->name = "Jane";

We create an instance of the Person class and set the $name variable to “Jane”. We use the -> operator to access the attributes of objects.

$p2 = new Person();
$p2->name = "Beky";

We create another instance of the Person class. Here we set the variable to “Beky”.

echo $p1->name . "\n"; 
echo $p2->name . "\n"; 

We print the contents of the variables to the console.

$ php memberfields.php 
Jane
Beky

We see the output of the script. Each instance of the Person class has a separate copy of the $name member field.


PHP Methods

Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. Methods are essential in encapsulation concept of the OOP paradigm. For example, we might have a connect() method in our AccessDatabase class. We need not to be informed how exactly the method connect() connects to the database. We only know that it is used to connect to a database. This is essential in dividing responsibilities in programming, especially in large applications.circle.php

<?php

class Circle {

    public $radius;

    function setRadius($radius) {
        $this->radius = $radius;
    }

    function area() {
        return $this->radius * $this->radius * M_PI;
    }
}

$c = new Circle();
$c->setRadius(5);

echo $c->area(), "\n";
?>

In the code example, we have a Circle class. We define two methods.

 public $radius;

We have one member field. It is the radius of the circle. The public keyword is an access specifier. It tells that the variable is fully accessible from the outside world.

function setRadius($radius) {
    $this->radius = $radius;
}

This is the setRadius() method. It is a normal PHP function. We call functions defined inside classes methods. The $this variable is a special variable which we use to access the member fields from methods.

function area() {
    return $this->radius * $this->radius * M_PI;
}

The area() method returns the area of a circle. The M_PI is a built-in constant.

$ php circle.php 
78.539816339745

Running the example gives this output.


PHP Access Modifiers

Access modifiers set the visibility of methods and member fields. PHP has three access modifiers: publicprotected, and private. The public members can be accessed from anywhere. The protected members can be accessed only within the class itself and by inherited and parent classes. The private members may only be accessed by the class that defines the member.

Access modifiers protect data against accidental modifications. They make the programs more robust.

access1.php

<?php

class Person {

    public $name = "";
    private $age;
}

$p = new Person();
$p->name = "Jane";
#$p->age = 17;

echo $p->name . "\n";
?>

In the above PHP script, we have two member fields; one is declared public, the other private.

$p->name = "Jane";
#$p->age = 17;

We access the $name member from the outside world. By the outside world, we mean ‘not in the class’. It is OK, since the $name variable is declared public. Accessing the $age member is not possible. The private modifier prohibits this. If we uncomment the code line, we will get the ‘Fatal error: Cannot access private property Person::$age’ error.access2.php

<?php

class Base {
    
    public $name = "Base";
    protected $id = 6124;
    private $is_defined = "yes"; 

}

class Derived extends Base {

    public function info() {
        echo "This is Derived class\n";
        echo "Members inherited: \n";

        echo $this->name . "\n";
        echo $this->id . "\n";
        echo $this->is_defined . "\n";
    }
}

$derived = new Derived();
$derived->info();
?>

In this PHP script, we have a Derived class which extends the Base class. The Base class has three member fields, all with different access modifiers. The $is_defined member is not inherited. The private modifier prevents this.

public function info() {

The info() method has a public access modifier. This means, it can be called outside the class environment.

$ php access2.php 
This is Derived class
Members inherited: 
Base
6124

Running the PHP script, we receive this output. The public and protected members are inherited, the private member is not.

system.php

<?php

class SysInfo {

    private function get_date() {
        return date("Y/m/d");
    }

    private function get_version() {
        return phpversion();
    }

    public function getInfo() {

        $date = $this->get_date();
        $version = $this->get_version();

        echo "The date is: $date\n";
        echo "The PHP version is: $version\n";
    }
}

$sys = new SysInfo();
$sys->getInfo();
#$sys->get_date();
?>

In this script, we have a SysInfo class. It outputs some system information to the console. We have two private functions and one public. The private methods are here only for internal working of the SysInfo class. They are not meant to be called outside the class.

$sys = new SysInfo();
$sys->getInfo();
#$sys->get_date();

We create an instance of the SysInfo class and call the publicly available getInfo() method. The getInfo() method uses internally the private methods to do its job. Uncommenting the last code line yields to error.


PHP Method Overloading

Method overloading allows the creation of several methods with the same name which differ from each other in the type of the input.

What is method overloading good for? The Qt4 library gives a nice example for the usage. The QPainter class has three methods to draw a rectangle. Their name is drawRect() and their parameters differ. One takes a reference to a floating point rectangle object, another takes a reference to an integer rectangle object and the last one takes four parameters, x, y, width, height. If the C++ language, which is the language in which Qt is developed, didn’t have method overloading, the creators of the library would have to name the methods like drawRectRectF()drawRectRect()drawRectXYWH(). The solution with method overloading is more elegant.

overloading1.php

<?php

class Sum {

    public function getSum() {
        return 0;
    }

    public function getSum($x) {
        return $x;
    }

    public function getSum($x, $y) {
        return $x + $y;
    }
}

$s = new Sum();
echo $s->getSum() . "\n" ;
echo $s->getSum(5) . "\n" ;
echo $s->getSum(3, 4) . "\n" ;
?>

This is a method overloading, we know from languages like C#, Java or C++. But this does not work in PHP. Running this example, we get the following error: ‘Fatal error: Cannot redeclare Sum::getSum()’. PHP functions can take arbitrary number of variables by default.

To simulate method overloading in PHP, we use the func_get_args() function.

overloading2.php

<?php

class Sum {

    public function getSum() {
    
        $args = func_get_args();

        if (empty($args)) return 0;

        foreach ($args as $arg) {
            $sum += $arg;
        }

        return $sum;
    }
}

$s = new Sum();
echo $s->getSum() . "\n" ;
echo $s->getSum(5) . "\n" ;
echo $s->getSum(3, 4) . "\n" ;
echo $s->getSum(3, 4, 7) . "\n" ;
?>

This time, the script will run.

$args = func_get_args();

The func_get_args() function returns an array comprising a function’s argument list.

foreach ($args as $arg) {
    $sum += $arg;
}

We go throught all members of the array, and calculate the sum.

echo $s->getSum() . "\n" ;
echo $s->getSum(5) . "\n" ;
echo $s->getSum(3, 4) . "\n" ;
echo $s->getSum(3, 4, 7) . "\n" ;

We call the same method name with different number of inputs.

$ php overloading2.php 
0
5
7
14

This is the output of the overloading2.php script.


PHP Constructor

A constructor is a special kind of a method. It is automatically called when the object is created. The purpose of the constructor is to initiate the state of the object. The name of the constructor in PHP is __construct() (with two underscores).

constructor.php

<?php

class Song {

    function __construct() {
        echo "Song object is created \n";
    }
}

$song = new Song();
?>

We have a Song class. This class has a constructor that prints message to the console.

$song = new Song();

This is the time, when the object is created and the constructor is called. We get a message in the console.

$ php constructor.php 
Song object is created 

This is the output of the script.

Constructors often take arguments.

constructor2.php

<?php

class Song {

    function __construct($song) {
        echo "Song $song is created \n";
    }
}

$song = new Song("Bad romance");
?>

We modify the previous example a bit. We pass a value to the constructor.

function __construct($song) {
    echo "Song $song is created \n";
}

The passed argument is stored in the local $song variable.

$ php constructor2.php 
Song Bad romance is created 

Now we have a message with a song title printed to the console.

In the next example, we initiate data members of the class. Initiation of variables is a typical job for constructors.

friend.php

<?php

class Friend {

    private $born;
    private $name;

    function __construct($name, $born) {
        $this->name = $name;
        $this->born = $born;
    }

    function getInfo() {
        echo "My friend $this->name was born in $this->born\n";
    }
}

$friend = new Friend("Monika", 1990);
$friend->getInfo();
?>

We have a Friend class with data members and methods.

private $born;
private $name;

We have two variables in the class definition. The private keyword is an access modifier. It is a form of encapsulation. The private keyword is the most restrictive modifier. It allows only the object in question to access the variable. No descendants, no other objects. More about this topic later.

function __construct($name, $born) {
    $this->name = $name;
    $this->born = $born;
}

In the constructor, we initiate the two data members. The $this variable is a handler used to reference the object variables.

$friend = new Friend("Monika", 1990);
$friend->getInfo();

We create a Friend object with two arguments. Then we call the getInfo() method of the object. To call object methods, we use the -> operator.

$ php friend.php 
My friend Monika was born in 1990

PHP Class Constants

PHP enables to create class constants. These constants do not belong to a concrete object. They belong to the class. By convention, constants are written in uppercase letters.

constants.php

<?php

class Math {

    const PI = 3.14159265359;

    public function getPI() {
        echo self::PI;
    }
}

$math = new Math();

echo Math::PI, "\n";
echo $math->getPI(), "\n";
?>

We have a Math class with a PI constant.

const PI = 3.14159265359;

The const keyword is used to define a constant.

public function getPI() {
    echo self::PI;
}

Class constants are accessed from within methods using the self keyword followed by two colons.

echo Math::PI, "\n";
echo $math->getPI(), "\n";

We print the PI constant to the console. In the first case, we get the constant value by referring to the class name, followed by two colons and a constant name. Note that no object was needed to get the class constant. In the second case, we use the object method.

PHP Instanceof Keyword

The instanceof keyword is used to determine whether a PHP variable is an instantiated object of a certain class.

instanceof.php

<?php

class Cat {}
class Dog {}
class Bird {}

$objects = [ new Cat(), new Dog(), new Cat(), new Bird(), new Bird(), 
             new Dog(), new Dog(), new Cat(), new Bird() ];

shuffle($objects);

foreach ($objects as $object) {

    if ($object instanceof Cat) {
        echo "It is a Cat\n";
    } elseif ($object instanceof Dog) {
        echo "It is a Dog\n";
    } else if ($object instanceof Bird) {
        echo "It is a Bird\n";
    }
}
?>

In the above script, we have three classes: CatDog, and Bird. We traverse the array and print the class for each array value.

$objects = [ new Cat(), new Dog(), new Cat(), new Bird(), new Bird(), 
             new Dog(), new Dog(), new Cat(), new Bird() ];

We create an array of these objects.

shuffle($objects);

We shuffle the array. At this point, we don’t know the class types for the values of the array.

if ($object instanceof Cat) {
    echo "It is a Cat\n";
}

Here we use the instanceof keyword to find out the type of the class.

$ php instanceof.php 
It is a Bird
It is a Cat
It is a Cat
It is a Dog
It is a Dog
It is a Cat
It is a Dog
It is a Bird
It is a Bird

We might get this output.


PHP __toString Method

When we use the print or the echo keyword with the object instance, the __toString() special method is called. We will demonstrate this in the following example.

tostring.php

<?php

class Cat {

    public $name;
    public $age;

    function __construct($name, $age) {
        $this->age = $age;
        $this->name = $name;
    }

    function __toString() {
        return "Cat: $this->name, Age: $this->age \n";
    }
}

$missy = new Cat("Missy", 6);
$lucky = new Cat("Lucky", 4);

print $missy;
echo $lucky;
?>

We have a Cat class with a __toString() special method defined.

function __toString() {
    return "Cat: $this->name, Age: $this->age \n";
}

The method prints the basic info about the object.

$missy = new Cat("Missy", 6);
$lucky = new Cat("Lucky", 4);

We create two objects of the Cat class.

print $missy;
echo $lucky;

And we use the print or the echo keywords on them.

$ php tostring.php 
Cat: Missy, Age: 6 
Cat: Lucky, Age: 4 

This is what we get when we run the script.


PHP Inheritance

The inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, the classes that we derive from are called base classes. Important benefits of inheritance are code reuse and reduction of complexity of a program. The derived classes (descendants) override or extend the functionality of base classes (ancestors).

derived.php

<?php

class Base {
    function __construct() {
       echo "Construction of Base class \n";
    }
}

class Derived extends Base {
    function __construct() {
        parent::__construct();
        echo "Construction of Derived class \n";
    }
}

$obj1 = new Base();
$obj2 = new Derived(); 
?>

In this PHP script, we have two classes: a Base class and a Derived class. The Derived class inherits from the Base class.

class Derived extends Base {

In PHP, we use the extends keyword to create inheritance relations.

function __construct() {
    parent::__construct();
    echo "Construction of Derived class \n";
}

In the constructor of the Derived class, we call the parent constructor. We use the parent keyword, followed by two colons and the __construct() method. The constructors of the parent classes must be called explicitly.

$obj1 = new Base();
$obj2 = new Derived(); 

We instantiate both the Base and the Derived classes.

$ php derived.php 
Construction of Base class 
Construction of Base class 
Construction of Derived class 

This is the output of the PHP script.

A more complex example follows.

inheritance.php

<?php

abstract class Being { 

    protected $isAlive = true;
   
    public function isAlive() {
    
        if ($this->isAlive) {
            echo "Being is alive\n";
        } else {
            echo "Being is not alive\n";
        }
    }

    public function kill() {
    
        $this->isAlive = false;
    }
}

abstract class Animal extends Being {

    protected $age;

    public function __construct($age) {
        $this->age = $age;
    }

    protected function setAge($age) {
        $this->age = $age;
    }

    public function getAge() {
        return $this->age;
    }
}

class Cat extends Animal {

    private $name;

    public function __construct($name, $age) {
        $this->name = $name;
        parent::__construct($age);
    }

    public function getName() {
    
        return $this->name;
    }
}

$cat = new Cat("Cici", 4);
$cat->isAlive();
echo $cat->getName() . " is " .  $cat->getAge() . " years old\n";
$cat->kill();
$cat->isAlive();
?>

We have used several new concepts here. In the code example, we have three classes: BeingAnimal, and Cat. The Animal class inherits from the Being class. The Cat class inherits from the Animal class. Classes inherit methods and data members that are not declared as private.

abstract class Being {

The Being class is declared to be abstract. The abstract keyword prohibits instantiation of classes. It does not make much sense to create an instance of the class Being.

protected $isAlive = true;

The $isAlive data member is declared to be protected. Such members can be accessed only by the classes that define them and by their descendants.

abstract class Animal extends Being {

The Animal class is also declared to be abstract. It inherits from class Being. For this, we use the extends keyword. The Animal is a descendant. It inherits methods and variables of the base Being class.

class Cat extends Animal {

The Cat class inherits from the Animal class. It inherits from the Animal class and indirectly from the Being class too. It is not declared abstract, which means that we can instantiate it.

parent::__construct($age);

In the constructor of the Cat class, we call the parent constructor using the parent keyword, followed by two colons and the __construct() method. The constructors of the parent classes must be called explicitly.

$cat = new Cat("Cici", 4);
$cat->isAlive();
echo $cat->getName() . " is " .  $cat->getAge() . " years old\n";
$cat->kill();
$cat->isAlive();

We create a new Cat: Cici, 4 years old. Then we call functions on the cici object. Note the usage of methods that were not created in the Cat class, but rather inherited from the parent classes.

$ php inheritance.php 
Being is alive
Cici is 4 years old
Being is not alive

Output of the script.


PHP abstract Classes and Methods

PHP introduced abstract classes and methods. Abstract classes cannot be instantiated. If a class contains at least one abstract method, it must be declared abstract too. Abstract methods cannot be implemented, they merely declare the methods’ signatures. When we inherit from an abstract class, all abstract methods must be implemented by the derived class. Furthermore, these methods must be declared with the same or with a less restricted visibility.

Unlike interfaces, abstract classes may have methods with full implementation and may also have defined member fields. So abstract classes may provide a partial implementation. Programmers often put some common functionality into abstract classes. And these abstract classes are later subclassed to provide more specific implementation. For example, the Qt graphics library has a QAbstractButton, which is the abstract base class of button widgets, providing functionality common to buttons. Buttons Q3ButtonQCheckBoxQPushButtonQRadioButton, and QToolButton inherit from this base abstract class.

Formally put, abstract classes are used to enforce a protocol. A protocol is a set of operations which all implementing objects must support.

abstract.php

<?php

abstract class Drawing {

    protected $x = 0;
    protected $y = 0;

    public abstract function area();

    public function getCoordinates() {
    
        echo "\$x is $this->x\n";
        echo "\$y is $this->y\n";
    }
}

class Circle extends Drawing {
   
    private $radius;

    public function __construct($x, $y, $r) {
    
        $this->radius = $r;
        $this->x = $x;
        $this->y = $y;
    }

    public function area() {
    
        return $this->radius * $this->radius * pi();
    }

   public function __toString() {
   
       return "Circle, at x: $this->x, y: $this->y, radius: $this->radius";
   }

}

$o = new Circle(12, 45, 22);
echo "$o \n";
echo "Area of the circle: " . $o->area() . "\n";
echo $o->getCoordinates();
?>

In our PHP script, we have an abstract base Drawing class. The class defines two member fields, defines one method and declares one method. One of the methods is abstract, the other one is fully implemented. The Drawing class is abstract because we cannot draw it. We can draw a circle, a dot, or a square. The Drawing class has some common functionality to the objects that we can draw.

class Circle extends Drawing {

Circle is a subclass of the Drawing class. It must implement the abstract area method.

$ php abstract.php 
Circle, at x: 12, y: 45, radius: 22 
Area of the circle: 1520.53084434
$x is 12
$y is 45

Output of the script.


PHP Interfaces

A remote control is an interface between the viewer and the TV. It is an interface to this electronic device. Diplomatic protocol guides all activities in the diplomatic field. Rules of the road are rules that motorists, cyclists, and pedestrians must follow. Interfaces in programming are analoguos to the previous examples.

Interfaces are:

  • APIs
  • Contracts

Objects interact with the outside world with the methods they expose. The actual implementation is not important to the programmer, or it also might be secret. A company might sell a library and it does not want to disclose the actual implementation. A programmer might call a maximize() method on a window of a GUI toolkit, but knows nothing about how this method is implemented. From this point of view, interfaces are methods through which objects interact with the outside world, without exposing too much about their inner workings.

From the second point of view, interfaces are contracts. If agreed upon, they must be followed. They are used to design an architecture of an application, and they help organize the code.

Interfaces are fully abstract types. They are declared using the interface keyword. Interfaces can only have method signatures and constants. All method signatures declared in an interface must be public. They cannot have fully implemented methods, nor member fields. A PHP class may implement any number of interfaces. An interface can also extend any number of interfaces. A class that implements an interface must implement all method signatures of an interface.

Interfaces are used to simulate multiple inheritance. A PHP class can extend only one class. A PHP class can implement multiple interfaces. Multiple inheritance using the interfaces is not about inheriting methods and variables. It is about inheriting ideas or contracts, which are described by the interfaces.

There is one important distinction between interfaces and abstract classes. Abstract classes provide partial implementation for classes that are related in the inheritance hierarchy. Interfaces on the other hand can be implemented by classes that are not related to each other. For example, we have two buttons: a classic button and a round button. Both inherit from an abstract button class that provides some common functionality to all buttons. Implementing classes are related, since all are buttons. Another example might have classes Database and SignIn. They are not related to each other. We can apply an ILoggable interface that would force them to create a method to do logging.

simpleinterface.php

<?php

interface IInfo {

    public function do_inform();
}

class Some implements IInfo {

    public function do_inform() {
        echo "This is a Some class\n";
    }
}

$sm = new Some();
$sm->do_inform();
?>

This is a simple PHP script demonstrating an interface.

interface IInfo {

    public function do_inform();
}

This is an interface IInfo. It has the do_inform() method signature.

class Some implements IInfo {

We use the implements to implement from an interface.

public function do_inform() {
    echo "This is a Some class\n";
}

The class provides an implementation for the do_inform() method.

The next example shows how a class can implement multiple interfaces.

interface.php

<?php

interface Device {

    public function switch_on();
    public function switch_off();
}

interface Volume {

    public function volume_up();
    public function volume_down();
}

interface Pluggable {

    public function plug_in();
    public function plug_off();
}

class CellPhone implements Device, Volume, Pluggable {

    public function switch_on() { echo "Switching on\n"; }
    public function switch_off() { echo "Switching off\n"; }

    public function volume_up() { echo "Volume up\n"; }
    public function volume_down() { echo "Volume down\n"; }

    public function plug_in() { echo "Plugging in\n"; }
    public function plug_off() { echo "Plugging off\n"; }
}

$o = new CellPhone();
$o->switch_on();
$o->volume_up();
$o->plug_in();
?>

We have a CellPhone class that inherits from three interfaces.

class CellPhone implements Device, Volume, Pluggable {

The class implements all three interfaces, which are divided by a comma. The CellPhone class must implement all method signatures from all three interfaces.

$ php interface.php 
Switching on
Volume up
Plugging in

Running the PHP script.

The next example shows how interfaces can extend from multiple other interfaces.

extendinginterfaces.php

<?php

interface IInfo {

    public function do_inform();
}

interface IVersion {

    public function get_version();
}

interface ILog extends IInfo, IVersion {

    public function do_log();
}


class DBConnect implements ILog {

    public function do_inform() {
    
        echo "This is a DBConnect class\n";
    }

    public function get_version() {
    
        echo "Version 1.02\n";
    }

    public function do_log() {
    
        echo "Logging\n";
    }

    public function connect() {
    
        echo "Connecting to the database\n";
    }
}

$db = new DBConnect();
$db->do_inform();
$db->get_version();
$db->do_log();
$db->connect();
?>

In this PHP script, we define three interfaces. Extending interfaces allows us to organize them.

interface ILog extends IInfo, IVersion {

    public function do_log();
}

The ILog interface extends other two interfaces.

public function do_inform() {

    echo "This is a DBConnect class\n";
}

The DBConnect class implements the do_inform() method. This method was inherited by the ILog interface, which the class implements.


PHP Polymorphism

Polymorphism is the process of using an operator or function in different ways for different data input. In practical terms, polymorphism means that if class B inherits from class A, it doesn’t have to inherit everything about class A; it can do some of the things that class A does differently.

In general, polymorphism is the ability to appear in different forms. Technically, it is the ability to redefine methods for derived classes. Polymorphism is concerned with the application of specific implementations to an interface or a more generic base class.

polymorphism.php

<?php

abstract class Shape {
    
    private $x = 0;
    private $y = 0;

    public abstract function area();
}

class Rectangle extends Shape {

    function __construct($x, $y) {
        
        $this->x = $x;
        $this->y = $y;
    }

    function area() {
        
        return $this->x * $this->y;
    }
}

class Square extends Shape {

    function __construct($x) {
        
        $this->x = $x;
    }

    function area() {
        
        return $this->x * $this->x;
    }
}

$shapes = [ new Square(5), new Rectangle(12, 4), new Square(8) ];

foreach ($shapes as $shape) {
    
    echo $shape->area() . "\n";
}
?>

In the above PHP script, we have an abstract Shape class. This class morphs into two descendant classes: Rectangle and Square. Both provide their own implementation of the area() method. Polymorphism brings flexibility and scalability to the OOP systems.

]]>
862
PHP Regular Expression https://shishirkant.com/php-regular-expression/?utm_source=rss&utm_medium=rss&utm_campaign=php-regular-expression Tue, 26 May 2020 15:22:37 +0000 http://shishirkant.com/?p=859 Regular expressions are used for text searching and more advanced text manipulation. Regular expressions are built-in tools like grep, sed, text editors like vi, emacs, programming languages like Tcl, Perl, and Python. PHP has a built-in support for regular expressions too.

In PHP, there are two modules for regular expressions: the POSIX Regex and the PCRE. The POSIX Regex is depreciated. In this chapter, we will use the PCRE examples. PCRE stands for Perl compatible regular expressions.

Two things are needed when we work with regular expressions: Regex functions and the pattern.

pattern is a regular expression that defines the text we are searching for or manipulating. It consists of text literals and metacharacters. The pattern is placed inside two delimiters. These are usually //##, or @@ characters. They inform the regex function where the pattern starts and ends.

Here is a partial list of metacharacters used in PCRE.

.Matches any single character.
*Matches the preceding element zero or more times.
[ ]Bracket expression. Matches a character within the brackets.
[^ ]Matches a single character that is not contained within the brackets.
^Matches the starting position within the string.
$Matches the ending position within the string.
|Alternation operator.

PRCE functions

We define some PCRE regex functions. They all have a preg prefix.

  • preg_split() – splits a string by regex pattern
  • preg_match() – performs a regex match
  • preg_replace() – search and replace string by regex pattern
  • preg_grep() – returns array entries that match the regex pattern

Next we will have an example for each function.

php> print_r(preg_split("@\s@", "Jane\tKate\nLucy Marion"));
Array
(
    [0] => Jane
    [1] => Kate
    [2] => Lucy
    [3] => Marion
)

We have four names divided by spaces. The \s is a character class which stands for spaces. The preg_split() function returns the split strings in an array.

php> echo preg_match("#[a-z]#", "s");
1

The preg_match() function looks if the ‘s’ character is in the character class [a-z]. The class stands for all characters from a to z. It returns 1 for success.

php> echo preg_replace("/Jane/","Beky","I saw Jane. Jane was beautiful.");
I saw Beky. Beky was beautiful.

The preg_replace() function replaces all occurrences of the word ‘Jane’ for the word ‘Beky’.

php> print_r(preg_grep("#Jane#", ["Jane", "jane", "Joan", "JANE"]));
Array
(
    [0] => Jane
)

The preg_grep() function returns an array of words that match the given pattern. In this example, only one word is returned in the array. This is because by default, the search is case sensitive.

php> print_r(preg_grep("#Jane#i", ["Jane", "jane", "Joan", "JANE"]));
Array
(
    [0] => Jane
    [1] => jane
    [3] => JANE
)

In this example, we perform a case insensitive grep. We put the i modifier after the right delimiter. The returned array has now three words.

The dot metacharacter

The . (dot) metacharacter stands for any single character in the text.

single.php

<?php

$words = [ "Seven", "even", "Maven", "Amen", "Leven" ];
$pattern = "/.even/";

foreach ($words as $word) {

    if (preg_match($pattern, $word)) {
        echo "$word matches the pattern\n";
    } else {
        echo "$word does not match the pattern\n";
    }
}
?>

In the $words array, we have five words.

$pattern = "/.even/";

Here we define the search pattern. The pattern is a string. The regular expression is placed within delimiters. The delimiters are mandatory. In our case, we use forward slashes / / as delimiters. Note that we can use different delimiters if we want. The dot character stands for any single character.

if (preg_match($pattern, $word)) {
    echo "$word matches the pattern\n";
} else {
    echo "$word does not match the pattern\n";
}

We test all five words if they match with the pattern.

$ php single.php 
Seven matches the pattern
even does not match the pattern
Maven does not match the pattern
Amen does not match the pattern
Leven matches the pattern

The Seven and Leven words match our search pattern.

Anchors

Anchors match positions of characters inside a given text.

In the next example, we look if a string is located at the beginning of a sentence.

anchors.php

<?php

$sentence1 = "Everywhere I look I see Jane";
$sentence2 = "Jane is the best thing that happened to me";

if (preg_match("/^Jane/", $sentence1)) {
    echo "Jane is at the beginning of the \$sentence1\n";
} else {
    echo "Jane is not at the beginning of the \$sentence1\n";
}

if (preg_match("/^Jane/", $sentence2)) {
    echo "Jane is at the beginning of the \$sentence2\n";
} else {
    echo "Jane is not at the beginning of the \$sentence2\n";
}
?>

We have two sentences. The pattern is ^Jane. The pattern checks if the ‘Jane’ string located at the beginning of the text.

$ php anchors.php 
Jane is not at the beginning of the $sentence1
Jane is at the beginning of the $sentence2
php> echo preg_match("#Jane$#", "I love Jane");
1
php> echo preg_match("#Jane$#", "Jane does not love me");
0

The Jane$ pattern matches a string in which the word Jane is at the end.

Exact word match

In the following examples we show how to look for exact word matches.

php> echo preg_match("/mother/", "mother");
1
php> echo preg_match("/mother/", "motherboard");
1
php> echo preg_match("/mother/", "motherland");
1

The mother pattern fits the words mother, motherboard and motherland. Say, we want to look just for exact word matches. We will use the aforementioned anchor ^ and $ characters.

php> echo preg_match("/^mother$/", "motherland");
0
php> echo preg_match("/^mother$/", "Who is your mother?");
0
php> echo preg_match("/^mother$/", "mother");
1

Using the anchor characters, we get an exact word match for a pattern.

Quantifiers

A quantifier after a token or a group specifies how often that preceding element is allowed to occur.

 ?     - 0 or 1 match
 *     - 0 or more
 +     - 1 or more
 {n}   - exactly n
 {n,}  - n or more
 {,n}  - n or less (??)
 {n,m} - range n to m

The above is a list of common quantifiers.

The question mark ? indicates there is zero or one of the preceding element.

zeroorone.php

<?php

$words = [ "color", "colour", "comic", "colourful", "colored", 
    "cosmos", "coloseum", "coloured", "colourful" ];
$pattern = "/colou?r/";

foreach ($words as $word) {
    if (preg_match($pattern, $word)) {
        echo "$word matches the pattern\n";
    } else {
        echo "$word does not match the pattern\n";
    }
}
?>

We have four nine in the $words array.

$pattern = "/colou?r/";

Color is used in American English, colour in British English. This pattern matches both cases.

$ php zeroorone.php 
color matches the pattern
colour matches the pattern
comic does not match the pattern
colourful matches the pattern
colored matches the pattern
cosmos does not match the pattern
coloseum does not match the pattern
coloured matches the pattern
colourful matches the pattern

This is the output of the zeroorone.php script.

The * metacharacter matches the preceding element zero or more times.

zeroormore.php

<?php

$words = [ "Seven", "even", "Maven", "Amen", "Leven" ];

$pattern = "/.*even/";

foreach ($words as $word) {
    
    if (preg_match($pattern, $word)) {
        echo "$word matches the pattern\n";
    } else {
        echo "$word does not match the pattern\n";
    }
}
?>

In the above script, we have added the * metacharacter. The .* combination means, zero, one or more single characters.

$ php zeroormore.php 
Seven matches the pattern
even matches the pattern
Maven does not match the pattern
Amen does not match the pattern
Leven matches the pattern

Now the pattern matches three words: Seven, even and Leven.

php> print_r(preg_grep("#o{2}#", ["gool", "root", "foot", "dog"]));
Array
(
    [0] => gool
    [1] => root
    [2] => foot
)

The o{2} pattern matches strings that contain exactly two ‘o’ characters.

php> print_r(preg_grep("#^\d{2,4}$#", ["1", "12", "123", "1234", "12345"]));
Array
(
    [1] => 12
    [2] => 123
    [3] => 1234
)

We have this ^\d{2,4}$ pattern. The \d is a character set; it stands for digits. The pattern matches numbers that have 2, 3, or 4 digits.

Alternation

The next example explains the alternation operator |. This operator enables to create a regular expression with several choices.

alternation.php

<?php

$names = [ "Jane", "Thomas", "Robert", "Lucy", "Beky", 
    "John", "Peter", "Andy" ];

$pattern = "/Jane|Beky|Robert/";

foreach ($names as $name) {

    if (preg_match($pattern, $name)) {
        echo "$name is my friend\n";
    } else {
        echo "$name is not my friend\n";
    }
}
?>

We have eight names in the $names array.

$pattern = "/Jane|Beky|Robert/";

This is the search pattern. The pattern looks for ‘Jane’, ‘Beky’, or ‘Robert’ strings.

$ php alternation.php 
Jane is my friend
Thomas is not my friend
Robert is my friend
Lucy is not my friend
Beky is my friend
John is not my friend
Peter is not my friend
Andy is not my friend

This is the output of the script.

Subpatterns

We can use square brackets () to create subpatterns inside patterns.

php> echo preg_match("/book(worm)?$/", "bookworm");
1
php> echo preg_match("/book(worm)?$/", "book");
1
php> echo preg_match("/book(worm)?$/", "worm");
0

We have the following regex pattern: book(worm)?$. The (worm) is a subpattern. The ? character follows the subpattern, which means that the subpattern might appear 0, 1 times in the final pattern. The $ character is here for the exact end match of the string. Without it, words like bookstore, bookmania would match too.

php> echo preg_match("/book(shelf|worm)?$/", "book");
1
php> echo preg_match("/book(shelf|worm)?$/", "bookshelf");
1
php> echo preg_match("/book(shelf|worm)?$/", "bookworm");
1
php> echo preg_match("/book(shelf|worm)?$/", "bookstore");
0

Subpatterns are often used with alternation. The (shelf|worm) subpattern enables to create several word combinations.

Character classes

We can combine characters into character classes with the square brackets. A character class matches any character that is specified in the brackets.

characterclass.php

<?php

$words = [ "sit", "MIT", "fit", "fat", "lot" ];

$pattern = "/[fs]it/";

foreach ($words as $word) {

    if (preg_match($pattern, $word)) {
        echo "$word matches the pattern\n";
    } else {
        echo "$word does not match the pattern\n";
    }
}
?>

We define a character set with two characters.

$pattern = "/[fs]it/";

This is our pattern. The [fs] is the character class. Note that we work only with one character at a time. We either consider f, or s, but not both.

$ php characterclass.php 
sit matches the pattern
MIT does not match the pattern
fit matches the pattern
fat does not match the pattern
lot does not match the pattern

This is the outcome of the script.

We can also use shorthand metacharacters for character classes. The \w stands for alphanumeric characters, \d for digit, and \s whitespace characters.

shorthand.php

<?php

$words = [ "Prague", "111978", "terry2", "mitt##" ];
$pattern = "/\w{6}/";

foreach ($words as $word) {

    if (preg_match($pattern, $word)) {
        echo "$word matches the pattern\n";
    } else {
        echo "$word does not match the pattern\n";
    }
}
?>

In the above script, we test for words consisting of alphanumeric characters. The \w{6} stands for six alphanumeric characters. Only the word mitt## does not match, because it contains non-alphanumeric characters.

php> echo preg_match("#[^a-z]{3}#", "ABC");
1

The #[^a-z]{3}# pattern stands for three characters that are not in the class a-z. The “ABC” characters match the condition.

php> print_r(preg_grep("#\d{2,4}#", [ "32", "234", "2345", "3d3", "2"]));
Array
(
    [0] => 32
    [1] => 234
    [2] => 2345
)

In the above example, we have a pattern that matches 2, 3, and 4 digits.

Extracting matches

The preg_match() takes an optional third parameter. If it is provided, it is filled with the results of the search. The variable is an array whose first element contains the text that matched the full pattern, the second element contains the first captured parenthesized subpattern, and so on.

extract_matches.php

<?php

$times = [ "10:10:22", "23:23:11", "09:06:56" ];

$pattern = "/(\d\d):(\d\d):(\d\d)/";

foreach ($times as $time) {

    $r = preg_match($pattern, $time, $match);
    
    if ($r) {
        
        echo "The $match[0] is split into:\n";
        
        echo "Hour: $match[1]\n";
        echo "Minute: $match[2]\n";
        echo "Second: $match[3]\n";
    } 
}
?>

In the example, we extract parts of a time string.

$times = [ "10:10:22", "23:23:11", "09:06:56" ];

We have three time strings in English locale.

$pattern = "/(\d\d):(\d\d):(\d\d)/";

The pattern is divided into three subpatterns using square brackets. We want to refer specifically to exactly to each of these parts.

$r = preg_match($pattern, $time, $match);

We pass a third parameter to the preg_match() function. In case of a match, it contains text parts of the matched string.

if ($r) {
    
    echo "The $match[0] is split into:\n";
    
    echo "Hour: $match[1]\n";
    echo "Minute: $match[2]\n";
    echo "Second: $match[3]\n";
} 

The $match[0] contains the text that matched the full pattern, $match[1] contains text that matched the first subpattern, $match[2] the second, and $match[3] the third.

$ php extract_matches.php 
The 10:10:22 is split into:
Hour: 10
Minute: 10
Second: 22
The 23:23:11 is split into:
Hour: 23
Minute: 23
Second: 11
The 09:06:56 is split into:
Hour: 09
Minute: 06
Second: 56

This is the output of the example.

Email example

Next have a practical example. We create a regex pattern for checking email addresses.

emails.php

<?php

$emails = [ "luke@gmail.com", "andy@yahoocom", "34234sdfa#2345", 
    "f344@gmail.com"];

# regular expression for emails
$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,18}$/";

foreach ($emails as $email) {

    if (preg_match($pattern, $email)) {
        echo "$email matches \n";
    } else {
        echo "$email does not match\n";
    }
}

>?

Note that this example provides only one solution. It does not have to be the best one.

$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,18}$/";

This is the pattern. The first ^ and the last $ characters are here to get an exact pattern match. No characters before and after the pattern are allowed. The email is divided into five parts. The first part is the local part. This is usually a name of a company, individual, or a nickname. The [a-zA-Z0-9._-]+ lists all possible characters, we can use in the local part. They can be used one or more times. The second part is the literal @ character. The third part is the domain part. It is usually the domain name of the email provider, like yahoo, or gmail. The [a-zA-Z0-9-]+ is a character set providing all characters that can be used in the domain name. The + quantifier makes use of one or more of these characters. The fourth part is the dot character. It is preceded by the escape character (\). This is because the dot character is a metacharacter and has a special meaning. By escaping it, we get a literal dot. The final part is the top level domain. The pattern is as follows: [a-zA-Z.]{2,18} Top level domains can have from 2 to 18 characters, like sk, net, info, travel, cleaning, travelinsurance. The maximum lenght can be 63 characters, but most domain are shorter than 18 characters today. There is also a dot character. This is because some top level domains have two parts; for example co.uk.

$ php emails.php 
luke@gmail.com matches 
andy@yahoocom does not match
34234sdfa#2345 does not match
f344@gmail.com matches 

This is the output of the emails.php example.

Recap

Finally, we provide a quick recap of the regex patterns.

Jane    the 'Jane' string
^Jane   'Jane' at the start of a string
Jane$   'Jane' at the end of a string
^Jane$  exact match of the string 'Jane'
[abc]   a, b, or c
[a-z]   any lowercase letter
[^A-Z]  any character that is not a uppercase letter
(Jane|Becky)   Matches either 'Jane' or 'Becky'
[a-z]+   one or more lowercase letters
^[98]?$  digits 9, 8 or empty string       
([wx])([yz])  wy, wz, xy, or xz
[0-9]         any digit
[^A-Za-z0-9]  any symbol (not a number or a letter)
]]>
859
PHP Error Handling https://shishirkant.com/php-error-handling/?utm_source=rss&utm_medium=rss&utm_campaign=php-error-handling Tue, 26 May 2020 15:10:50 +0000 http://shishirkant.com/?p=855 PHP has a number of functions for handling as well as reporting errors. Besides, you can define your own way of handling and reporting errors. In this and subsequent pages we are going to discuss installation, runtime configuration, predefined constants and functions relating to PHP error handling and reporting.

Configuration settings for PHP Error handling and reporting are available in php.ini file, which is located in the php installation folder of your system.
Following is a list of error handling settings, there descriptions, default value and where they can be changed (Changeable).

For reference, settings of any PHP configuration can be changed in various ways – using ini_set(), in WINDOWS registry, in php.ini, in .htaccess or in httpd.conf. PHP_INI_ALL refers that the related configuration can be changed in any the aforementioned ways. PHP_INI_SYSTEM refers the entry can be set in php.ini or httpd.conf.

NameTypeDescriptionDefaultChangeable
error_reportingintegerSet the error reporting level.NULLPHP_INI_ALL
display_errorsstringDetermines if errors are displayed or hidden.“1” PHP_INI_ALL
display_startup_errorsbooleanEven if display_errors is on, hides errors that occur during PHP’s startup sequence. Keep it off when online.“0”PHP_INI_ALL
log_errorsbooleanSpecifies if script error messages should be logged to the server’s error log.“0”PHP_INI_ALL
log_errors_max_lenintegerSpecifies the maximum length of log_errors in bytes.“1024”PHP_INI_ALL
ignore_repeated_errors booleanDo not log repeated messages.“0”PHP_INI_ALL
ignore_repeated_sourcebooleanIgnore source of message when ignoring repeated messages.“0”PHP_INI_ALL
report_memleaksbooleanIf set to Off, memory leaks (the program is unable to release memory it has occupied) will not be displayed.“1”PHP_INI_ALL
track_errorsbooleanIf enabled, variable $php_errormsg will always hold the last error message.“0”PHP_INI_ALL
html_errorsbooleanTurns HTML tags off in error messages.“1” PHP_INI_ALL
xmlrpc_errorsbooleanFormats errors as XML-RPC error message, turning normal error reporting off.“0”PHP_INI_SYSTEM
xmlrpc_error_numberintegerUsed as the value of the XML-RPC fault Code element.“0”PHP_INI_ALL
docref_rootstringFormat of a new error which contains a reference to a page describing the error or function causing the error.“”PHP_INI_ALL
docref_extstringSpecifies the file extension of the reference page (as mentioned in docref_root).“”PHP_INI_ALL
error_prepend_stringstringString to output before an error message.NULLPHP_INI_ALL
error_append_stringstringString to output after an error message.NULLPHP_INI_ALL
error_logstringName of the file where script errors should be logged.NULLPHP_INI_ALL

PHP error handling – predefined constants

DescriptionList of predefined constants used in PHP 5 for error handling.

Predefined constants

Here is a list of the predefined constants used in PHP 5 for error handling : 

NameTypeDescriptionvalue
E_ERRORintegerExecution of the script comes to a halt. An example is memory allocation problem.1
E_WARNINGintegerExecution of the script is not halted, warnings generated. 2
E_PARSE integerParse errors generated by parsers during compilation.4
E_NOTICE integerRun-time notices which indicated that may be an error took place but may also be a normal course of action.8
E_CORE_ERRORintegerFatal errors that occur during the initial startup of PHP.16
E_CORE_WARNINGintegerWarnings (execution of the script is not halted) that occur during PHP’s initial startup.32
E_COMPILE_ERROR  integerFatal compile-time errors.64
E_COMPILE_WARNING  integerCompile-time warnings, execution of the script is not halted.128
E_USER_ERROR  integerUser-generated error message. 256
E_USER_WARNINGintegerUser-generated warning message. 512
E_USER_NOTICEintegerSame as E_NOTICE. The only difference is, trigger_error() function is used here to generate the error message.1024 
E_STRICTinteger User-generated notice message.2048
E_RECOVERABLE_ERROR integerCatchable fatal error.4096
E_DEPRECATED integerRun-time notices. 8192
E_USER_DEPRECATED integerUser-generated warning message.16384
E_ALL integerAll errors and warnings, as supported. Exception level E_STRICT.30719

All these constants are available in  php.ini of your PHP installation folder.

]]>
855
PHP Session https://shishirkant.com/php-session/?utm_source=rss&utm_medium=rss&utm_campaign=php-session Tue, 26 May 2020 13:33:07 +0000 http://shishirkant.com/?p=852 PHP session has the ability to store information on the server that can be accessed across multiple PHP pages.

In PHP, There are three common methods to pass data from any page to other pages. The Session is one of them. The second method is using Cookies and the third method is PHP Form. However, forms can only pass data between two pages only.


Use of PHP Sessions:

A PHP session is used when you need to store user information and need to access that information on various pages. For example, you save user profile, user preferences, shopping item that can be used later such as on payment page.

This session data is stored temporarily and deleted after a limited time. By default most server has session time out after 24 minutes (session.gc_maxlifetime = 1440) but it can be changed using php.ini file.


Where PHP Session store data:

PHP session store its data in a temporary folder on the server. You can find this temporary folder location inside ‘php.ini’ file configuration using ‘session.save_path’ value.

For example, local/XAMPP ‘session.save_path’ is set as ‘/Applications/XAMPP/xamppfiles/temp/’.

When you start a session:

  • PHP first creates a unique identification string made of 32 hexadecimal numbers.
  • Then, a file is created on the server with the prefix ‘sess_’ and unique identifier for example ‘sess_4a7e9f06243a550c72ca84d28c0610d8’.
  • Then a cookie PHPSESSID is created on a user’s browser to store the same unique session id 4a7e9f06243a550c72ca84d28c0610d8.
  • Now, these two things are used by PHP Session to store data on a server and passing this data to user’s PHP script whenever required.

Start a PHP Session

session_start() function is used to start PHP Session. Once session stared, you can set Session variables using PHP global variable: $_SESSION.

<?php
 
// Start the session
session_start();
 
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
 
// Display session variables
echo "Session variables are set.".$_SESSION["favcolor"].$_SESSION["favanimal"];
 
?>

Now you can access these session variables in any PHP page.

<?php
 
// Start the session
session_start();
 
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
 
// Display session variables
echo "Session variables are set.".$_SESSION["favcolor"].$_SESSION["favanimal"];
 
?>

PHPCopyNote: Note: You need to start the session at the beginning of each page where you want to access the session variables.


Modify a PHP Session Variable

To change a value of any session variable, just overwrite PHP session variable’s value.

<?php
 
// Start the session
session_start();
 
// Set session variables
$_SESSION["favcolor"] = "balck";
$_SESSION["favanimal"] = "dog";
 
echo "Session variables are set.".$_SESSION["favcolor"].$_SESSION["favanimal"];
 
?>

Destroy a PHP Session

Before deleting session data, we need to start the session environment using the session_start() function.

We can remove global session variables and destroy all session data using session_unset() and session_destroy()

If you need to delete only a single session variable, you can use the unset() function. See example below:

<?php
 
// Start the session
session_start();
 
// Display session data before deletion
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.".$_SESSION["favcolor"].$_SESSION["favanimal"];
 
// Destroy session data
// unset($_SESSION["favanimal"]);
session_destroy();
 
// Display session data after deletion
echo "Session variables are set.".$_SESSION["favcolor"].$_SESSION["favanimal"];
 
?>
]]>
852
PHP Cookies https://shishirkant.com/php-cookies/?utm_source=rss&utm_medium=rss&utm_campaign=php-cookies Tue, 26 May 2020 13:23:39 +0000 http://shishirkant.com/?p=849 What is a Cookie

Cookies are used to store the information of a web page in a remote browser, so that when the same user comes back to that page, that information can be retrieved from the browser itself.

In this tutorial, we will discuss how to use Cookies in PHP. We have several examples in this tutorial which will help you to understand the concept and use of a cookie.

Uses of cookie

Cookies are often used to perform following tasks:

  • Session management: Cookies are widely used to manage user sessions. For example, when you use an online shopping cart, you keep adding items in the cart and finally when you checkout, all of those items are added to the list of items you have purchased. This can be achieved using cookies.
  • User identification: Once a user visits a webpage, using cookies, that user can be remembered. And later on, depending upon the search/visit pattern of the user, content which the user likely to be visited are served. A good example of this is ‘Retargetting’. A concept used in online marketing, where depending upon the user’s choice of content, advertisements of the relevant product, which the user may buy, are served.
  • Tracking / Analytics: Cookies are used to track the user. Which, in turn, is used to analyze and serve various kind of data of great value, like location, technologies (e.g. browser, OS) form where the user visited, how long (s)he stayed on various pages etc.

How to create a cookie in PHP

PHP has a setcookie() function to send a cookie. We will discuss this function in detail now.

Usage:

setcookie(name, value, expire, path, domain, secure, httponly)

Parameters:

setcookie() has several parameters. Following table discusses those.

ParameterDescriptionWhich type of data
nameName of the cookie.String
valueValue of the cookie, stored in clients computer.String
expireUnix timestamp, i.e. number of seconds since January 1st, 1970 (called as Unix Epoch).Integer
pathServer path in which the cookie will be available.String
domainTo which domain the cookie is available.String
secureIf set true, the cookie is available over a secure connection only.Boolean
httponlyIf set true, the cookie is available over HTTP protocol only. Scripting languages like JavaScript won’t be able to access the cookie.Boolean

setcookie() returns boolean.

Example:

Following example shows how to create a cookie in PHP. Code first and then some explanation.

<?php
$cookie_value = "shishirkant tutorials";
setcookie("shishirkant", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1);
if (isset($_COOKIE['cookie']))
echo $_COOKIE["shishirkant"];
?>

So, what does the code above does? The first parameter sets the name of the cookie as ‘w3resource’, the second parameter sets the value as ‘w3resource tutorials’, the third parameter states that the cookie will be expired after 3600 seconds (note the way it has been declared, we use time() and then add the number of seconds we wish the cookie must be expired after), the fourth parameter sets path on the server ‘/home/your_name’ where your_name may be an username, so it directs the home directory of a user, the fifth and sixth parameter is set to 1, i.e. true, so the cookie is available over secure connections only and it is available on HTTP protocol only.

echo $_COOKIE["shishirkant"]; simply prints the cookie value. This way you can retrieve a cookie value.

Output:

shishirkant tutorials

How to create a cookie without urlencoding the cookie value

The setcookie() sends a cookie by urlencoding the cookie value. If you want to send a cookie without urlencoding the cookie value, you have to use setrawcookie().

This function has all the parameters which setcookie() has, and the return value is also boolean.

PHP $_COOKIE autoglobal

If a cookie is successfully sent to you from the client, it is available in $_COOKIE, which is automatically global in PHP, if the variables_order directive in php.ini is set to C.

The following code shows how to use $_COOKIE.

<?php
$cookie_value = "shishirkant tutorials";
setcookie("shishirkant", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1);
echo 'Hi ' . htmlspecialchars($_COOKIE["shishirkant"]);
?>

If you wish to retreive all the cookies, you may use the following command

<?php
print_r($_COOKIE);
?>

headers already sent problem because of cookies

PHP Cookies are part of the HTTP header. Therefore, in a PHP script, if it is not set before any another output is sent to the browser, you will get a warning like “…headers already sent….”.

To get rid of the problem, you may use “Output buffering functions”. Following code shows how to add an output buffering function.

<?php
ob_start(); //at the begining of the php script
//your code goes here
//add these two lines at the end of the script
$stuff = ob_get_clean();
echo $stuff;
?>

How to delete a cookie

To delete a cookie value, you may set the expiry time of the cookie in the past. In the following code snippet, cookie expiry time is set one hour before.

<?php
$cookie_value = "shishirkant  tutorials";
setcookie("shishirkant", $cookie_value, time()-3600, "/home/your_usename/", "example.com", 1, 1);
?>

Javascript cookies vs php cookies

This may confuse you if you are just starting out with web programming. But in practice, Cookies are defined by RFC 2965. It is a standard which can be used any programming language. It has nothing to do with PHP vs JavaScript. In PHP, as we have seen in the first example of this tutorial, that cookies can be set such a way that it can’t be accessed by client side JavaScript, but that is a programming feature only.

Cookies vs Sessions

Both cookies and sessions are used for storing persistent data. But there are differences for sure.

Sessions are stored on server side. Cookies are on the client side.

Sessions are closed when the user closes his browser. For cookies, you can set time that when it will be expired.

Sessions are safe that cookies. Because, since stored on client’s computer, there are ways to modify or manipulate cookies.

Hopefully, this tutorial about PHP cookies is useful for you. Let us know if you have questions or suggestions.

]]>
849
PHP Include and Require https://shishirkant.com/php-include-and-require/?utm_source=rss&utm_medium=rss&utm_campaign=php-include-and-require Tue, 26 May 2020 12:59:04 +0000 http://shishirkant.com/?p=844 File Inclusion

The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.
Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.

You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file.

  • The include() Function
  • The require() Function

This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file.


include() Function

The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.

<?php
echo "Learn Online Free Courses – Web Tutorials – Articles – Interview Questions – Tips for IT Professionals . " shishirkant.com";
?>

<html>
<body>
<?php include 'header.php';?>
<h1>Welcome to our website shishirkant.com!
<p>Some text.
<p>Some more text.
</body>
</html>

require() Function

The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.

So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.

<?php
echo "<p>Learn Online Free Courses – Web Tutorials – Articles – Interview Questions – Tips for IT Professionals
 . " shishirkant.com</p>";
?>
<html>
<body>

<?php include 'header1.php';?>
<h1>Welcome to our website shishirkant.com!</h1>
<p>Some text.</p>
<p>Some more text.</p>

</body>
</html>

If we do the same example using the require statement, the echo statement will not be executed because the script execution dies after the require statement returned a fatal error:


Common Mistakes in PHP File Inclusion

If you find error while including PHP file, check following things:

  1. While using full path, do not forget to include http// in url. Form example: <?php include 'http://localhost/includes/header.php'; ?>
  2. While including file from the same folder, just use file name: <?php include 'header.php'; ?>
  3. While including file from the sub-folder, just includes subfolders name (but not localhost or htdocs)
  4. Make sure your file exists at given path with proper file name and extension.
]]>
844