Author: Pooja Kotwani

  • PHP Intl Functions

    The intl extension in PHP provides capabilities for internationalization (i18n) and localization (l10n), supporting features like locale-aware formatting, transliteration, and message formatting. Below is a list of key functions provided by the intl extension.

    Collator

    1. collator_asort(): Sort array maintaining index association.
    collator_asort(Collator $coll, array &$arr, int $sort_flag = Collator::SORT_REGULAR): bool;

    chgrp(): Changes the group ownership of a file.

    chgrp($filename, $group);

    collator_compare(): Compare two Unicode strings.

    collator_compare(Collator $coll, string $str1, string $str2): int;

    collator_get_attribute(): Get an attribute value.

    collator_get_attribute(Collator $coll, int $attr): int|false;

    collator_get_error_code(): Get collator’s last error code.

    collator_get_error_code(Collator $coll): int;

    collator_get_error_message(): Get text for collator’s last error code.

    collator_get_error_message(Collator $coll): string;

    collator_get_locale(): Get the locale name of the collator.

    collator_get_locale(Collator $coll, int $type): string|false;

    collator_get_sort_key(): Get sorting key for a string.

    collator_get_sort_key(Collator $coll, string $string): string|false;

    collator_get_strength(): Get the collator’s strength.

    collator_get_strength(Collator $coll): int;

    collator_set_attribute(): Set an attribute value.

    collator_set_attribute(Collator $coll, int $attr, int $val): bool;

    collator_set_strength(): Set the collator’s strength.

    collator_set_strength(Collator $coll, int $strength): bool;

    collator_sort(): Sort an array.

    collator_sort(Collator $coll, array &$arr, int $sort_flag = Collator::SORT_REGULAR): bool;

    collator_sort_with_sort_keys(): Sort array using specified sort keys.

    collator_sort_with_sort_keys(Collator $coll, array &$arr): bool;

    NumberFormatter

    numfmt_create(): Create a number formatter.

    numfmt_create(string $locale, int $style, ?string $pattern = null): ?NumberFormatter;

    numfmt_format(): Format a number.

    numfmt_format(NumberFormatter $fmt, int|float $num, int $type = NumberFormatter::TYPE_DEFAULT): string|false;

    numfmt_format_currency(): Format a currency value.

    numfmt_format_currency(NumberFormatter $fmt, float $value, string $currency): string|false;

    numfmt_get_attribute(): Get an attribute value.

    fgetcsv($handle, $length, $delimiter, $enclosure, $escape);

    fgets(): Gets a line from a file pointer.

    numfmt_get_attribute(NumberFormatter $fmt, int $attr): int|float|false;

    numfmt_get_error_code(): Get formatter’s last error code.

    numfmt_get_error_code(NumberFormatter $fmt): int;

    numfmt_get_error_message(): Get text for formatter’s last error code.

    numfmt_get_error_message(NumberFormatter $fmt): string;

    numfmt_get_locale(): Get the locale name of the formatter.

    numfmt_get_locale(NumberFormatter $fmt, int $type): string|false;

    numfmt_get_pattern(): Get formatter pattern.

    file_exists($filename);

    numfmt_get_symbol(): Get a symbol value.

    numfmt_get_symbol(NumberFormatter $fmt, int $attr): string|false;

    numfmt_get_text_attribute(): Get a text attribute value.

    numfmt_get_text_attribute(NumberFormatter $fmt, int $attr): string|false;

    numfmt_parse(): Parse a number.

    numfmt_parse(NumberFormatter $fmt, string $value, int $type = NumberFormatter::TYPE_DOUBLE, &$position = null): int|float|false;

    numfmt_parse_currency(): Parse a currency number.

    numfmt_parse_currency(NumberFormatter $fmt, string $value, string &$currency, &$position = null): float|false;

    numfmt_set_attribute(): Set an attribute value.

    numfmt_set_attribute(NumberFormatter $fmt, int $attr, int|float $value): bool;

    numfmt_set_pattern(): Set formatter pattern.

    numfmt_set_pattern(NumberFormatter $fmt, string $pattern): bool;

    numfmt_set_symbol(): Set a symbol value.

    numfmt_set_symbol(NumberFormatter $fmt, int $attr, string $value): bool;

    MessageFormatter

    msgfmt_create(): Create a message formatter.

    msgfmt_create(string $locale, string $pattern): ?MessageFormatter;

    msgfmt_format(): Format the message.

    msgfmt_format(MessageFormatter $fmt, array $args): string|false;

    msgfmt_format_message(): Quick format message.

    msgfmt_format_message(string $locale, string $pattern, array $args): string|false;

    msgfmt_get_error_code(): Get formatter’s last error code.

    msgfmt_get_error_code(MessageFormatter $fmt): int;

    msgfmt_get_error_message(): Get text for formatter’s last error code.

    msgfmt_get_error_message(MessageFormatter $fmt): string;

    msgfmt_get_locale(): Get the locale name of the formatter.

    msgfmt_get_locale(MessageFormatter $fmt): string|false;

    msgfmt_get_locale(MessageFormatter $fmt): string|false;

    msgfmt_get_locale(MessageFormatter $fmt): string|false;

    msgfmt_get_pattern(): Get formatter pattern.

    msgfmt_get_pattern(MessageFormatter $fmt): string|false;

    msgfmt_parse(): Parse input string.

    msgfmt_parse(MessageFormatter $fmt, string $value): array|false;

    msgfmt_parse_message(): Quick parse input string.

    msgfmt_parse_message(string $locale, string $pattern, string $source): array|false;

    msgfmt_set_pattern(): Set formatter pattern.

    msgfmt_set_pattern(MessageFormatter $fmt, string $pattern): bool;

    Normalizer

    normalizer_is_normalized(): Checks if the provided string is already in the specified normalization form.

    normalizer_is_normalized(string $input, int $form = Normalizer::FORM_C): bool;

    normalizer_normalize(): Normalizes the input provided and returns the normalized string.

    normalizer_normalize(string $input, int $form = Normalizer::FORM_C): string|false;

    ResourceBundle

    resourcebundle_create(): Create a resource bundle.

    resourcebundle_create(string $locale, string $bundlename, bool $fallback): ?ResourceBundle;

    resourcebundle_count(): Get the number of elements in the bundle.

    resourcebundle_count(ResourceBundle $bundle): int;

    resourcebundle_get(): Get data from the bundle.

    resourcebundle_get(ResourceBundle $bundle, int|string $index): mixed;

    resourcebundle_get_error_message(): Get text for bundle’s last error code.

    resourcebundle_get_error_message(ResourceBundle $bundle): string;

    resourcebundle_get_error_code(): Get bundle’s last error code.

    resourcebundle_get_error_code(ResourceBundle $bundle): int;

    resourcebundle_locales(): Get supported locales.

    resourcebundle_locales(string $bundlename): array|false;
  • PHP Filesystem Functions Complete Reference

    PHP Filesystem Functions Complete Reference

    basename()
    Description: Return the filename from a given path.
    Example:

    echo basename("/path/to/file.txt");
    // Output: file.txt

    chgrp()
    Description: Change the user group of a specified file.
    Example:

    chgrp("example.txt", "users");
    // Output: (changes the group to 'users')

    chmod()
    Description: Modify file permissions to a specified mode.
    Example:

    chmod("example.txt", 0755);
    // Output: (sets permissions to 755)

    chown()
    Description: Assign a new owner to a specified file.
    Example:

    chown("example.txt", "newowner");
    // Output: (changes the owner to 'newowner')

    copy()
    Description: Create a copy of a specified file.
    Example:

    copy("source.txt", "copy.txt");
    // Output: (creates a duplicate of 'source.txt' as 'copy.txt')

    dirname()
    Description: Get the directory path from a file path.
    Example:

    echo dirname("/path/to/file.txt");
    // Output: /path/to

    disk_free_space()
    Description: Determine the free space in a specified directory.
    Example:

    echo disk_free_space("/");
    // Output: (returns free space in bytes)

    disk_total_space()
    Description: Retrieve the total storage capacity of a specified directory.
    Example:

    echo disk_total_space("/");
    // Output: (returns total space in bytes)

    fclose()
    Description: Close a file pointer that is currently open.
    Example:

    $file = fopen("example.txt", "r");
    fclose($file);
    // Output: (closes 'example.txt')

    feof()
    Description: Check if the end-of-file has been reached on a file pointer.
    Example:

    $file = fopen("example.txt", "r");
    while (!feof($file)) {
        echo fgets($file);
    }
    fclose($file);
    // Output: (reads until end of file)

    fflush()
    Description: Flush the output buffer to an open file.
    Example:

    $file = fopen("example.txt", "a");
    fwrite($file, "New content");
    fflush($file);
    fclose($file);
    // Output: (writes 'New content' and flushes buffer)

    fgetc()
    Description: Retrieve a single character from an open file.
    Example:

    $file = fopen("example.csv", "w");
    fputcsv($file, ["Name", "Age", "City"]); // Writes CSV line
    fclose($file);

    fgets()
    Description: Read a line from a file pointer.
    Example:

    $file = fopen("example.txt", "r");
    echo fgets($file);
    fclose($file);
    // Output: (reads and outputs the first line)

    fgetss()
    Description: Read a line from a file while stripping out HTML and PHP tags.
    Example:

    $file = fopen("example.txt", "r");
    echo fgetss($file);
    fclose($file);
    // Output: (outputs the line without HTML tags)

    file_exists()
    Description: Check if a file or directory exists.
    Example:

    echo file_exists("example.txt") ? "Exists" : "Does not exist";
    // Output: Exists or Does not exist

    file_get_contents()
    Description: Read the entire file content into a string.
    Example:

    echo file_get_contents("example.txt");
    // Output: (displays file contents as a string)

    file_put_contents()
    Description: Write a string to a file.
    Example:

    file_put_contents("example.txt", "Some content");
    // Output: (writes 'Some content' to 'example.txt')

    fileatime()
    Description: Retrieve the last access time of a specified file.
    Example:

    echo date("F d Y H:i:s", fileatime("example.txt"));
    // Output: (displays last access date and time)

    filesize()
    Description: Get the size of a specified file in bytes.
    Example:

    echo filesize("example.txt");
    // Output: (file size in bytes)

    filectime()
    Description: Get the last change time of a specified file.
    Example:

    echo date("F d Y H:i:s", filectime("example.txt"));
    // Output: (displays last change date and time)

    filemtime()
    Description:Return the last modified time of a specified file.
    Example:

    echo date("F d Y H:i:s", filemtime("example.txt"));
    // Output: (displays last modified date and time)

    fileperms()
    Description: Retrieve the permissions for a file or directory.
    Example:

    echo substr(sprintf('%o', fileperms("example.txt")), -4);
    // Output: (displays permissions, e.g., 0755)

    filesize()
    Description: Get the size of a specified file in bytes.
    Example:

    echo filesize("example.txt");
    // Output: (file size in bytes)

    filetype()
    Description: Determine the type of file.
    Example:

    echo filetype("example.txt");
    // Output: file or dir

    flock()
    Description: Apply a portable advisory lock on the file.
    Example:

    $file = fopen("example.txt", "r+");
    if (flock($file, LOCK_EX)) {
        // Do something
        flock($file, LOCK_UN);
    }
    fclose($file);
    // Output: (locks and unlocks the file)

    fopen()
    Description: Open a file or URL.
    Example:

    $file = fopen("example.txt", "r");
    // Output: (opens 'example.txt' for reading)

    fpassthru()
    Description: Output all remaining data from a file pointer until EOF.
    Example:

    The variable is an integer.
    The variable is a string.

    fputcsv()
    Description: Write a line of CSV formatted data to a file.
    Example:

    $file = fopen("data.csv", "w");
    fputcsv($file, ["Name", "Age"]);
    fclose($file);
    // Output: (writes "Name, Age" to 'data.csv')

    fread()
    Description: Read up to a specified length of bytes from a file.
    Example:

    $file = fopen("example.txt", "r");
    echo fread($file, 100);
    fclose($file);
    // Output: (displays first 100 bytes)

    fseek()
    Description: Set the file pointer to a specified position.
    Example:

    $file = fopen("example.txt", "r");
    fseek($file, 5);
    echo fgets($file);
    fclose($file);
    // Output: (displays content starting from position 5)

    fstat()
    Description: Return information about an open file.
    Example:

    $file = fopen("example.txt", "r");
    print_r(fstat($file));
    fclose($file);
    // Output: (displays file info array)

    ftell()
    Description: Get the current position of the file pointer.
    Example:

    $file = fopen("example.txt", "r");
    echo ftell($file);
    fclose($file);
    // Output: (current file pointer position)

    ftruncate()
    Description: Truncate a file to a specified length.
    Example:

    $file = fopen("example.txt", "r+");
    ftruncate($file, 50);
    fclose($file);
    // Output: (shortens file to 50 bytes)

    fwrite()
    Description: Write a string to a file.
    Example:

    $file = fopen("example.txt", "w");
    fwrite($file, "PHP Filesystem Functions");
    fclose($file);
    // Output: (writes text to 'example.txt')

    is_dir()
    Description: Check if a path is a directory.
    Example:

    echo is_dir("/path/to/directory") ? "Directory" : "Not a directory";
    // Output: Directory or Not a directory

    is_executable()
    Description: Determine if a file is executable.
    Example:

    echo is_executable("script.sh") ? "Executable" : "Not executable";
    // Output: Executable or Not executable

    is_file()
    Description: Verify if a path is a regular file.
    Example:

    echo is_file("example.txt") ? "File" : "Not a file";
    // Output: File or Not a file

    is_link()
    Description: Check if a specified file is a symbolic link.
    Example:

    echo is_link("example_link") ? "Symbolic link" : "Not a symbolic link";
    // Output: Symbolic link or Not a symbolic link

    is_readable()
    Description: Determine if a file exists and is readable.
    Example:

    echo is_readable("example.txt") ? "Readable" : "Not readable";
    // Output: Readable or Not readable

    is_uploaded_file()
    Description: Check if a file was uploaded via HTTP POST.
    Example:

    echo is_uploaded_file($_FILES['file']['tmp_name']) ? "Uploaded" : "Not uploaded";
    // Output: Uploaded or Not uploaded

    is_writable()
    Description: Verify if a file is writable.
    Example:

    echo is_writable("example.txt") ? "Writable" : "Not writable";
    // Output: Writable or Not writable

    link()
    Description: Create a hard link for a specified target.
    Example:

    link("target.txt", "hardlink.txt");
    // Output: (creates a hard link 'hardlink.txt' pointing to 'target.txt')

    lstat()
    Description: Retrieve information about a file or symbolic link.
    Example:

    print_r(lstat("example.txt"));
    // Output: (array of file or symbolic link information)

    popen()
    Description: Open a pipe to a specified command.
    Example:

    $pipe = popen("ls", "r");
    // Output: (opens a pipe to list directory contents)

    pclose()
    Description: Close a pipe opened by popen().
    Example:

    $pipe = popen("ls", "r");
    pclose($pipe);
    // Output: (closes the pipe to the command 'ls')

    pathinfo()
    Description: Get information about a path as an associative array or string.
    Example:

    print_r(pathinfo("example.txt"));
    // Output: (displays path info, e.g., directory, basename, extension)

    readfile()
    Description: Read a file and output it directly to the buffer.
    Example:

    readfile("example.txt");
    // Output: (displays contents of 'example.txt')

    rename()
    Description: Rename a file or directory.
    Example:

    rename("oldname.txt", "newname.txt");
    // Output: (changes 'oldname.txt' to 'newname.txt')

    realpath()
    Description: Return the canonical absolute pathname.
    Example:

    echo realpath("example.txt");
    // Output: (full path to 'example.txt')

    rewind()
    Description: Set the file pointer to the beginning of a file.
    Example:

    $file = fopen("example.txt", "r");
    rewind($file);
    fclose($file);
    // Output: (moves file pointer to start)

    stat()
    Description: Retrieve detailed information about a file.
    Example:

    print_r(stat("example.txt"));
    // Output: (array of file statistics)

    symlink()
    Description: Create a symbolic link pointing to a specified target.
    Example:

    symlink("target.txt", "symbolic_link.txt");
    // Output: (creates symbolic link 'symbolic_link.txt' to 'target.txt')

    tmpfile()
    Description: Create a temporary file in read-write mode.
    Example:

    $temp = tmpfile();
    fwrite($temp, "Temporary data");
    fclose($temp);
    // Output: (creates and closes a temporary file)

    touch()
    Description: Set the access and modification times for a file.
    Example:

    touch("example.txt");
    // Output: (updates 'example.txt' timestamp)

    unlink()
    Description: Delete a file.
    Example:

    unlink("example.txt");
    // Output: (removes 'example.txt')
  • PHP Math Functions Complete Reference

    PHP Math Functions Complete Reference

    PHP Math Functions

    PHP includes a range of predefined mathematical functions that facilitate operations on integer and float types. These functions are integrated into the PHP core and require no installation.

    Example: Using the decbin() function in PHP:

    <?php
    echo decbin(12);
    ?>

    abs()
    Description: Return the absolute (positive) value of a number.
    Example:

    echo abs(-10);
    // Output: 10

    acos()
    Description: Find the arc cosine of a number, returning the result in radians.
    Example:

    echo acos(0.5);
    // Output: 1.0471975511966

    acosh()
    Description: Calculate the inverse hyperbolic cosine of a number.
    Example:

    echo acosh(2);
    // Output: 1.3169578969248

    asin()
    Description: Calculate the arc sine of a number in radians.
    Example:

    echo asin(0.5);
    // Output: 0.5235987755983

    asinh()
    Description: Find the inverse hyperbolic sine of a number
    Example:.

    echo asinh(1);
    // Output: 0.88137358701954

    atan2()
    Description: Calculate the arc tangent of two numbers x and y.
    Example:

    echo atan2(1, 1);
    // Output: 0.78539816339745

    atan()
    Description: Return the arc tangent of a number, result in radians.
    Example:

    echo atan(1);
    // Output: 0.78539816339745

    atanh()
    Description: Find the inverse hyperbolic tangent of a number.
    Example:

    $file = fopen("example.txt", "r");
    echo fgets($file); // Outputs one line
    fclose($file);

    base_convert()
    Description: Convert a number from one base to another.
    Example:

    echo base_convert("A1", 16, 2);
    // Output: 10100001

    bindec()
    Description: Convert a binary string to its decimal equivalent.
    Example:

    echo bindec("1101");
    // Output: 13

    ceil()
    Description: Round a number up to the nearest integer.
    Example:

    echo ceil(4.3);
    // Output: 5

    cos()
    Description: Find the cosine of a number (in radians).
    Example:

    echo cos(1);
    // Output: 0.54030230586814

    cosh()
    Description: Calculate the hyperbolic cosine of a number.
    Example:

    echo cosh(1);
    // Output: 1.5430806348152

    decbin()
    Description: Convert a decimal number to binary.
    Example:

    echo decbin(12);
    // Output: 1100

    dechex()
    Description: Convert a decimal number to hexadecimal.
    Example:

    echo dechex(255);
    // Output: ff

    decoct()
    Description: Convert a decimal number to octal.
    Example:

    echo decoct(15);
    // Output: 17

    deg2rad()
    Description: Convert degrees to radians.
    Example:

    echo deg2rad(180);
    // Output: 3.1415926535898

    exp()
    Description: Calculate e raised to the power of a given number.
    Example:

    echo exp(2);
    // Output: 7.3890560989306

    expm1()
    Description: Calculate e raised to the power of a given number minus one.
    Example:

    echo expm1(1);
    // Output: 1.718281828459

    hypot()
    Description: Returns the square root of the sum of squares of two numbers.
    Example:

    echo hypot(3, 4);
    // Output: 5

    fmod()
    Description: Calculate the remainder of a division (modulo operation).
    Example:

    echo fmod(5.7, 1.3);
    // Output: 0.5

    hexdec()
    Description: Convert a hexadecimal string to its decimal equivalent.
    Example:

    echo hexdec("ff");
    // Output: 255

    hypot()
    Description: Calculate the length of the hypotenuse of a right-angled triangle.
    Example:

    echo hypot(3, 4);
    // Output: 5

    intdiv()
    Description: Calculate the integer quotient of the division of two numbers.
    Example:

    echo intdiv(7, 3);
    // Output: 2

    is_finite()
    Description: Check if a number is finite.
    Example:

    echo is_finite(1.2e308) ? "Finite" : "Infinite";
    // Output: Finite

    is_infinite()
    Description: Check if a number is infinite.
    Example:

    echo is_infinite(1.2e308 * 10) ? "Infinite" : "Finite";
    // Output: Infinite

    is_nan()
    Description: Check if a value is ‘not a number’.
    Example:

    echo is_nan(acos(2)) ? "Not a number" : "Number";
    // Output: Not a number

    is_readable()
    Description: Determine if a file exists and is readable.
    Example:

    echo is_readable("example.txt") ? "Readable" : "Not readable";
    // Output: Readable or Not readable

    is_uploaded_file()
    Description: Check if a file was uploaded via HTTP POST.
    Example:

    echo is_uploaded_file($_FILES['file']['tmp_name']) ? "Uploaded" : "Not uploaded";
    // Output: Uploaded or Not uploaded

    is_writable()
    Description: Verify if a file is writable.
    Example:

    echo is_writable("example.txt") ? "Writable" : "Not writable";
    // Output: Writable or Not writable

    link()
    Description: Create a hard link for a specified target.
    Example:

    link("target.txt", "hardlink.txt");
    // Output: (creates a hard link 'hardlink.txt' pointing to 'target.txt')

    lstat()
    Description: Retrieve information about a file or symbolic link.
    Example:

    print_r(lstat("example.txt"));
    // Output: (array of file or symbolic link information)

    mkdir()
    Description: Create a new directory with the specified path.
    Example:

    mkdir("new_folder");
    // Output: (creates 'new_folder' directory)

    pathinfo()
    Description: Get information about a path as an associative array or string.
    Example:

    print_r(pathinfo("example.txt"));
    // Output: (displays path info, e.g., directory, basename, extension)

    pclose()
    Description: Close a pipe opened by popen().
    Example:

    $pipe = popen("ls", "r");
    pclose($pipe);
    // Output: (closes the pipe to the command 'ls')

    popen()
    Description: Open a pipe to a specified command.
    Example:

    $pipe = popen("ls", "r");
    // Output: (opens a pipe to list directory contents)

    readfile()
    Description: Read a file and output it directly to the buffer.
    Example:

    readfile("example.txt");
    // Output: (displays contents of 'example.txt')

    realpath()
    Description: Return the canonical absolute pathname.
    Example:

    echo realpath("example.txt");
    // Output: (full path to 'example.txt')

    rewind()
    Description: Set the file pointer to the beginning of a file.
    Example:

    $file = fopen("example.txt", "r");
    rewind($file);
    fclose($file);
    // Output: (moves file pointer to start)

    stat()
    Description: Retrieve detailed information about a file.
    Example:

    print_r(stat("example.txt"));
    // Output: (array of file statistics)

    symlink()
    Description: Create a symbolic link pointing to a specified target.v Example:

    symlink("target.txt", "symbolic_link.txt");
    // Output: (creates symbolic link 'symbolic_link.txt' to 'target.txt')

    tmpfile()
    Description: Create a temporary file in read-write mode.
    Example:

    $temp = tmpfile();
    fwrite($temp, "Temporary data");
    fclose($temp);
    // Output: (creates and closes a temporary file)

    touch()
    Description: Set the access and modification times for a file.
    Example:

    touch("example.txt");
    // Output: (updates 'example.txt' timestamp)
  • PHP String Functions Complete Reference

    PHP String Functions Complete Reference

    The predefined math functions in PHP are used to handle mathematical operations with integer and float types. These math functions are built into PHP and do not require any additional installation.

    Installation: These functions do not require any special installation. The complete list of PHP math functions is given below:

    Example: A program illustrating the decbin() function in PHP:

    <?php
    echo decbin(45);
    ?>

    Output:

    101101
    List of Common PHP String Functions

    addcslashes()

    Description: Inserts backslashes before specified characters in a string.

    Example:

    echo addcslashes("Hello, World!", 'o');
    // Output: Hell\o, W\orld!

    addslashes()

    Description: Escapes special characters by adding backslashes.
    Example:

    echo addslashes("Hello 'World'");
    // Output: Hello \'World\'

    bin2hex()

    Description: Converts a string to hexadecimal representation.
    Example:

    echo bin2hex("Hi");
    // Output: 4869

    chop()

    Description: Removes whitespace or specified characters from the end of a string.
    Example:

    echo chop("Hello World!  ");
    // Output: Hello World!

    chr()

    Description: Converts ASCII value to a character.
    Example:

    echo chr(65);
    // Output: A

    chunk_split()

    Description: Splits a string into smaller chunks.
    Example:

    echo chunk_split("abcdef", 2, "-");
    // Output: ab-cd-ef-

    convert_uudecode()

    Description: Decodes a uuencoded string.
    Example:

    $encoded = convert_uuencode("Hello");
    echo convert_uudecode($encoded);
    // Output: Hello

    convert_uuencode()

    Description: Encodes a string using the uuencode algorithm.
    Example:

    echo convert_uuencode("Hello");
    // Output: 0=&5S=`IT

    count_chars()

    Description: Returns information about character frequencies in a string.
    Example:

    print_r(count_chars("Hello", 1));
    // Output: Array ( [72] => 1 [101] => 1 [108] => 2 [111] => 1 )

    crc32()

    Description: Calculates the CRC32 polynomial of a string.
    Example:

    echo crc32("Hello");
    // Output: 907060870

    crypt()

    Description: One-way string hashing using algorithms like DES, Blowfish, or MD5.
    Example:

    echo crypt("mypassword", "salt");
    // Output: saGng5vH/kMmQ

    password_hash()

    Description: Creates a password hash using the bcrypt algorithm.
    Example:

    echo password_hash("mypassword", PASSWORD_DEFAULT);
    // Output: $2y$10$...

    echo()

    Description: Outputs one or more strings.
    Example:

    echo "Hello", " World!";
    // Output: Hello World!

    explode()

    Description: Splits a string by a specified delimiter into an array.
    Example:

    print_r(explode(" ", "Hello World"));
    // Output: Array ( [0] => Hello [1] => World )

    hex2bin()

    Description: Converts a hexadecimal string to binary.
    Example:

    echo hex2bin("48656c6c6f");
    // Output: Hello

    implode()

    Description: Joins array elements into a single string.
    Example:

    echo implode(", ", array("apple", "banana", "cherry"));
    // Output: apple, banana, cherry

    lcfirst()

    Description: Converts the first character of a string to lowercase.
    Example:

    echo lcfirst("HELLO");
    // Output: hELLO

    levenshtein()

    Description: Returns the Levenshtein distance between two strings.
    Example:

    echo levenshtein("kitten", "sitting");
    // Output: 3

    ltrim()

    Description: Strips whitespace from the beginning of a string.
    Example:

    echo ltrim("    Hello");
    // Output: Hello

    md5_file()

    Description: Generates the MD5 hash of a file.
    Example:

    echo md5_file("example.txt");
    // Output: 5d41402abc4b2a76b9719d911017c592

    md5()

    Description: Generates the MD5 hash of a string.
    Example:

    echo md5("Hello World");
    // Output: b10a8db164e0754105b7a99be72e3fe5

    metaphone()

    Description: Computes the metaphone key of a string for phonetic comparisons.
    Example:

    echo metaphone("example");
    // Output: EXMPL

    nl2br()

    Description: Inserts HTML line breaks before newlines in a string.
    Example:

    echo nl2br("Hello\nWorld!");
    // Output: Hello<br />World!
  • PHP Array Functions

    PHP Array Functions

    array_chunk()

    Description:Splits an array into chunks of a specified size.

    Example:

    $array = array(1, 2, 3, 4, 5, 6);
    print_r(array_chunk($array, 2));
    // Output:
    // Array
    // (
    //     [0] => Array ( [0] => 1 [1] => 2 )
    //     [1] => Array ( [0] => 3 [1] => 4 )
    //     [2] => Array ( [0] => 5 [1] => 6 )
    // )

    array_combine()

    Description:Creates an array by combining one array as keys and another array as values.

    Example:

    $keys = array('fruit', 'vegetable');
    $values = array('apple', 'carrot');
    print_r(array_combine($keys, $values));
    // Output:
    // Array
    // (
    //     [fruit] => apple
    //     [vegetable] => carrot
    // )

    array_count_values()

    Description:Counts the occurrences of all values in an array.

    Example:

    $array = array(1, "hello", 1, "world", "hello");
    print_r(array_count_values($array));
    // Output:
    // Array
    // (
    //     [1] => 2
    //     [hello] => 2
    //     [world] => 1
    // )

    array_diff()

    Description:Computes the difference between two or more arrays.

    Example:

    $array1 = array("a" => "green", "b" => "brown", "c" => "blue");
    $array2 = array("a" => "green", "yellow", "red");
    print_r(array_diff($array1, $array2));
    // Output:
    // Array
    // (
    //     [b] => brown
    //     [c] => blue
    // )

    array_fill()

    Description:Fills an array with a specified value, starting from a specified index.

    Example:

    print_r(array_fill(3, 5, "apple"));
    // Output:
    // Array
    // (
    //     [3] => apple
    //     [4] => apple
    //     [5] => apple
    //     [6] => apple
    //     [7] => apple
    // )

    array_filter()

    Description:Filters elements of an array using a callback function.

    Example:

    $array = array(1, 2, 3, 4, 5, 6);
    print_r(array_filter($array, function($value) { return $value % 2 == 0; }));
    // Output:
    // Array
    // (
    //     [1] => 2
    //     [3] => 4
    //     [5] => 6
    // )

    array_flip()

    Description:Exchanges keys and values in an array.

    Example:

    $array = array("a" => "apple", "b" => "banana", "c" => "cherry");
    print_r(array_flip($array));
    // Output:
    // Array
    // (
    //     [apple] => a
    //     [banana] => b
    //     [cherry] => c
    // )

    array_key_exists()

    Description:Checks if a specified key exists within an array.

    Example:

    $array = array("fruit" => "apple", "vegetable" => "carrot");
    echo array_key_exists("fruit", $array) ? "Key exists" : "Key does not exist";
    // Output: Key exists

    array_merge()

    Description:Merges one or more arrays into a single array.

    Example:

    $array1 = array("color" => "red", 2, 4);
    $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
    print_r(array_merge($array1, $array2));
    // Output:
    // Array
    // (
    //     [color] => green
    //     [0] => 2
    //     [1] => 4
    //     [2] => a
    //     [3] => b
    //     [shape] => trapezoid
    //     [4] => 4
    // )

    array_reverse()

    Description:Reverses the order of elements in an array.

    Example:

    $array = array("a", "b", "c", "d");
    print_r(array_reverse($array));
    // Output:
    // Array
    // (
    //     [0] => d
    //     [1] => c
    //     [2] => b
    //     [3] => a
    // )

    array_search()

    Description:Searches for a value in an array and returns the corresponding key if found.

    Example:

    $array = array(0 => 'blue', 1 => 'red', 2 => 'green');
    echo array_search('green', $array);
    // Output: 2

    array_sum()

    Description:Returns the sum of all values in an array.

    Example:

    $array = array(2, 4, 6, 8);
    echo array_sum($array);
    // Output: 20

    array_unique()

    Description:Removes duplicate values from an array.

    Example:

    $array = array("apple", "banana", "apple", "orange");
    print_r(array_unique($array));
    // Output:
    // Array
    // (
    //     [0] => apple
    //     [1] => banana
    //     [3] => orange
    // )

    array_values()

    Description:Returns all the values from an array, with numeric keys starting from 0.

    Example:

    $array = array("size" => "large", "color" => "red");
    print_r(array_values($array));
    // Output:
    // Array
    // (
    //     [0] => large
    //     [1] => red
    // )

    compact()

    Description:Create an array using variables as keys and their values as elements.

    Example:

    $name = "John";
    $age = 30;
    print_r(compact("name", "age"));
    // Output: Array ( [name] => John [age] => 30 )

    count()

    Description:Count the total number of elements in an array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo count($array);
    // Output: 3

    current()

    Description:Return the value of the element at the internal pointer in an array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo current($array);
    // Output: apple

    end()

    Description:Find the last element of a given array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo end($array);
    // Output: cherry

    extract()

    Description:Convert array elements into variables.

    Example:

    $array = array("name" => "John", "age" => 30);
    extract($array);
    echo $name;
    // Output: John

    in_array()

    Description:Check if a specific value exists in an array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo in_array("banana", $array) ? "Found" : "Not found";
    // Output: Found

    key()

    Description:Return the current index or key of an array where the internal pointer points.

    Example:

    $array = array("a" => "apple", "b" => "banana");
    echo key($array);
    // Output: a

    krsort()

    Description:Sort an array by its keys in descending order.

    Example:

    $array = array("a" => "apple", "c" => "cherry", "b" => "banana");
    krsort($array);
    print_r($array);
    // Output: Array ( [c] => cherry [b] => banana [a] => apple )

    list()

    Description:Assign array values to multiple variables.

    Example:

    $array = array("apple", "banana", "cherry");
    list($fruit1, $fruit2) = $array;
    echo $fruit1;
    // Output: apple

    natcasesort()

    Description:Sort an array using natural order, case-insensitively.

    Example:

    $array = array("Image2.jpg", "image10.jpg", "Image1.jpg");
    natcasesort($array);
    print_r($array);
    // Output: Array ( [0] => Image1.jpg [2] => Image2.jpg [1] => image10.jpg )

    natsort()

    Description:Sort an array using a “natural order” algorithm without regard to case.

    Example:

    $array = array("Image2.jpg", "image10.jpg", "Image1.jpg");
    natsort($array);
    print_r($array);
    // Output: Array ( [2] => Image1.jpg [0] => Image2.jpg [1] => image10.jpg )

    next()

    Description:Move the internal pointer to the next element and return its value.

    Example:

    $array = array("apple", "banana", "cherry");
    echo next($array);
    // Output: banana

    pos()

    Description:Return the value of the current element of an array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo pos($array);
    // Output: apple

    prev()

    Description:Move the internal pointer to the previous element and return its value.

    Example:

    $array = array("apple", "banana", "cherry");
    next($array);
    echo prev($array);
    // Output: apple

    range()

    Description:Create an array with elements within a specified range.

    Example:

    print_r(range(0, 5));
    // Output: Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 )

    reset()

    Description:Move the internal pointer to the first element of an array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo reset($array);
    // Output: apple

    rsort()

    Description:Sort an array in descending order.

    Example:

    $array = array(3, 1, 2);
    rsort($array);
    print_r($array);
    // Output: Array ( [0] => 3 [1] => 2 [2] => 1 )

    shuffle()

    Description:Randomize the order of elements in an array.

    Example:

    $array = array("apple", "banana", "cherry");
    shuffle($array);
    print_r($array);
    // Output: (random order, e.g., Array ( [0] => banana [1] => cherry [2] => apple ))

    sizeof()

    Description:Count the number of elements in an array or countable object.

    Example:

    $array = array("apple", "banana", "cherry");
    echo sizeof($array);
    // Output: 3

    sort()

    Description:Sort an array in ascending order.

    Example:

    $array = array(3, 1, 2);
    sort($array);
    print_r($array);
    // Output: Array ( [0] => 1 [1] => 2 [2] => 3 )

    uasort()

    Description:Sort an array while maintaining index association, using a user-defined function.

    Example:

    $array = array("a" => 3, "b" => 1, "c" => 2);
    uasort($array, function($x, $y) { return $x <=> $y; });
    print_r($array);
    // Output: Array ( [b] => 1 [c] => 2 [a] => 3 )

    usort()

    Description:Sort an array using a custom comparison function.

    Example:

    $array = array("apple", "banana", "cherry");
    usort($array, function($x, $y) { return strlen($x) <=> strlen($y); });
    print_r($array);
    // Output: Array ( [0] => apple [1] => cherry [2] => banana )
  • MySQL Database

    PHP MySQL Database Introduction

    What is MySQL?

    MySQL is an open-source relational database management system (RDBMS) widely used in conjunction with PHP. It is currently one of the most popular database systems and is developed, distributed, and maintained by Oracle Corporation.

    • Data within a MySQL database is organized into tables consisting of rows and columns.
    • MySQL operates as a server-based database system.
    • It is well-suited for both small and large-scale applications.
    • Known for its speed, reliability, and ease of use, MySQL uses standard SQL (Structured Query Language).
    • MySQL can run on various platforms.
    Downloading MySQL Database

    You can download MySQL for free from the official MySQL website.

    How to Connect PHP to a MySQL Database?

    In PHP version 5 and above, MySQL can be accessed using two primary methods:

    • MySQLi extension.
    • PDO (PHP Data Objects).
    Difference Between MySQLi and PDO
    • PDO supports 12 different types of databases, while MySQLi is exclusively for MySQL databases.
    • Both PDO and MySQLi offer object-oriented interfaces, but MySQLi also provides a procedural interface.
    • If you need to switch your project from MySQL to another database system, PDO allows this with minimal changes to the connection string and a few queries. With MySQLi, you would have to rewrite the entire codebase, including all queries.
    Ways to Work with MySQL in PHP

    There are three primary methods to connect and interact with a MySQL database in PHP:

    1. MySQLi (Object-Oriented)
    2. MySQLi (Procedural)
    3. PDO (PHP Data Objects)

    Connecting to a MySQL Database using PHP

    Below are the three different approaches to connect to a MySQL database from a PHP script.

    1. MySQLi Object-Oriented Approach: You can use the object-oriented approach with MySQLi to create a connection to the MySQL database.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
    ?>

    Output:

    Connected successfully

    2. MySQLi Procedural Approach: You can also establish a connection using MySQLi’s procedural interface.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    // Create connection
    $conn = mysqli_connect($servername, $username, $password);
    
    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    echo "Connected successfully";
    ?>

    Output:

    Connected successfully

    3. PDO Approach: PDO offers a unified interface for connecting to a MySQL database and can be easily adapted for other database systems.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    try {
        $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
        // Set PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
    }
    catch(PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
    ?>

    Output:

    Connected successfully

    PHP MySQL ( Creating Database )

    What is a Database?

    A database is a structured collection of related data that allows efficient storage, retrieval, insertion, and deletion of information. It organizes data into tables, views, schemas, reports, etc., facilitating streamlined data management. For instance, a university database may organize data about students, faculty, and administration, which enables effective data operations such as retrieval and insertion.

    To create a database in MySQL, a SQL query is needed. Here are the steps to create a MySQL database using PHP:

    1. Establish a connection to the MySQL server from the PHP script.
    2. If the connection is successful, write a SQL query to create a database and store it in a string variable.
    3. Execute the query.

    We already know how to establish a connection and create variables in PHP. The query can be executed in three different ways, as shown below:

    1. Using MySQLi Object-Oriented Approach: If the MySQL connection is made using the object-oriented approach, the query() method of the mysqli class is used to run the query.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    // Establishing connection
    $conn = new mysqli($servername, $username, $password);
    
    // Checking connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    // SQL query to create a database named newDB
    $sql = "CREATE DATABASE newDB";
    if ($conn->query($sql) === TRUE) {
        echo "Database created successfully with the name newDB";
    } else {
        echo "Error creating database: " . $conn->error;
    }
    
    // Closing connection
    $conn->close();
    ?>

    Output:

    Database created successfully with the name newDB

    2. Using MySQLi Procedural Approach: If the MySQL connection is established using the procedural approach, the mysqli_query() function is used to execute the query.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    // Establishing connection
    $conn = mysqli_connect($servername, $username, $password);
    
    // Checking connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    
    // SQL query to create a database named newDB
    $sql = "CREATE DATABASE newDB";
    if (mysqli_query($conn, $sql)) {
        echo "Database created successfully with the name newDB";
    } else {
        echo "Error creating database: " . mysqli_error($conn);
    }
    
    // Closing connection
    mysqli_close($conn);
    ?>

    Output:

    Database created successfully with the name newDB

    3. Using PDO Approach: If the connection is made using PDO, the query can be executed as shown below.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    try {
        $conn = new PDO("mysql:host=$servername;dbname=newDB", $username, $password);
        // Setting PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        // SQL query to create a database named newDB
        $sql = "CREATE DATABASE newDB";
    
        // Executing the query using exec() as no results are returned
        $conn->exec($sql);
        echo "Database created successfully with the name newDB";
    }
    catch(PDOException $e) {
        echo $sql . "<br>" . $e->getMessage();
    }
    
    // Closing the connection
    $conn = null;
    ?>

    Output:

    Database created successfully with the name newDB

    PHP Database connection

    The collection of related data is called a database.

    XAMPP is an abbreviation for Cross-Platform, Apache, MySQL, PHP, and Perl. It is a lightweight and straightforward local server used for website development.

    Requirements:

    Procedure to use the XAMPP web server:

    1. Start the XAMPP server by running Apache and MySQL.
    2. Write a PHP script for connecting to the XAMPP server.
    3. Run the script in your local browser.
    4. A database is created based on the PHP code.

    In PHP, we can connect to a database using the XAMPP server by navigating to the following path:

    “localhost/phpmyadmin”

    Steps in Detail:

    1. Open XAMPP and start the Apache, MySQL, and FileZilla services.
    2. Now open your PHP file and write the PHP code to create a database and a table.

    PHP Code to Create a Database:

    <?php
    
    // Server name is typically localhost
    $servername = "localhost";
    
    // Username for XAMPP is generally root
    $username = "root";
    
    // No password by default in XAMPP
    $password = "";
    
    // Establishing a connection
    $conn = new mysqli($servername, $username, $password);
    
    // Checking the connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    // SQL to create a database named myDB
    $sql = "CREATE DATABASE myDB";
    if ($conn->query($sql) === TRUE) {
        echo "Database 'myDB' created successfully";
    } else {
        echo "Error creating database: " . $conn->error;
    }
    
    // Closing the connection
    $conn->close();
    ?>

    Steps to Follow:

    • Save the file as “create_database.php” in the htdocs folder located in your XAMPP installation directory.
    • Open your web browser and navigate to localhost/create_database.php.

    Final Step:

    • The database will be created and connected to PHP.
    • To view your newly created database, type localhost/phpmyadmin in your web browser, and the database will appear.

    Output:

    Database 'myDB' created successfully

    Connect PHP to MySQL

    MySQL can run on a server and is well-suited for both small and large applications. It is known for being fast, reliable, and easy to use. Additionally, it supports SQL standards and is available on multiple platforms.

    How to Connect PHP with MySQL?

    Starting with PHP 5, there are two main ways to interact with MySQL databases:

    • MySQLi extension (where “i” stands for “improved”)
    • PDO (PHP Data Objects)
    Should You Use MySQLi or PDO?

    Both MySQLi and PDO have their advantages:

    • PDO works with 12 different types of databases, whereas MySQLi is specifically designed to work only with MySQL databases.
    • If you foresee switching to another database system, PDO simplifies the transition by only requiring changes to the connection string and some queries. With MySQLi, you would need to rewrite the entire codebase, including queries.
    • Both provide object-oriented interfaces, though MySQLi also offers a procedural API.

    In short, if you are only using MySQL, both are good options, but if you may switch databases, PDO is more flexible.

    Connecting PHP to MySQL

    Using MySQLi (Object-Oriented): Here is how you can establish a connection to a MySQL database using MySQLi in object-oriented style:

    <?php
    $server = "localhost";
    $user = "admin";
    $pass = "admin123";
    
    // Establishing the connection
    $connection = new mysqli($server, $user, $pass);
    
    // Check the connection
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    }
    
    echo "Connection successful!";
    ?>

    Output:

    Connection successful!

    Using MySQLi (Procedural): The procedural approach to connect PHP with MySQL using MySQLi looks like this:

    <?php
    $server = "localhost";
    $user = "admin";
    $pass = "admin123";
    
    // Establishing the connection
    $connection = mysqli_connect($server, $user, $pass);
    
    // Checking the connection
    if (!$connection) {
        die("Connection failed: " . mysqli_connect_error());
    }
    
    echo "Connection successful!";
    ?>

    Output:

    Connection successful!

    PHP MySQL ( Creating Table )

    What is a Table?

    In relational and flat file databases, a table refers to an organized structure where data elements are stored in the form of vertical columns and horizontal rows. Each row represents a data record, and each column represents a specific field. A table has a fixed number of columns but can have an unlimited number of rows. The point where a row and column meet is known as a cell.

    Creating a MySQL Table Using MySQLi and PDO

    The process of creating a table is similar to creating a database. However, instead of creating a new database, you will connect to an existing database and define a table within it. To connect to an existing database, you need to specify the database name during the connection to MySQL.

    The CREATE TABLE statement is used to define a new table.

    In the following example, we will create a table named “customers” with four columns: customer_idfirst_namelast_name, and email.

    The data types used are:

    • VARCHAR: Holds a string of variable length, containing letters, numbers, and special characters. The maximum size is defined in parentheses.
    • INT: Holds integer values, ranging between -2147483648 to 2147483647.

    Attributes used:

    • NOT NULL: Ensures that every row must have a value in the column.
    • PRIMARY KEY: Uniquely identifies each row in the table. Often applied to an ID column.

    Creating a Table Using MySQLi Object-Oriented Procedure

    <?php
    $server = "localhost";
    $user = "root";
    $pass = "";
    $dbname = "shopDB";
    
    // Establishing connection
    $conn = new mysqli($server, $user, $pass, $dbname);
    
    // Checking the connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    // SQL code to create the table
    $sql = "CREATE TABLE customers (
            customer_id INT(3) PRIMARY KEY,
            first_name VARCHAR(40) NOT NULL,
            last_name VARCHAR(40) NOT NULL,
            email VARCHAR(60)
            )";
    
    if ($conn->query($sql) === TRUE) {
        echo "Table customers created successfully";
    } else {
        echo "Error creating table: " . $conn->error;
    }
    
    // Closing connection
    $conn->close();
    ?>

    Creating a Table Using MySQLi Procedural Procedure

    <?php
    $server = "localhost";
    $user = "root";
    $pass = "";
    $dbname = "shopDB";
    
    // Establishing connection
    $conn = mysqli_connect($server, $user, $pass, $dbname);
    
    // Checking connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    
    // SQL code to create the table
    $sql = "CREATE TABLE customers (
            customer_id INT(3) PRIMARY KEY,
            first_name VARCHAR(40) NOT NULL,
            last_name VARCHAR(40) NOT NULL,
            email VARCHAR(60)
            )";
    
    if (mysqli_query($conn, $sql)) {
        echo "Table customers created successfully";
    } else {
        echo "Error creating table: " . mysqli_error($conn);
    }
    
    // Closing connection
    mysqli_close($conn);
    ?>

    Output:

    Table customers created successfully

    Creating a Table Using PDO

    <?php
    $server = "localhost";
    $user = "root";
    $pass = "";
    $dbname = "shopDB";
    
    try {
        // Establishing connection
        $conn = new PDO("mysql:host=$server;dbname=$dbname", $user, $pass);
    
        // Setting PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        // SQL code to create the table
        $sql = "CREATE TABLE customers (
                customer_id INT(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                first_name VARCHAR(40) NOT NULL,
                last_name VARCHAR(40) NOT NULL,
                email VARCHAR(60)
                )";
    
        // Using exec() as no results are returned
        $conn->exec($sql);
        echo "Table customers created successfully";
    }
    catch(PDOException $e) {
        echo $sql . "<br>" . $e->getMessage();
    }
    
    // Closing connection
    $conn = null;
    ?>

    Output:

    Table customers created successfully

    PHP Inserting into MySQL database

    Inserting Data into a MySQL Database Using PHP

    Inserting data into a MySQL database using PHP is a key task in many web applications. This allows developers to dynamically manage and store data, such as user inputs, for a wide variety of tasks like content management, e-commerce, and more.

    In this section, we’ll explore how to insert records into a MySQL database using PHP. The process involves creating a connection to the database, writing an SQL INSERT statement, executing it, and handling any potential errors.

    Inserting Data Using MySQLi (Object-Oriented Approach)

    Let’s assume we are inserting a new record into a MySQL table named people. The objective is to add the namesurname, and age of an individual.

    <?php
    $mysqli = new mysqli("localhost", "admin", "password123", "mydatabase");
    
    // Check connection
    if ($mysqli === false) {
        die("ERROR: Could not connect. " . $mysqli->connect_error);
    }
    
    // Insert data
    $sql = "INSERT INTO people (name, surname, age)
            VALUES ('John', 'Doe', '30')";
    
    if ($mysqli->query($sql) === true) {
        echo "Record inserted successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . $mysqli->error;
    }
    
    // Close connection
    $mysqli->close();
    ?>

    Output:

    Record inserted successfully.
    Inserting Data Using MySQLi (Procedural Approach)

    In this case, we are inserting data into the people table using the MySQLi procedural method. The values to be added are AnnaSmith, and 24 for name, surname, and age, respectively.

    <?php
    $link = mysqli_connect("localhost", "admin", "password123", "mydatabase");
    
    // Check connection
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    // Insert data
    $sql = "INSERT INTO people (name, surname, age)
            VALUES ('Anna', 'Smith', '24')";
    
    if (mysqli_query($link, $sql)) {
        echo "Record added successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    // Close connection
    mysqli_close($link);
    ?>

    Output:

    Record added successfully.
    Inserting Data Using PDO

    In this example, we are inserting data into the people table using the PDO method. The script will handle any errors that might occur during the connection or execution phases.

    <?php
    try {
        $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "admin", "password123");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("ERROR: Could not connect. " . $e->getMessage());
    }
    
    try {
        // Insert data
        $sql = "INSERT INTO people (name, surname, age)
                VALUES ('David', 'Lee', '28')";
        $pdo->exec($sql);
        echo "Record inserted successfully.";
    } catch (PDOException $e) {
        die("ERROR: Could not execute $sql. " . $e->getMessage());
    }
    
    // Close connection
    unset($pdo);
    ?>

    Output:

    Record inserted successfully.
    Inserting Multiple Rows into a Table

    You can also insert multiple rows into a table with a single INSERT query. To do this, add multiple sets of values within the query, where each set is enclosed in parentheses and separated by commas.

    Inserting Multiple Rows Using MySQLi (Object-Oriented Approach)

    <?php
    $mysqli = new mysqli("localhost", "admin", "password123", "mydatabase");
    
    // Check connection
    if ($mysqli === false) {
        die("ERROR: Could not connect. " . $mysqli->connect_error);
    }
    
    // Insert multiple rows
    $sql = "INSERT INTO people (name, surname, age)
            VALUES ('Alice', 'Brown', '22'),
                   ('Tom', 'Harris', '35'),
                   ('Emily', 'Clark', '27'),
                   ('Luke', 'Morris', '31')";
    
    if ($mysqli->query($sql) === true) {
        echo "Records inserted successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . $mysqli->error;
    }
    
    // Close connection
    $mysqli->close();
    ?>

    Output:

    Records inserted successfully.

    Inserting Multiple Rows Using MySQLi (Procedural Approach)

    <?php
    $link = mysqli_connect("localhost", "admin", "password123", "mydatabase");
    
    // Check connection
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    // Insert multiple rows
    $sql = "INSERT INTO people (name, surname, age)
            VALUES ('Michael', 'Smith', '40'),
                   ('Nina', 'Johnson', '29'),
                   ('Chris', 'Evans', '33'),
                   ('Sophia', 'Martinez', '24')";
    
    if (mysqli_query($link, $sql)) {
        echo "Records added successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    // Close connection
    mysqli_close($link);
    ?>

    Output:

    Records added successfully.

    Inserting Multiple Rows Using PDO

    <?php
    try {
        $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "admin", "password123");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("ERROR: Could not connect. " . $e->getMessage());
    }
    
    try {
        // Insert multiple rows
        $sql = "INSERT INTO people (name, surname, age)
                VALUES ('Olivia', 'Taylor', '21'),
                       ('James', 'Wilson', '37'),
                       ('Isabella', 'Garcia', '30'),
                       ('Liam', 'White', '45')";
        $pdo->exec($sql);
        echo "Records inserted successfully.";
    } catch (PDOException $e) {
        die("ERROR: Could not execute $sql. " . $e->getMessage());
    }
    
    // Close connection
    unset($pdo);
    ?>

    Output:

    Records inserted successfully.

    PHP MySQL Delete Query

    The DELETE query is used to remove records from a table in a database. It is often used with a SELECT statement to delete only those rows that meet a certain condition.

    Syntax:

    The basic syntax for a DELETE query is as follows:

    Example Implementation:

    Let us consider a table called Employees with four columns: EmployeeIDFirstNameLastName, and Position. Below are examples of how to delete the record of an employee whose EmployeeID is 101 from the Employees table using different MySQLi and PDO methods.

    1. DELETE Query Using MySQLi Procedural Method:

    <?php
    $link = mysqli_connect("localhost", "root", "", "CompanyDB");
    
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    $sql = "DELETE FROM Employees WHERE EmployeeID = 101";
    if (mysqli_query($link, $sql)) {
        echo "Record deleted successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    mysqli_close($link);
    ?>

    Output:

    This code will delete the record where the EmployeeID is 101 from the Employees table. After execution, a confirmation message will be displayed: “Record deleted successfully.”

    2. SELECT Query Using MySQLi Object-Oriented Method:

    <?php
    $mysqli = new mysqli("localhost", "root", "", "SampleDB");
    
    if ($mysqli === false) {
        die("ERROR: Could not connect. " . $mysqli->connect_error);
    }
    
    $sql = "SELECT * FROM Users";
    if ($res = $mysqli->query($sql)) {
        if ($res->num_rows > 0) {
            echo "<table>";
            echo "<tr>";
            echo "<th>FirstName</th>";
            echo "<th>LastName</th>";
            echo "<th>Age</th>";
            echo "</tr>";
            while ($row = $res->fetch_array()) {
                echo "<tr>";
                echo "<td>".$row['FirstName']."</td>";
                echo "<td>".$row['LastName']."</td>";
                echo "<td>".$row['Age']."</td>";
                echo "</tr>";
            }
            echo "</table>";
            $res->free();
        } else {
            echo "No records found.";
        }
    } else {
        echo "ERROR: Could not execute $sql. " . $mysqli->error;
    }
    $mysqli->close();
    ?>

    Output:

    Similar to the previous example, this code will output the data in an HTML table format. If there are no matching records, it will show “No records found.”

    PHP MySQL WHERE Clause

    The WHERE clause is used to filter records based on a specific condition provided by the user. Essentially, it helps restrict the number of rows returned or affected by a SELECTUPDATE, or DELETE query.

    Syntax:

    The basic syntax for using the WHERE clause is as follows:

    SELECT Column1, Column2, ...
    FROM Table_Name
    WHERE Condition;

    Example of WHERE Clause:

    Let’s consider a table called Students with three columns: FirstNameLastName, and Age.

    To retrieve all the rows where the FirstName is “John”, we will use the following code examples:

    1. WHERE Clause Using MySQLi Procedural Method:

    <?php
    $link = mysqli_connect("localhost", "root", "", "SchoolDB");
    
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    $sql = "SELECT * FROM Students WHERE FirstName='John'";
    if ($res = mysqli_query($link, $sql)) {
        if (mysqli_num_rows($res) > 0) {
            echo "<table>";
            echo "<tr>";
            echo "<th>FirstName</th>";
            echo "<th>LastName</th>";
            echo "<th>Age</th>";
            echo "</tr>";
            while ($row = mysqli_fetch_array($res)) {
                echo "<tr>";
                echo "<td>" . $row['FirstName'] . "</td>";
                echo "<td>" . $row['LastName'] . "</td>";
                echo "<td>" . $row['Age'] . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            mysqli_free_result($res);
        } else {
            echo "No matching records found.";
        }
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    mysqli_close($link);
    ?>

    Output:

    This code fetches all records from the Students table where the FirstName is “John.” The matching rows are displayed in a table format.

    2. WHERE Clause Using MySQLi Object-Oriented Method:

    <?php
    $mysqli = new mysqli("localhost", "root", "", "SchoolDB");
    
    if ($mysqli === false) {
        die("ERROR: Could not connect. " . $mysqli->connect_error);
    }
    
    $sql = "SELECT * FROM Students WHERE FirstName='John'";
    if ($res = $mysqli->query($sql)) {
        if ($res->num_rows > 0) {
            echo "<table>";
            echo "<tr>";
            echo "<th>FirstName</th>";
            echo "<th>LastName</th>";
            echo "<th>Age</th>";
            echo "</tr>";
            while ($row = $res->fetch_array()) {
                echo "<tr>";
                echo "<td>" . $row['FirstName'] . "</td>";
                echo "<td>" . $row['LastName'] . "</td>";
                echo "<td>" . $row['Age'] . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            $res->free();
        } else {
            echo "No matching records found.";
        }
    } else {
        echo "ERROR: Could not execute $sql. " . $mysqli->error;
    }
    
    $mysqli->close();
    ?>

    Output:

    In this example, the object-oriented method retrieves all the rows from the Students table where the FirstName is “John” and displays them in a table format.

    3. WHERE Clause Using PDO Method:

    <?php
    try {
        $pdo = new PDO("mysql:host=localhost;dbname=SchoolDB", "root", "");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("ERROR: Could not connect. " . $e->getMessage());
    }
    
    try {
        $sql = "SELECT * FROM Students WHERE FirstName='John'";
        $res = $pdo->query($sql);
        if ($res->rowCount() > 0) {
            echo "<table>";
            echo "<tr>";
            echo "<th>FirstName</th>";
            echo "<th>LastName</th>";
            echo "<th>Age</th>";
            echo "</tr>";
            while ($row = $res->fetch()) {
                echo "<tr>";
                echo "<td>" . $row['FirstName'] . "</td>";
                echo "<td>" . $row['LastName'] . "</td>";
                echo "<td>" . $row['Age'] . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            unset($res);
        } else {
            echo "No matching records found.";
        }
    } catch (PDOException $e) {
        die("ERROR: Could not execute $sql. " . $e->getMessage());
    }
    
    unset($pdo);
    ?>

    Output:

    The PDO example runs a query to select all rows from the Students table where the FirstName is “John.” The results are displayed in a table format.

    PHP MySQL UPDATE Query

    The MySQL UPDATE query is utilized to modify existing records in a table within a MySQL database.

    It allows updating one or more fields simultaneously and can be used in conjunction with the WHERE clause to specify conditions for the update.

    Syntax:

    The basic syntax for the UPDATE query is as follows:

    UPDATE table_name
    SET column1 = value1, column2 = value2, ...
    WHERE condition;

    Example of WHERE Update Query:

    Let’s consider a table called Employees with columns IDFirstNameLastName, and Age.

    To update the Age of an employee with ID 105 in the Employees table, we can use the following code:

    1. Update Query Using MySQLi Procedural Method:

    <?php
    $link = mysqli_connect("localhost", "root", "", "CompanyDB");
    
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    $sql = "UPDATE Employees SET Age='32' WHERE ID=105";
    if (mysqli_query($link, $sql)) {
        echo "Record was updated successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    mysqli_close($link);
    ?>

    Output:

    This code updates the Age of the employee with ID 105 to 32. If successful, a message is displayed indicating the update.

    2. Update Query Using MySQLi Object-Oriented Method:

    <?php
    $mysqli = new mysqli("localhost", "root", "", "CompanyDB");
    
    if ($mysqli === false) {
        die("ERROR: Could not connect. " . $mysqli->connect_error);
    }
    
    $sql = "UPDATE Employees SET Age='32' WHERE ID=105";
    if ($mysqli->query($sql) === true) {
        echo "Record was updated successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . $mysqli->error;
    }
    
    $mysqli->close();
    ?>

    Output:

    In this example, the Age of the employee with ID 105 is updated to 32. A success message is shown if the query is executed without errors.

    3. Update Query Using PDO Method:

    <?php
    try {
        $pdo = new PDO("mysql:host=localhost;dbname=CompanyDB", "root", "");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("ERROR: Could not connect. " . $e->getMessage());
    }
    
    try {
        $sql = "UPDATE Employees SET Age='32' WHERE ID=105";
        $pdo->exec($sql);
        echo "Record was updated successfully.";
    } catch (PDOException $e) {
        die("ERROR: Could not execute $sql. " . $e->getMessage());
    }
    
    unset($pdo);
    ?>

    Output:

    This PDO method updates the Age of the employee with ID 105 to 32, and a confirmation message is displayed upon successful execution.

    PHP MySQL LIMIT Clause

    In MySQL, the LIMIT clause is used in conjunction with the SELECT statement to control the number of rows returned in the result set. The LIMIT clause accepts either one or two arguments: offset and count. Both values must be non-negative integers.

    • Offset: This specifies the position of the first row to return.
    • Count: This defines the maximum number of rows to return.

    When two parameters are used, the first one represents the offset and the second indicates the count. If only one parameter is provided, it represents the number of rows to return from the start of the result set.

    Syntax:

    SELECT column1, column2, ...
    FROM table_name
    LIMIT offset, count;

    Example:

    Let’s consider the following table named Employees, which contains three columns: FirstNameLastName, and Age.

    To retrieve the first two rows from the Employees table, use the following query:

    SELECT * FROM Employees LIMIT 2;

    To fetch rows starting from the second row and retrieve two rows (rows 2 and 3 inclusive), use the following query:

    SELECT * FROM Employees LIMIT 1, 2;

    Below is the PHP implementation of the query to display the first two rows from the Employees table using the LIMIT clause in both procedural and object-oriented methods:

    1. Limit Clause Using MySQLi Procedural Method:

    <?php
    $link = mysqli_connect("localhost", "root", "", "CompanyDB");
    
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    $sql = "SELECT * FROM Employees LIMIT 2";
    if ($res = mysqli_query($link, $sql)) {
        if (mysqli_num_rows($res) > 0) {
            echo "<table>";
            echo "<tr>";
            echo "<th>FirstName</th>";
            echo "<th>LastName</th>";
            echo "<th>Age</th>";
            echo "</tr>";
            while ($row = mysqli_fetch_array($res)) {
                echo "<tr>";
                echo "<td>" . $row['FirstName'] . "</td>";
                echo "<td>" . $row['LastName'] . "</td>";
                echo "<td>" . $row['Age'] . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            mysqli_free_result($res);
        } else {
            echo "No matching records were found.";
        }
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    mysqli_close($link);
    ?>

    Output:

    This code retrieves and displays the first two rows from the Employees table, showing FirstNameLastName, and Age fields.

  • PHP OOPs

    PHP Classes

    Like C++ and Java, PHP supports object-oriented programming (OOP). Classes in PHP are the blueprints for creating objects. One key difference between functions and classes is that a class can contain both data (properties/variables) and functions (methods) that define the behavior of an object.

    A class is essentially a programmer-defined data type that includes local methods and properties. It serves as a collection of objects, each having specific attributes and behavior.

    Syntax:

    To define a class, start with the keyword class followed by the name of the class.

    <?php
        class ExampleClass {
    
        }
    ?>

    Note: Classes are enclosed using curly braces {}, similar to how functions are defined.

    Below are examples illustrating the use of classes in PHP’s object-oriented programming:

    Example 1: Constructor in PHP Class

    A constructor is a special method that gets called automatically when an object of the class is created. In PHP, constructors are defined using __construct().

    <?php
    class MyClass
    {
        // Constructor
        public function __construct(){
            echo 'The class "' . __CLASS__ . '" has been instantiated!<br>';
        }
    
    }
    
    // Create a new object of the class
    $obj = new MyClass;
    ?>

    Output:

    The class "MyClass" has been instantiated!

    Example 2: Destructor in PHP Class

    destructor is another special method that is invoked automatically when an object is no longer in use or the script execution ends. In PHP, destructors are defined using __destruct().

    <?php
    class MyClass
    {
        // Destructor
        public function __destruct(){
            echo 'The class "' . __CLASS__ . '" has been destroyed!';
        }
    
    }
    
    // Create a new object of the class
    $obj = new MyClass;
    ?>

    Output:

    The class "MyClass" has been destroyed!

    PHP Variables

    Constructors are special methods used for initial settings when new instances of a class are created. They play a key role in PHP’s object-oriented programming model introduced in PHP5. Constructors act as the blueprint for creating objects, initializing their properties, and defining their behavior. Once the object is initialized, the constructor is automatically called. In contrast, destructors handle object cleanup and are automatically invoked at the end of the script execution.

    In this article, we’ll explore constructors and destructors, two important concepts in PHP’s object-oriented programming.

    Both constructors and destructors are special member functions, with the primary difference being that destructors are preceded by a ~ (tilde) symbol.

    Constructor Syntax:

    __construct():
    
    function __construct()
    {
       // Initialize the object and its properties
    }

    Destructor Syntax:

    __destruct():
    
    function __destruct()
    {
       // Cleanup code
    }

    Note: The constructor is defined in the public section of the class. It is responsible for setting the initial values of the class properties.

    Types of Constructors:

    1. Default Constructor: It has no parameters but can accept dynamic values during object creation.
    2. Parameterized Constructor: This constructor accepts parameters and assigns them to class properties.
    3. Copy Constructor: This accepts another object as an argument and initializes the new object from it.

    Inheritance and Constructors:

    Constructors are inherited by child classes. If a child class defines its own constructor, it will be called instead of the parent’s constructor.

    Pre-defined vs. User-defined Constructor:

    When a class contains both the pre-defined __construct() and a user-defined constructor, __construct() will act as the constructor while the user-defined one behaves like a regular method.

    Example 1: Pre-defined Constructor in PHP Class

    <?php
    class Plant
    {
        function Plant()
        {
            echo "This is a user-defined constructor for the Plant class.";
        }
    
        function __construct()
        {
            echo "This is the pre-defined constructor for the Plant class.";
        }
    }
    
    $obj = new Plant();
    ?>

    Output:

    This is the pre-defined constructor for the Plant class.

    Example 2: Parameterized Constructor

    In this example, the constructor takes parameters and sets the object’s properties accordingly.

    <?php
    
    class Vehicle
    {
        public $make;
        public $model;
    
        function __construct($make, $model)
        {
            $this->make = $make;
            $this->model = $model;
        }
    
        function show_details()
        {
            echo "Make: " . $this->make . ", Model: " . $this->model . "\n";
        }
    }
    
    $vehicle1 = new Vehicle("Toyota", "Corolla");
    $vehicle1->show_details();
    
    $vehicle2 = new Vehicle("Honda", "Civic");
    $vehicle2->show_details();
    
    ?>

    Output:

    Make: Toyota, Model: Corolla
    Make: Honda, Model: Civic
    Inheritance and Constructors

    If a child class has its own constructor, both the child’s and parent’s constructors will be called in order.

    Example 3: Constructor in Parent and Child Classes

    <?php
    class Animal
    {
        function __construct()
        {
            print "Animal class constructor.\n";
        }
    }
    
    class Dog extends Animal
    {
        function __construct()
        {
            parent::__construct(); // Call the parent constructor
            print "Dog class constructor.\n";
        }
    }
    
    $obj1 = new Animal();
    $obj2 = new Dog();
    ?>

    Output:

    Animal class constructor.
    Animal class constructor.
    Dog class constructor.
    Destructor in PHP

    Destructors are used to clean up resources when an object is no longer needed. They are automatically called when the object goes out of scope or the script ends.

    Example 4: Destructor

    <?php
    class Item
    {
        function __construct()
        {
            echo "In constructor, ";
            $this->name = "Item Object";
        }
    
        function __destruct()
        {
            echo "destroying " . $this->name . "\n";
        }
    }
    
    $obj = new Item();
    ?>

    Output:

    In constructor, destroying Item Object

    Note: In cases of inheritance, if both the parent and child class have destructors, the destructor of the child class is executed first, followed by the parent’s destructor.

    Advantages of Constructors:

    1. Automatic Initialization: Constructors allow automatic initialization of object properties when creating an instance.
    2. Flexibility with Parameters: They can take multiple parameters, enabling dynamic initialization.
    3. Reusability: Objects can be reused without having to reinitialize their properties each time.
    4. Session Management: Constructors can initiate sessions, removing the need to start them manually in every function.

    Destructor:

    Destructors clean up resources and free memory before an object is destroyed. They are especially useful for closing file handles or database connections.

    Constructor vs. Destructor Comparison
    ConstructorsDestructors
    Accepts one or more parameters.Takes no parameters.
    Named as __construct().Named as __destruct().
    Called automatically when an object is created.Called automatically when an object is destroyed.
    Used for initializing an object’s properties.Used for cleaning up resources.
    Can be overloaded.Cannot be overloaded.
    Allocates memory.Deallocates memory.

    Example 5: Destructor in Inherited Class

    <?php
    class ParentClass
    {
        function __destruct()
        {
            echo "Destructor of Parent Class\n";
        }
    }
    
    class ChildClass extends ParentClass
    {
        function __destruct()
        {
            echo "Destructor of Child Class\n";
            parent::__destruct(); // Call parent destructor
        }
    }
    
    $obj = new ChildClass();
    ?>

    Output:

    Destructor of Child Class
    Destructor of Parent Class

    PHP Access Specifiers

    In PHP, each property of a class must have one of three visibility levels, known as public, private, and protected.

    • Public: Public properties can be accessed by any code, whether that code is inside or outside the class. If a property is declared public, its value can be read or changed from anywhere in your script.
    • Private: Private properties of a class can be accessed only by code inside the class. If a property is declared private, only methods and objects inside the same class can access its contents.
    • Protected: Protected class properties are like private properties in that they can’t be accessed by code outside the class. However, classes that inherit from the parent class can access protected properties.

    Generally, it’s recommended to avoid creating public properties wherever possible. Instead, it’s safer to create private properties and methods to control how external code interacts with class properties.

    Note: Attempting to access a private or protected property outside the class results in a fatal error.

    PHP Access Specifier Feasibility:
    Access SpecifierAccess from ClassAccess from SubclassAccess from Outside
    PrivateYesNoNo
    ProtectedYesYesNo
    PublicYesYesYes

    Example 1: Public Access Specifier

    <?php
    class Calculator
    {
        public $x = 100;  // public attributes
        public $y = 50;
    
        function add()
        {
            echo $this->x + $this->y;
            echo " ";
        }
    }
    
    class AdvancedCalculator extends Calculator
    {
        function subtract()
        {
            echo $this->x - $this->y;
        }
    }
    
    $obj = new AdvancedCalculator();
    
    // Accessing public properties and methods
    $obj->add();
    $obj->subtract();
    ?>

    Output:

    150 50

    Example 2: Private Access Specifier

    <?php
    class Calculator
    {
        private $a = 75;  // private attributes
        private $b = 5;
    
        private function divide()  // private member function
        {
            echo $this->a / $this->b;
            echo " ";
        }
    }
    
    class AdvancedCalculator extends Calculator
    {
        function multiply()
        {
            echo $this->a * $this->b;  // Trying to access private properties
        }
    }
    
    $obj = new AdvancedCalculator();
    
    // Attempting to access private method and properties
    $obj->divide();  // This will cause a fatal error
    $obj->multiply();  // This will cause a fatal error
    ?>

    Output:

    PHP Fatal error:  Uncaught Error: Call to private method Calculator::divide() from context

    Example 3: Protected Access Specifier

    <?php
    class Calculator
    {
        protected $x = 1000;  // protected attributes
        protected $y = 100;
    
        function divide()
        {
            echo $this->x / $this->y;
            echo " ";
        }
    }
    
    class AdvancedCalculator extends Calculator
    {
        function subtract()
        {
            echo $this->x - $this->y;
        }
    }
    
    class OutsideClass
    {
        function multiply()
        {
            echo $this->x * $this->y;  // Trying to access protected properties
        }
    }
    
    $obj = new AdvancedCalculator();
    
    // Accessing protected method from within the subclass
    $obj->divide();
    $obj->subtract();
    
    // Trying to access protected properties from an external class
    $obj2 = new OutsideClass();
    $obj2->multiply();  // This will cause a fatal error
    ?>

    Output:

    10
    900
    Fatal error:  Uncaught Error: Call to undefined method OutsideClass::multiply()

    Multiple Inheritance in PHP

    Multiple Inheritance refers to a feature in object-oriented programming languages where a child class can inherit properties and methods from multiple parent classes. PHP, by default, does not support multiple inheritance, but this can be achieved using Traits or Interfaces.

    Using Traits for Multiple Inheritance

    Traits allow you to reuse sets of methods across multiple classes. This makes it possible to mimic multiple inheritance in PHP.

    Example 1: Using a Class and a Trait

    <?php
    // Class ExampleOne
    class ExampleOne {
        public function greet() {
            echo "Hi";
        }
    }
    
    // Trait ExampleTrait
    trait ExampleTrait {
        public function greetTrait() {
            echo " World";
        }
    }
    
    class Combined extends ExampleOne {
        use ExampleTrait;
        public function finalGreeting() {
            echo "\nWelcome to the PHP World!";
        }
    }
    
    $test = new Combined();
    $test->greet();
    $test->greetTrait();
    $test->finalGreeting();
    ?>

    Output:

    Hi World
    Welcome to the PHP World!

    In this example, we use a class (ExampleOne) and a trait (ExampleTrait) in combination. The class Combined inherits the method from both the parent class and the trait.

    Example 2: Using Multiple Traits

    You can include multiple traits in a class using the use keyword.

    <?php
    // Trait ExampleOne
    trait ExampleOne {
        public function greet() {
            echo "Hello";
        }
    }
    
    // Trait ExampleTwo
    trait ExampleTwo {
        public function greetTwo() {
            echo " World";
        }
    }
    
    class MultipleTraits {
        use ExampleOne, ExampleTwo;
        public function finalMessage() {
            echo "\nPHP Multiple Traits Example";
        }
    }
    
    $test = new MultipleTraits();
    $test->greet();
    $test->greetTwo();
    $test->finalMessage();
    ?>

    Output:

    Hello World
    PHP Multiple Traits Example

    In this case, two traits (ExampleOne and ExampleTwo) are used together inside the MultipleTraits class, allowing us to call methods from both traits.

    Using Interfaces for Multiple Inheritance

    PHP interfaces allow you to define methods that a class must implement, which enables multiple inheritance by implementing multiple interfaces.

    Example 3: Using a Class and an Interface

    <?php
    
    class FirstClass {
        public function insideFirst() {
            echo "This is Class A";
        }
    }
    
    interface SecondInterface {
        public function insideSecond();
    }
    
    class InheritanceExample extends FirstClass implements SecondInterface {
    
        public function insideSecond() {
            echo "\nThis is Interface B";
        }
    
        public function inChildClass() {
            echo "\nThis is the child class";
        }
    }
    
    $example = new InheritanceExample();
    $example->insideFirst();
    $example->insideSecond();
    $example->inChildClass();
    ?>

    Output:

    This is Class A
    This is Interface B
    This is the child class

    PHP Constants

    Constants in PHP are identifiers or names assigned to fixed values that remain unchanged throughout the program execution. Once a constant is set, it cannot be redefined or removed.

    By convention, constant names are written in uppercase. By default, constants are case-sensitive and must start with a letter or an underscore, followed by letters, numbers, or underscores. Special characters, except for the underscore, are not allowed.

    1. Creating a Constant Using define() Function: The define() function is commonly used to create constants in PHP.

    Syntax:

    define('CONSTANT_NAME', value, case_insensitive);
    • name: The name of the constant.
    • value: The value assigned to the constant.
    • case_insensitive: Defines whether the constant should be case-insensitive. The default value is false, meaning the constant is case-sensitive.

    Example: Creating Constants Using define() Function

    <?php
    
    // Creates a case-sensitive constant
    define("GREETING", "Hello World");
    echo GREETING . "\n";
    
    // Creates a case-insensitive constant
    define("WELCOME", "Hello Universe", true);
    echo welcome;
    
    ?>

    Output:

    Hello World
    Hello Universe

    2. Creating a Constant Using const Keyword: The const keyword is another way to define constants, usually used within classes or functions. Unlike define(), constants defined using const are always case-sensitive.

    Syntax:

    const CONSTANT_NAME = value;

    Example: Creating Constants Using const Keyword

    <?php
    const WEBSITE = 'MyWebsite';
    echo WEBSITE;
    ?>

    Output:

    MyWebsite

    3. Constants are Global: Constant global, meaning they can be accessed from any part of the script, including functions.

    Example: Global Scope of Constants

    <?php
    
    define("MESSAGE", "PHP is Fun!");
    
    function displayMessage() {
        echo MESSAGE;
    }
    
    echo MESSAGE . "\n";
    displayMessage();
    
    ?>

    Output:

    PHP is Fun!
    PHP is Fun!

    In the example above, the constant MESSAGE can be accessed both inside and outside the function displayMessage() because constants have a global scope.

    Difference Between Constants and Variables

    Here are some key differences between constants and variables:

    FeatureConstantsVariables
    SyntaxDoes not use $Starts with $
    ValueImmutable (cannot be changed)Mutable (can be changed)
    Case SensitivityCase-sensitive by defaultCase-sensitive
    Global ScopeAlways globalScope depends on where it’s defined (local or global)
    Declaration Methoddefine() or constDeclared using $ symbol

    This updated content keeps the same meaning and structure but has revised wording and updated examples. The examples now reflect the typical usage of constants in PHP, and their respective outputs have been adjusted accordingly.

    PHP Constants

    Abstract Classes in PHP are classes where at least one method is declared as abstract. In PHP, abstract classes are defined using the abstract keyword. The main purpose of abstract classes is that any class extending the abstract class must implement the abstract methods defined in the parent class. An abstract class can also contain non-abstract methods.

    Syntax Example of an Abstract Class in PHP

    <?php
    
    // Abstract class example in PHP
    abstract class BaseClass
    {
        // Abstract method (must be implemented by child classes)
        abstract function showData();
    
        // Non-abstract method
        function display()
        {
            echo "Base class method";
        }
    }
    ?>
    Key Points About Abstract Classes in PHP:

    1. Cannot Instantiate Abstract Classes: Like in Java, you cannot create an instance of an abstract class in PHP.

    Example:

    <?php
    
    // Abstract class
    abstract class ParentClass {
        // Abstract method
        abstract function showData();
    }
    
    // Derived class extending the abstract class
    class ChildClass extends ParentClass {
        function showData() {
            echo "Child class method";
        }
    }
    
    // Trying to create an instance of abstract class will cause an error
    // $obj = new ParentClass();  // This will result in an error
    
    $obj1 = new ChildClass;
    $obj1->showData();
    
    ?>

    Output:

    Child class method

    2. Abstract Classes Can Have Constructors: Similar to C++ or Java, abstract classes in PHP can contain constructors as well.

    Example:

    <?php
    
    // Abstract class
    abstract class ParentClass {
        function __construct() {
            echo "Abstract class constructor";
        }
    
        // Abstract method
        abstract function showData();
    }
    
    // Child class that extends the abstract class
    class ChildClass extends ParentClass {
        function __construct() {
            echo "\nChild class constructor";
        }
        function showData() {
            echo "\nChild class showData method";
        }
    }
    
    $obj = new ChildClass;
    $obj->showData();
    
    ?>

    Output:

    Child class constructor
    Child class showData method

    3. Abstract Classes Must Contain At Least One Abstract Method: In PHP, unlike Java, you cannot create an abstract class without having at least one abstract method. If you try to define an abstract method with a body, PHP will generate a runtime error.

    Example:

    <?php
    
    // Invalid abstract class in PHP
    abstract class ParentClass {
        // This will cause an error because an abstract method cannot have a body
        abstract function showData() {
            echo "This will cause an error";
        }
    }
    
    ?>

    Runtime Error:

    PHP Fatal error:  Abstract function ParentClass::showData() cannot contain body

    PHP Interface

    Interface in PHP allows developers to define the structure of the methods that a class must implement without specifying the exact implementation. It serves as a way to enforce a contract for classes and provides a higher level of abstraction. Interfaces are similar to abstract classes but do not include any method bodies or data members. They ensure that any class implementing the interface must include the methods described.

    Defining an Interface

    To define an interface, we use the interface keyword, similar to how we define a class, but without providing method implementations.

    Syntax Example:

    <?php
    
    interface ExampleInterface {
       public function methodOne();
       public function methodTwo();
    }
    
    ?>
    Key Features of Interfaces:

    1. Abstract Methods: All methods in an interface are abstract, meaning they contain no method bodies.
    2. Visibility Scope: Methods defined in interfaces must be public.
    3. Multiple Implementations: A class can implement multiple interfaces, unlike inheritance where a class can only extend one parent class.

    Implementing an Interface

    To implement an interface in a class, use the implements keyword. The class that implements the interface must provide implementations for all methods defined in the interface.

    Example:

    <?php
    
    interface SimpleInterface {
       public function methodOne();
       public function methodTwo();
    }
    
    class MyClass implements SimpleInterface {
       public function methodOne() {
         echo "Method One executed.\n";
       }
       public function methodTwo() {
         echo "Method Two executed.\n";
       }
    }
    
    $obj = new MyClass;
    $obj->methodOne();
    $obj->methodTwo();
    
    ?>

    Output:

    Method One executed.
    Method Two executed.
    Concrete Class:

    A class that implements an interface is called a Concrete Class. It must provide implementations for all the methods defined by the interface. If two interfaces have the same method name, ambiguity may occur and cannot be implemented in the same class. An interface can extend another interface using the extends keyword, just like class inheritance.

    Interface Inheritance Example:

    <?php
    
    interface FirstInterface {
        public function functionOne();
    }
    
    interface SecondInterface extends FirstInterface {
        public function functionTwo();
    }
    
    class MyClass implements SecondInterface {
        public function functionOne() {
            echo "Function One from First Interface\n";
        }
        public function functionTwo() {
            echo "Function Two from Second Interface\n";
        }
    }
    
    $obj = new MyClass;
    $obj->functionOne();
    $obj->functionTwo();
    
    ?>

    Output:

    Function One from First Interface
    Function Two from Second Interface

    Practical Example of Interface Implementation:

    <?php
    
    interface BasicInterface {
        public function showMethod1();
        public function showMethod2();
    }
    
    class DemoClass implements BasicInterface {
        public function showMethod1() {
            echo "showMethod1 called.\n";
        }
        public function showMethod2() {
            echo "showMethod2 called.\n";
        }
    }
    
    $instance = new DemoClass;
    $instance->showMethod1();
    $instance->showMethod2();
    
    ?>

    Output:

    showMethod1 called.
    showMethod2 called.
    Benefits of Using PHP Interfaces
    • Unrelated Classes Can Share Methods:
      Interfaces allow unrelated classes to implement the same set of methods, regardless of their inheritance hierarchy.
    • Supports Multiple Inheritance:
      A class can implement multiple interfaces, enabling a form of multiple inheritance, unlike classes that can only extend a single parent class.
    • Focus on Interface, Not Implementation:
      Interfaces allow the developer to focus on the interaction with an object rather than worrying about the actual implementation, maintaining consistency for the user of the interface.

    Static Function in PHP

    In certain scenarios, it is useful to access class methods and properties directly without the need to create an instance of the class. This can be achieved using the static keyword. A method declared as static can be accessed without instantiating an object. Static methods are tied to the class itself, not a particular object instance. However, they can only interact with static properties and methods of the class.

    To declare a static method, use the static keyword as shown below:

    public static function exampleMethod()
    {
        // Method logic here
    }

    Static methods can be invoked outside the class using the scope resolution operator :: as follows:

    MyClass::exampleMethod();

    Example: Using a Static Method as a Counter

    <?php
    /* Demonstrating the use of a static function as a counter */
    
    class Counter {
    
        static $count;
    
        public static function incrementCount() {
            return self::$count++;
        }
    }
    
    Counter::$count = 1;
    
    for($i = 0; $i < 5; ++$i) {
        echo 'The next count is: ' . Counter::incrementCount() . "\n";
    }
    
    ?>

    Output:

    The next count is: 1
    The next count is: 2
    The next count is: 3
    The next count is: 4
    The next count is: 5
    When to Use Static Methods?

    The static keyword is used in cases where variables and methods are common to all instances of a class. Any logic that needs to be shared across multiple instances should be placed in static methods. Static methods in PHP are often found in utility classes that contain shared functionality, such as those in frameworks like Laravel or CakePHP.

    Below is an example demonstrating the use of static methods.

    Example: Static Method in PHP

    <?php
    /* Demonstrating static methods in PHP */
    
    class NonStaticClass {
    
        public function display($message = "Hello World") {
            $this->message = $message;
            return $this->message;
        }
    }
    
    class StaticClass {
        public static function display($message) {
            $message = "This is a static method";
            return $message;
        }
    }
    
    // Create an instance of NonStaticClass
    $object = new NonStaticClass();
    
    echo $object->display('This is a non-static method');
    echo "\n";
    echo StaticClass::display('This is non-static');
    
    ?>

    Output:

    This is a non-static method
    This is a static method

    PHP Namespace

    Similar to C++, PHP namespaces provide a way to organize code and prevent name conflicts when reusing the same class, function, or constant names. Namespaces offer an abstract structure that lets you reuse names without encountering fatal errors due to naming conflicts.

    Key points about namespaces in PHP:
    • They serve as containers for your PHP code, allowing code reuse and preventing conflicts.
    • Namespaces can include classes (including abstracts and traits), interfaces, functions, and constants.
    • The namespace keyword is used to define a namespace.
    • It must be declared at the top of a file before any other code (except the declare keyword).
    • A namespace can hold valid PHP code, just like a regular PHP script.

    Example: Declaring a Namespace

    <?php
    namespace MyNamespace {
    
        // This is regular PHP code
        function hello()
        {
            echo 'Hello, I am running from a namespace!';
        }
    }
    ?>
    Global Namespace Declaration

    If the namespace is to be declared globally (i.e., without a specific name), it is done like this:

    <?php
    namespace {
        // Code in the global space
    }
    ?>
    Declaring Multiple Namespaces in a Single File

    You can declare multiple namespaces within a single PHP file:

    <?php
    namespace MyNamespace1 {
        // Code for the first namespace
    }
    
    namespace MyNamespace2 {
        // Code for the second namespace
    }
    
    namespace {
        // Code in the global namespace
    }
    ?>

    Namespaces are used to avoid conflicts and add flexibility and structure to your codebase. Just like directories in file systems, namespaces can be hierarchical. In PHP, the backslash (\) serves as the namespace separator.

    Example: Using a Namespace

    <?php
    namespace MyNamespace;
    
    function hello()
    {
        echo 'Hello, I am running from a namespace!';
    }
    
    // This calls the function within the MyNamespace namespace
    hello();
    
    // Explicitly resolves to MyNamespace\hello
    namespace\hello();
    ?>

    Output:

    Hello, I am running from a namespace!
    Hello, I am running from a namespace!
    Aliasing in Namespaces

    Namespaces allow the use of aliases for ease of reference. The use keyword imports namespaces, and you can use the as keyword to create a custom alias.

    Example: Aliasing in Namespaces

    <?php
    namespace MyNamespace;
    
    require 'project/database/connection.php';
    
    // Creating an alias for Project\Database\Connection
    use Project\Database\Connection as Conn;
    
    $connection = new Conn();
    
    // Importing the Project\Database namespace with alias
    use Project\Database as DB;
    
    $connection = new DB\Connection();
    ?>
    Dynamic Namespaces

    Although you can dynamically include files in PHP, dynamic namespace importing is not supported.

    Example: Dynamic Namespace Usage

    <?php
    namespace OtherProject;
    
    $title = 'geeks';
    
    // This is valid PHP code
    require 'project/blog/title/' . $title . '.php';
    
    // This will cause an error (invalid dynamic namespace)
    use Project\Blog\title\$title;
    ?>

    Runtime Error:

    PHP Fatal error: Invalid namespace usage
  • PHP Advance

    PHP Superglobals

    Introduction to Superglobal Variables in PHP

    Superglobals are built-in array variables in PHP that allow developers to access important data about requests or scripts. These superglobals can be accessed globally from any part of your code, such as functions or classes, without requiring special declarations like global variables. They are especially useful for handling data transfer between pages, dealing with requests, and managing server information.

    Here’s a list of the available superglobal variables in PHP:

    • $GLOBALS
    • $_SERVER
    • $_REQUEST
    • $_GET
    • $_POST
    • $_SESSION
    • $_COOKIE
    • $_FILES
    • $_ENV

    Let’s take a closer look at some of these superglobals:

    1. $GLOBALS Superglobal :$GLOBALS is used to access global variables from any part of the PHP script. PHP stores all global variables in the $GLOBALS array, where the key is the variable name, and the value can be accessed.

    Example:

    <?php
    $a = 10;
    $b = 20;
    
    function addition() {
        $GLOBALS['result'] = $GLOBALS['a'] + $GLOBALS['b'];
    }
    
    addition();
    echo $result;
    ?>

    Output:

    30

    2.$_SERVER Superglobal:$_SERVER holds information about headers, paths, and script locations. It provides valuable details about the server and the current script.

    Example:

    <?php
    echo $_SERVER['PHP_SELF'];  // Current script
    echo "<br>";
    echo $_SERVER['SERVER_ADDR'];  // Server IP
    echo "<br>";
    echo $_SERVER['HTTP_USER_AGENT'];  // Browser details
    echo "<br>";
    echo $_SERVER['REQUEST_METHOD'];  // HTTP method used
    ?>

    Output:

    /path/to/script.php
    127.0.0.1
    Mozilla/5.0 (your browser details)
    GET

    3.$_REQUEST Superglobal$_REQUEST is a superglobal that collects data from forms, whether submitted using GET or POST. Although it’s versatile, developers often prefer using $_POST or $_GET for specific requests.

    Example:

    <!DOCTYPE html>
    <html>
    <body>
    
    <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
      Name: <input type="text" name="username">
      <input type="submit" value="Submit">
    </form>
    
    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $name = $_REQUEST['username'];
        if (empty($name)) {
            echo "Name is empty";
        } else {
            echo "Hello, " . $name;
        }
    }
    ?>
    </body>
    </html>

    Output:

    Hello, John

    4.$_POST Superglobal:$_POST is used to collect data from forms when they are submitted using the POST method. The data is not visible in the URL, ensuring privacy and security.

    Example:

    <!DOCTYPE html>
    <html>
    <body>
    
    <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
      Enter your name: <input name="username" type="text"><br>
      Enter your age: <input name="age" type="text"><br>
      <input type="submit" value="Submit">
    </form>
    
    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $name = $_POST['username'];
        $age = $_POST['age'];
        echo "$name is $age years old.";
    }
    ?>
    </body>
    </html>

    Output:

    Jane is 25 years old.

    5. $_GET Superglobal$_GET is used to collect data from forms submitted using the GET method. Data sent this way is visible in the URL, making it less secure but useful in certain scenarios.

    Example:

    <!DOCTYPE html>
    <html>
    <head>
    <title>$_GET Example</title>
    </head>
    <body>
    
    <?php
    // Collecting values sent in the URL
    $name = $_GET['username'];
    $city = $_GET['city'];
    
    echo "<h2>Welcome, $name from $city!</h2>";
    ?>
    
    </body>
    </html>

    Assuming URL

    http://localhost/page.php?username=Alice&city=NewYork

    Output:

    Welcome, Alice from NewYork!

    HTTP GET and POST Methods in PHP

    Understanding HTTP GET and POST Methods in PHP

    The Hypertext Transfer Protocol (HTTP) enables communication between clients (browsers) and servers. It follows a request-response model where the client submits an HTTP request, and the server responds with the necessary content and status information. In PHP, we frequently work with two primary HTTP request methods: GET and POST.

    1. GET Method: Used to request data from a specified resource.
    2. POST Method: Used to send data to the server for processing.

    1. GET Method in PHP: The GET method sends data through the URL as query parameters. These parameters are key-value pairs separated by &. The GET method is suitable for retrieving data and can be used to pass simple text information.

    Example URL:

    http://www.example.com/process.php?name=Alex&age=30

    Here, name=Alex and age=30 are the query parameters sent via GET.

    Example: GET Method in PHP

    <?php
      if( $_GET["name"] || $_GET["age"] ) {
          echo "Hello, " . htmlspecialchars($_GET['name']) . "<br />";
          echo "Your age is " . htmlspecialchars($_GET['age']);
          exit();
      }
    ?>
    <html>
    <body>
      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
        Name: <input type="text" name="name" />
        Age: <input type="text" name="age" />
        <input type="submit" />
      </form>
    </body>
    </html>

    Output:

    Hello, Alex
    Your age is 30

    In this example, the user enters their name and age, which is sent via the GET method. The data is displayed on the same page after submission.

    Advantages of GET:
    • The data is visible in the URL, making it easy to bookmark the page with query string values.
    • GET requests can be cached and stored in browser history.
    • They can also be bookmarked for future reference.
    Disadvantages of GET:
    • It’s unsuitable for sending sensitive data like passwords, as the information is exposed in the URL.
    • The amount of data you can send via GET is limited by the URL length.
    POST Method in PHP

    The POST method sends data to the server within the HTTP request body, making it invisible in the URL. This method is commonly used when you need to send large amounts of data or sensitive information.

    Example: POST Method in PHP

    <?php
       if( $_POST["name"] || $_POST["height"] ) {
           if (preg_match("/[^A-Za-z'-]/", $_POST['name'])) {
               die ("Invalid name, name should only contain letters.");
           }
           echo "Hello, " . htmlspecialchars($_POST['name']) . "<br />";
           echo "Your height is " . htmlspecialchars($_POST['height']) . " cm.";
           exit();
       }
    ?>
    <html>
    <body>
      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
         Name: <input type="text" name="name" />
         Height: <input type="text" name="height" />
         <input type="submit" />
      </form>
    </body>
    </html>

    Output:

    Hello, John
    Your height is 175 cm.

    In this example, the user’s name and height are submitted via the POST method. The form data is securely processed, and the result is displayed on the same page.

    Advantages of POST:
    • Since the data isn’t visible in the URL, it’s more secure for handling sensitive information.
    • The POST method allows sending large amounts of data, including files or binary data.
    Disadvantages of POST:
    • POST requests cannot be bookmarked since the data isn’t in the URL.
    • POST requests are not cached or stored in browser history, making it harder to retrieve past form submissions.

    PHP Regular Expressions

    Regular expressions, often abbreviated as regex or regexes, are sequences of characters that define search patterns used for matching text. They are commonly employed in algorithms to match loosely defined patterns, helping with tasks like data validation, searching, and text manipulation. Regexes can be considered a mini programming language with a specific syntax that allows users to parse and manipulate text strings, making them invaluable tools in many programming contexts.

    Regular expressions are powerful tools for working with string patterns, often used to efficiently match or extract certain sequences from text. PHP, being a popular open-source programming language, provides built-in support for regular expressions, just like many other programming languages. Different systems and languages may have their own syntax for regexes, but the basic concepts remain the same. Regexes are capable of working with very large text files or streams, and their applications are widespread across modern development environments.

    Key Uses and Benefits of Regular Expressions:

    1. Validation: Regexes can be used to validate user inputs such as email addresses, phone numbers, and IP addresses.
    2. Searching and Matching: They offer efficient ways to search for and extract specific string patterns in large datasets.
    3. Text Parsing: They are useful in parsing text files or streams to find patterns for further analysis or manipulation.
    4. Development Efficiency: Using regex saves development time when performing pattern matching and text processing.
    5. HTML Template Creation: Regexes help in recognizing tags and templates within HTML, allowing data to be substituted dynamically.
    6. Form Validations: Ensuring fields like passwords meet strength requirements by using regex to check for required characters.
    7. Other Uses: Regexes are used for browser detection, spam filtration, and keyword searching, among other applications.

    Regular Expression Syntax and Examples:
    Regular ExpressionMatches
    developersThe string “developers”
    ^developersStrings that begin with “developers”
    developers$Strings that end with “developers”
    ^developers$The exact string “developers”
    [xyz]Any one of the characters: x, y, or z
    [a-z]Any lowercase letter
    [^A-Z]Any character that is not an uppercase letter
    `(pngjpeg)`
    [a-z]+One or more lowercase letters
    ^[a-zA-Z0-9]{3, }$A word with at least three alphanumeric characters
    ([mn])([op])Matches: mo, mp, no, np
    [^a-zA-Z0-9]Any symbol other than letters or numbers
    `([A-Z]{2}[0-9]{4})`
    Key Regex Operators:
    OperatorDescription
    ^Indicates the start of the string
    $Indicates the end of the string
    .Matches any single character
    ()Groups expressions together
    []Matches any character within the brackets
    [^]Matches any character not in the brackets
    -Specifies a range (e.g., [a-z] for lowercase letters)
    ``
    ?Matches 0 or 1 of the preceding character
    *Matches 0 or more of the preceding character
    +Matches 1 or more of the preceding character
    {n}Matches exactly n occurrences
    {n,}Matches at least n occurrences
    {n, m}Matches between n and m occurrences
    \Escape character
    Special Character Classes:
    Special CharacterMeaning
    \nNew line
    \rCarriage return
    \tTab
    \vVertical tab
    \fForm feed
    \xhhHexadecimal character
    Example Functions in PHP:
    FunctionDescription
    preg_match()Searches for a pattern in a string and returns true if found
    preg_match_all()Searches for all occurrences of a pattern and returns all matches
    preg_replace()Searches and replaces occurrences of a pattern in a string
    preg_split()Splits a string by a regex pattern
    preg_grep()Searches for array elements that match a pattern

    PHP Example 1:

    <?php
    // Example of validating a name string with letters and spaces
    $regex = '/^[a-zA-Z ]+$/';
    $name = 'John Doe';
    
    if (preg_match($regex, $name)) {
        echo "Valid name string";
    } else {
        echo "Invalid name string";
    }
    ?>

    Output:

    Valid name string

    Example:

    <?php
    // Extract bold text within HTML tags
    $regex = "/<b>(.*)<\/b>/U";
    $string = "Title: <b>PHP</b> Version: <b>7.4</b>";
    
    preg_match_all($regex, $string, $matches);
    
    echo $matches[0][0] . " <br> " . $matches[0][1];
    ?>

    Output:

    PHP
    7.4

    Example:

    <?php
    // Replace year in a string
    $regex = "([0-9]+)";
    $original = "Graduated in 2010";
    $replaceWith = "2015";
    
    $updatedString = preg_replace($regex, $replaceWith, $original);
    echo $updatedString;
    ?>

    Output:

    Graduated in 2015
    Metacharacters:
    MetacharacterDescriptionExample
    .Matches any single character except newline/./ matches any character
    ^Matches the start of a string/^web/ matches “web” at the start
    $Matches the end of a string/end$/ matches “end” at the end
    *Matches zero or more occurrences/do*/ matches “do”, “dog”, etc.
    +Matches one or more occurrences/go+/ matches “go”, “good”, etc.
    \Escapes a metacharacter/\./ matches the literal dot
    POSIX Regular Expressions:
    RegexMeaning
    [0-9]Matches any digit
    [a-z]Matches any lowercase letter
    [A-Z]Matches any uppercase letter
    [:lower:]Matches any lowercase letter
    [:upper:]Matches any uppercase letter
    [:alnum:]Matches any alphanumeric character
    Quantifiers:
    QuantifierMeaning
    a+Matches one or more occurrences of “a”
    a*Matches zero or more occurrences of “a”
    a{2}Matches exactly two occurrences of “a”
    a{2,}Matches two or more occurrences of “a”
    a{2,5}Matches between two and five occurrences of “a”
    ^aMatches “a” at the start of a string
    a$Matches “a” at the end of a string
    [^a-zA-Z]Matches any character that is not a letter

    PHP Form Processing

    Processing Forms in PHP

    In this article, we will explore how to handle forms in PHP. HTML forms are designed to send user information to a server and return results to the browser. For instance, if you wish to collect visitor details on your website and send them positive messages, you can achieve this through form processing. The gathered information can be validated either on the client-side or server-side, and the final results are communicated back to the client via their web browser. To create an HTML form, you should utilize the <form> tag.

    Attributes of the Form Tag:
    AttributeDescription
    name or idSpecifies the name of the form, allowing for individual identification.
    actionIndicates the destination to which the form data will be sent upon submission.
    methodDefines the HTTP method to be used during form submission. Possible values include GET and POST. Using the GET method exposes the form data in the URL. The default method is GET.
    encTypeSpecifies the encoding type for the form data upon submission.
    novalidateInstructs the server not to validate form data upon submission.
    Controls Used in Forms:

    Form processing involves a variety of controls through which communication occurs between the client and the server. The controls typically found in forms are:

    • Textbox: A textbox allows users to input single-line data, suitable for entries like names or search queries.
    • Textarea: A textarea enables users to provide multi-line input, ideal for gathering information like addresses or messages.
    • Dropdown: A dropdown (or combobox) lets users select a value from a predefined list.
    • Radio Buttons: Radio buttons permit users to choose only one option from a specified set of options.
    • Checkbox: Checkboxes allow users to select multiple options from a provided list.
    • Buttons: Buttons are clickable elements used to submit the form.
    Creating a Simple HTML Form:

    All the aforementioned form controls can be created using the <input> tag based on its type attribute. In the following script, the form does not implement any event handling mechanism upon submission. Event handling refers to the processes executed during form submission, which can be managed using JavaScript or PHP. While JavaScript provides client-side validation, PHP is recommended for robust form processing.

    HTML Code:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Simple Form Processing</title>
    </head>
    <body>
        <form id="form1" method="post">
            First Name:
            <input type="text" name="firstname" required/>
            <br><br>
            Last Name:
            <input type="text" name="lastname" required/>
            <br><br>
            Address:
            <input type="text" name="address" required/>
            <br><br>
            Email Address:
            <input type="email" name="emailaddress" required/>
            <br><br>
            Password:
            <input type="password" name="password" required/>
            <br><br>
            <input type="submit" value="Submit"/>
        </form>
    </body>
    </html>

    Output:

    Current file: /path/to/current/script.php
    Form Validation:

    Form validation ensures that users provide the required information. Basic validation can be implemented using HTML attributes. For example, in the script above, the email input has a type of “email,” preventing incorrect entries. Each field in the form is marked with a required attribute, prompting users to complete all fields before submission.

    PHP Functions and Arrays Used in Form Processing:
    • isset(): This function checks whether a variable or form control has a value.
    • $_GET[]: Retrieves information from form controls via parameters sent in the URL.
    • $_POST[]: Fetches data from form controls using the HTTP POST method.
    • $_REQUEST[]: Used to retrieve data when working with databases.
    Form Processing Using PHP:

    The above HTML code is revised to include the necessary functions and arrays for validation. The rewritten script checks all fields, and if no errors occur, it displays the submitted information in a table format.

    Example:

    <?php
    if (isset($_POST['submit'])) {
        if ((!isset($_POST['firstname'])) || (!isset($_POST['lastname'])) ||
            (!isset($_POST['address'])) || (!isset($_POST['emailaddress'])) ||
            (!isset($_POST['password'])) || (!isset($_POST['gender']))) {
            $error = "*" . "Please fill all the required fields.";
        } else {
            $firstname = $_POST['firstname'];
            $lastname = $_POST['lastname'];
            $address = $_POST['address'];
            $emailaddress = $_POST['emailaddress'];
            $password = $_POST['password'];
            $gender = $_POST['gender'];
        }
    }
    ?>
    <html>
    <head>
        <title>Simple Form Processing</title>
    </head>
    <body>
        <h1>Form Processing with PHP</h1>
        <fieldset>
            <form id="form1" method="post" action="form.php">
                <?php
                    if (isset($_POST['submit'])) {
                        if (isset($error)) {
                            echo "<p style='color:red;'>" . $error . "</p>";
                        }
                    }
                ?>
                First Name:
                <input type="text" name="firstname"/>
                <span style="color:red;">*</span>
                <br><br>
                Last Name:
                <input type="text" name="lastname"/>
                <span style="color:red;">*</span>
                <br><br>
                Address:
                <input type="text" name="address"/>
                <span style="color:red;">*</span>
                <br><br>
                Email:
                <input type="email" name="emailaddress"/>
                <span style="color:red;">*</span>
                <br><br>
                Password:
                <input type="password" name="password"/>
                <span style="color:red;">*</span>
                <br><br>
                Gender:
                <input type="radio" value="Male" name="gender"> Male
                <input type="radio" value="Female" name="gender"> Female
                <br><br>
                <input type="submit" value="Submit" name="submit" />
            </form>
        </fieldset>
    
        <?php
        if (isset($_POST['submit'])) {
            if (!isset($error)) {
                echo "<h1>INPUT RECEIVED</h1><br>";
                echo "<table border='1'>";
                echo "<thead>";
                echo "<th>Parameter</th>";
                echo "<th>Value</th>";
                echo "</thead>";
                echo "<tr>";
                echo "<td>First Name</td>";
                echo "<td>".$firstname."</td>";
                echo "</tr>";
                echo "<tr>";
                echo "<td>Last Name</td>";
                echo "<td>".$lastname."</td>";
                echo "</tr>";
                echo "<tr>";
                echo "<td>Address</td>";
                echo "<td>".$address."</td>";
                echo "</tr>";
                echo "<tr>";
                echo "<td>Email Address</td>";
                echo "<td>" .$emailaddress."</td>";
                echo "</tr>";
                echo "<tr>";
                echo "<td>Password</td>";
                echo "<td>".$password."</td>";
                echo "</tr>";
                echo "<tr>";
                echo "<td>Gender</td>";
                echo "<td>".$gender."</td>";
                echo "</tr>";
                echo "</table>";
            }
        }
        ?>
    </body>
    </html>

    Output:

    INPUT RECEIVED
    
    +------------------+------------------+
    |     Parameter    |       Value      |
    +------------------+------------------+
    |    First Name    |     John         |
    |     Last Name    |     Doe          |
    |      Address     |     123 Main St  |
    |   Email Address   | john@example.com  |
    |     Password     |  password123     |
    |      Gender      |      Male        |
    +------------------+------------------+

    PHP Date and Time

    Handling date and time is a common task in PHP, especially when managing database queries or web development tasks. PHP provides built-in functions for these operations, and we’ll discuss some of the most useful ones below.

    PHP date() Function:

    The date() function in PHP is used to convert a timestamp into a more human-readable format, allowing us to work with dates and times in a flexible way.

    Why do we need the date() function?

    Dates and times in computers are stored as UNIX Timestamps, which are the number of seconds since the Unix epoch (January 1, 1970, 00:00:00 GMT). This raw format is not suitable for human interpretation, so PHP allows us to convert it into a readable format using the date() function.

    Syntax:

    date(format, timestamp)

    Explanation:

    • format: Specifies the format of the output.
    • timestamp (optional): If not provided, the current date and time will be used.

    Example: Here’s how you can use the date() function to get today’s date:

    <?php
      echo "Current date is: ";
      $currentDate = date("d-m-Y");
      echo $currentDate;
    ?>

    Output:

    Current date is: 23-10-2024
    Formatting Options in the date() Function:

    The format parameter allows us to specify how the date will be displayed. Below are some common formatting characters:

    • d: Day of the month (01 to 31).
    • D: Abbreviated day name (Mon to Sun).
    • m: Month number (01 to 12).
    • M: Abbreviated month name (Jan to Dec).
    • y: Two-digit year (e.g., 24 for 2024).
    • Y: Four-digit year (e.g., 2024).

    You can also include separators like hyphens (-), dots (.), slashes (/), etc., to format the date as desired.

    Example:

    <?php
      echo "Date formats:" . "\n";
      echo date("d/m/Y") . "\n";
      echo date("d-m-Y") . "\n";
      echo date("Y.m.d") . "\n";
      echo date("M-d-Y/D");
    ?>

    Output:

    Date formats:
    23/10/2024
    23-10-2024
    2024.10.23
    Oct-23-2024/Wed
    Time Formatting with date() Function:

    You can also use the date() function to format the time string using the following characters:

    • h: 12-hour format with leading zeros (01 to 12).
    • H: 24-hour format with leading zeros (00 to 23).
    • i: Minutes with leading zeros (00 to 59).
    • s: Seconds with leading zeros (00 to 59).
    • a: Lowercase am or pm.
    • A: Uppercase AM or PM.

    Example:

    <?php
      echo date("h:i:s A") . "\n";
      echo date("d-M-Y h:i:s a");
    ?>

    Output:

    03:14:29 PM
    23-Oct-2024 03:14:29 pm
    PHP time() Function:

    The time() function returns the current time as a Unix timestamp (the number of seconds since January 1, 1970, 00:00:00 GMT).

    Example:

    <?php
      $currentTimestamp = time();
      echo "Current timestamp: " . $currentTimestamp;
      echo "\n";
      echo "Formatted time: " . date("F d, Y h:i:s A", $currentTimestamp);
    ?>

    Output:

    Current timestamp: 1729674869
    Formatted time: October 23, 2024 03:14:29 PM
    PHP mktime() Function:

    The mktime() function is used to create a timestamp for a specified date and time. If no arguments are provided, it will return the current date and time.

    Syntax:

    mktime(hour, minute, second, month, day, year)

    Example:

    <?php
      echo mktime(12, 45, 30, 10, 23, 2024);
    ?>

    Output:

    1729674330

    PHP Date and Time

    In this article, we will explore the include() and require() functions in PHP, understand how they impact code execution, and examine their differences and usage through examples. As you may know, PHP enables us to create reusable functions and elements that might be needed on multiple pages. Writing the same function across different pages is time-consuming and error-prone. This repetition can be avoided using the concept of file inclusion, which allows you to insert external files—containing text or code—into a program, saving time and effort. If you need to update the code later, modifying the source file will automatically update all the files that include it. PHP offers two key functions for this purpose:

    1. include() function
    2. require() function

    We will explore both of these functions, their uses, and their differences through examples.

    PHP include() Function:

    The include() function allows us to include the contents of a file within another PHP file. It copies the contents of the specified file into the location where the include() function is called, before the server executes the rest of the script.

    Example: Using the include() function in PHP

    <?php
      // Contents of file_to_include.php
      echo "Hello from the file!";
    ?>

    Now, we can include this file in another PHP file, such as index.php:

    <?php
        include("file_to_include.php");
        echo "<br>File has been included successfully.";
    ?>
    PHP require() Function:

    The require() function works similarly to the include() function. It also copies the contents of the specified file into the location where it is called.

    Example: Using the require() function in PHP

    <?php
      // Contents of file_to_include.php
      echo "Hello from the file!";
    ?>

    We can include this file using the require() function in another PHP file:

    <?php
        require("file_to_include.php");
        echo "<br>File has been required successfully.";
    ?>
    Difference between include() and require() functions:

    While both include() and require() perform the same task of file inclusion, there is one key difference in how they handle errors. This difference becomes evident when an error arises, such as a missing file.

    Example 1: Using include() when a file is missing:

    <?php
        include("missing_file.php");
        echo "<br>This message is displayed even if the file is missing.";
    ?>

    Output:

    Warning: include(missing_file.php): Failed to open stream: No such file or directory in [file path] on line X
    Warning: include(): Failed opening 'missing_file.php' for inclusion in [file path] on line X
    This message is displayed even if the file is missing.

    PHP File Handling

    File handling in PHP allows you to create, open, read, write, delete, and manage files on a server. It’s especially useful when you need to store data persistently or handle file uploads by users. PHP provides a variety of built-in functions that simplify and secure file handling tasks.

    Common File Handling Functions in PHP
    • fopen() – Opens a file.
    • fclose() – Closes a file.
    • fread() – Reads data from a file.
    • fwrite() – Writes data to a file.
    • file_exists() – Checks if a file exists.
    • unlink() – Deletes a file.
    What is File Handling in PHP?

    File handling refers to the process of working with files on the server, including reading, writing, creating, or deleting files. It is crucial for applications requiring data storage and retrieval, such as logging systems, user-generated content, or file uploads.

    Opening and Closing Files

    Before performing operations like reading or writing to a file, it needs to be opened using the fopen() function, which returns a file pointer resource. After the file operations are done, the file should be closed using fclose() to free system resources.

    <?php
    
    // Open a file in read mode
    $file = fopen("example.txt", "r");
    
    if ($file) {
        echo "File opened successfully!";
        fclose($file); // Close the file after use
    } else {
        echo "Failed to open the file.";
    }
    
    ?>
    File Modes in PHP

    Files can be opened in several modes, such as:

    • "w" – Opens the file for writing. If the file doesn’t exist, a new one is created. If it exists, the contents will be erased.
    • "r" – Opens the file for reading only.
    • "a" – Opens the file for writing, appending data to the end. Existing data is preserved.
    • "w+" – Opens the file for both reading and writing. If it doesn’t exist, a new one is created. If it exists, its contents are erased.
    • "r+" – Opens the file for both reading and writing.
    • "a+" – Opens the file for both writing and reading, appending data to the end. If the file doesn’t exist, a new one is created.
    • "x" – Creates a new file for writing only.

    Reading from Files

    There are two primary ways to read the contents of a file in PHP:

    1. Reading the Entire File: You can use the fread() function or file_get_contents() to read the whole content of a file.

    <?php
    
    $file = fopen("example.txt", "r");
    $content = fread($file, filesize("example.txt"));
    
    echo $content;
    fclose($file);
    
    ?>

    2. Reading a File Line by Line: The fgets() function allows reading a file line by line.

    <?php
    
    $file = fopen("example.txt", "r");
    
    if ($file) {
        while (($line = fgets($file)) !== false) {
            echo $line . "<br>";
        }
        fclose($file);
    }
    
    ?>

    3. Writing to Files: To write data to a file, you can use the fwrite() function, which writes to an open file in the specified mode.

    <?php
    
    // Open a file in write mode
    $file = fopen("example.txt", 'w');
    
    if ($file) {
        $text = "Hello, PHP file handling!\n";
        fwrite($file, $text);
        fclose($file);
    }
    
    ?>

    4. Deleting Files: To delete a file in PHP, use the unlink() function.

    <?php
    
    if (file_exists("example.txt")) {
        unlink("example.txt");
        echo "File deleted successfully!";
    } else {
        echo "File does not exist.";
    }
    
    ?>

    1. Output for Each Example: Opening a file:

    File opened successfully!

    2. Reading the entire file:

    (Contents of example.txt displayed here)

    3. Reading the file line by line:

    (Each line of example.txt is displayed with <br> between lines)

    4. Writing to a file: No output. The contents of example.txt will be updated with the text “Hello, PHP file handling!”.

    5. Deleting a file:

    File deleted successfully!

    PHP Uploading File

    Approach: To execute the PHP script, you’ll need a server environment. Ensure you have either XAMPP or WAMP installed on your machine for testing purposes.

    HTML Code Snippet: Here’s an HTML code example for creating a file upload form. The enctype='multipart/form-data' is an encoding type that allows files to be sent through a POST method. Without this, files cannot be uploaded through the form.

    upload.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>File Upload</title>
    </head>
    <body>
        <form action="upload-handler.php" method="post" enctype="multipart/form-data">
            <h2>Select a File to Upload</h2>
            <label for="fileSelect">Choose File:</label>
            <input type="file" name="fileToUpload" id="fileSelect">
            <input type="submit" name="submit" value="Upload File">
            <p><strong>Note:</strong> Only .pdf, .docx, .txt files are allowed, with a maximum size of 3MB.</p>
        </form>
    </body>
    </html>

    In this form, we use the enctype attribute to ensure that the form can handle file uploads. The input field name fileToUpload will be used later in our PHP script to access the uploaded file.

    PHP File Upload Script: Now let’s create the PHP script to manage the file upload.

    upload-handler.php:

    <?php
    // Check if the form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
        // Check if file was uploaded without errors
        if (isset($_FILES["fileToUpload"]) && $_FILES["fileToUpload"]["error"] == 0) {
    
            // Allowed file types and extensions
            $allowed_extensions = array("pdf" => "application/pdf", "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "txt" => "text/plain");
            $file_name = $_FILES["fileToUpload"]["name"];
            $file_type = $_FILES["fileToUpload"]["type"];
            $file_size = $_FILES["fileToUpload"]["size"];
    
            // Extract file extension
            $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
    
            // Check if the file extension is allowed
            if (!array_key_exists($file_extension, $allowed_extensions)) {
                die("Error: Please upload a valid file format.");
            }
    
            // Check file size (max 3MB)
            $maxsize = 3 * 1024 * 1024;
            if ($file_size > $maxsize) {
                die("Error: File size exceeds the 3MB limit.");
            }
    
            // Verify file MIME type
            if (in_array($file_type, $allowed_extensions)) {
    
                // Check if the file already exists
                if (file_exists("uploads/" . $file_name)) {
                    echo "Error: " . $file_name . " already exists!";
                } else {
                    // Move the file to the uploads directory
                    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "uploads/" . $file_name);
                    echo "File uploaded successfully!";
                }
            } else {
                echo "Error: Invalid file type.";
            }
        } else {
            echo "Error: " . $_FILES["fileToUpload"]["error"];
        }
    }
    ?>

    In this script, we first check if the form was submitted using the POST method. Then, we access the uploaded file using the $_FILES array to retrieve the file name, size, and type. After that, we validate the file type and size. If the file passes the checks, we move it from its temporary location to the uploads folder on the server.

    Output:

    When the form is submitted, the following scenarios could occur:

    1. File Uploaded Successfully:

    File uploaded successfully!

    2. File Size Exceeds Limit:

    Error: File size exceeds the 3MB limit.

    3. Invalid File Type:

    Error: Please upload a valid file format.

    4. File Already Exists:

    Error: filename.docx already exists!

    5. General Upload Error:

    Error: (error code)

    PHP Cookies

    cookie in PHP is a small data file, typically 4KB in size, that a web server saves on a user’s computer. Cookies are mainly used to track user information, such as usernames, to personalize web experiences when the user revisits the site. Cookies can only be accessed by the domain that created them, and while they are usually set using HTTP headers, they can also be created using JavaScript.

    Setting a Cookie in PHP:

    To create a cookie in PHP, you use the setcookie() function. This function needs to be called before any output is generated by the script; otherwise, the cookie won’t be set.

    Syntax:

    setcookie(name, value, expire, path, domain, security);

    Parameters:

    • Name: The name of the cookie.
    • Value: The value to be stored in the cookie.
    • Expire: The expiration timestamp for the cookie. After this time, the cookie is no longer available.
    • Path: Specifies the path on the server where the cookie will be available.
    • Domain: Defines the domain where the cookie is accessible.
    • Security: Indicates if the cookie should only be sent over secure HTTPS connections.
    Operations on Cookies in PHP:

    1. Creating Cookies: This example creates a cookie named User_Preference with a value of "Dark Mode", which will expire after 3 days.

    <!DOCTYPE html>
    <?php
        setcookie("User_Preference", "Dark Mode", time() + 3 * 24 * 60 * 60);
    ?>
    <html>
    <body>
        <?php
            echo "Cookie has been set.";
        ?>
        <p>
            <strong>Note:</strong> You may need to reload the page to see the cookie's value.
        </p>
    </body>
    </html>

    Output:

    Cookie has been set.

    Note: Only the name parameter is mandatory in setcookie(). You can leave other parameters blank by providing an empty string ("").

    2. Checking if a Cookie is Set: It’s a good practice to check if a cookie exists before trying to access it. You can use the isset() function to verify whether a cookie is set.

    Example:

    <!DOCTYPE html>
    <?php
        setcookie("User_Preference", "Dark Mode", time() + 3 * 24 * 60 * 60);
    ?>
    <html>
    <body>
        <?php
        if (isset($_COOKIE["User_Preference"])) {
            echo "User preference is set to " . $_COOKIE["User_Preference"];
        } else {
            echo "No user preferences are saved.";
        }
        ?>
        <p>
            <strong>Note:</strong> Reload the page to check the cookie's value.
        </p>
    </body>
    </html>

    Output:

    User preference is set to Dark Mode

    3. Accessing Cookie Values: You can retrieve a cookie’s value using PHP’s $_COOKIE superglobal array. This array holds all the cookies sent by the user’s browser in the current request.

    Example:

    <!DOCTYPE html>
    <?php
        setcookie("User_Preference", "Dark Mode", time() + 3 * 24 * 60 * 60);
    ?>
    <html>
    <body>
        <?php
            echo "The current user preference is: " . $_COOKIE["User_Preference"];
        ?>
        <p>
            <strong>Note:</strong> Reload the page to access the cookie value.
        </p>
    </body>
    </html>

    Output:

    The current user preference is: Dark Mode

    4. Deleting Cookies: You can delete a cookie by calling setcookie() again but setting the expiration time to a point in the past.

    Example:

    <!DOCTYPE html>
    <?php
        setcookie("User_Preference", "Dark Mode", time() + 3 * 24 * 60 * 60);
    ?>
    <html>
    <body>
        <?php
            setcookie("User_Preference", "", time() - 3600);
            echo "Cookie has been deleted.";
        ?>
        <p>
            <strong>Note:</strong> Reload the page to ensure the cookie is deleted.
        </p>
    </body>
    </html>

    Output:

    Cookie has been deleted.

    PHP Sessions

    In general, a session refers to a period of communication between two entities. In PHP, sessions are used to store user data on the server rather than on the client side, offering a more secure way to manage user-related information. Each user in a session-based environment is assigned a unique identifier known as a Session ID (SID). The SID helps link users to their session data stored on the server, such as posts, emails, and other personal information.

    Why are Sessions Better than Cookies?

    While cookies are also used to store user-related data, they come with security concerns. Cookies are stored on the user’s computer, making them vulnerable to tampering. Attackers can easily modify cookie content, which may lead to malicious data being injected into the application. Moreover, cookies can slow down website performance, as they send user data back to the server every time the user loads a page. Each time the browser makes a request, all cookie data for that site is included in the request.

    Steps Involved in PHP Sessions:

    1. Starting a Session: To initiate a session, the session_start() function is used. This function starts a new session or resumes an existing one, and also generates a new session ID.

    Example:

    <?php
        session_start();
    ?>

    2. Storing Session Data: Session data can be stored as key-value pairs using the $_SESSION[] superglobal array. This data will persist across different pages during the session.

    Example:

    <?php
        session_start();
    
        $_SESSION["StudentID"] = "101";
        $_SESSION["StudentName"] = "Rahul";
    ?>

    3. Accessing Session Data: To retrieve session data, you must first call session_start() and then use the key from the $_SESSION array.

    Example:

    <?php
        session_start();
    
        echo 'The student\'s name is: ' . $_SESSION["StudentName"] . '<br>';
        echo 'The student\'s ID is: ' . $_SESSION["StudentID"] . '<br>';
    ?>

    Output:

    The student's name is: Rahul
    The student's ID is: 101

    4. Deleting Specific Session Data: To remove specific session data, you can use the unset() function with the particular session variable.

    Example:

    <?php
        session_start();
    
        if (isset($_SESSION["StudentName"])) {
            unset($_SESSION["StudentID"]);
        }
    ?>

    Output:

    Coding is challenging!

    Implementing callback in PHP

    In PHP, a callback is essentially a reference to a function that can be called later. A callback variable (or callable) can represent various types of functions such as normal functions, object methods, or static methods in classes. Below are a few ways to implement a callback in PHP:

    Standard Callback:

    In PHP, normal functions can be invoked through the call_user_func() function, where the argument is simply the function’s name as a string.

    Example:

    <?php
    
    // Function that prints a message
    function someFunction() {
        echo "Hello World \n";
    }
    
    // Calling the function via callback
    call_user_func('someFunction');
    ?>

    Output:

    Hello World
    Static Class Method Callback:

    Static methods in classes can also be invoked using call_user_func(). The argument in this case is an array where the first element is the class name and the second element is the method name.

    Example:

    <?php
    
    // Class definition
    class BaseClass {
    
        // Static method in the class
        static function someFunction() {
            echo "Base Class Method \n";
        }
    }
    
    class ChildClass extends BaseClass {
    
        // Static method in the child class
        static function someFunction() {
            echo "Child Class Method \n";
        }
    }
    
    // Callback for static method in the child class
    call_user_func(array('ChildClass', 'someFunction'));
    
    // Another way to call the same static method
    call_user_func('ChildClass::someFunction');
    
    // Callback to the parent class method using relative path
    call_user_func(array('ChildClass', 'parent::someFunction'));
    ?>

    Output:

    Child Class Method
    Child Class Method
    Base Class Method
  • PHP Functions

    PHP Functions

    A function is a set of instructions packaged into a single block that performs a specific task. To better understand how functions work, consider this analogy: imagine a boss asking an employee to compute the annual budget. The employee collects relevant data, performs the necessary calculations, and provides the result to the boss. Similarly, functions in programming take input (called parameters), perform operations, and return results.

    PHP provides two types of functions:
    • Built-in Functions: PHP has a large collection of pre-defined functions such as strlen()array_push()fopen(), etc., which we can call directly.
    • User-Defined Functions: In addition to built-in functions, PHP also allows us to create custom functions to encapsulate reusable code blocks.
    Why Use Functions?
    • Reusability: Functions allow you to reuse code across multiple parts of your program, minimizing redundancy.
    • Easier Error Detection: Since the code is divided into functions, it becomes easier to detect errors in specific parts.
    • Easy Maintenance: Functions make it easier to modify code, as changes within a function automatically propagate wherever the function is used.
    Why Use Functions?
    • Reusability: Functions allow you to reuse code across multiple parts of your program, minimizing redundancy.
    • Easier Error Detection: Since the code is divided into functions, it becomes easier to detect errors in specific parts.
    • Easy Maintenance: Functions make it easier to modify code, as changes within a function automatically propagate wherever the function is used.
    function functionName() {
        // Code to be executed
    }

    Example

    <?php
    
    function greet() {
        echo "Welcome to PHP!";
    }
    
    // Calling the function
    greet();
    
    ?>

    Output:

    Welcome to PHP!
    Function Parameters (Arguments)

    Parameters allow a function to accept input values during its execution. These parameters are specified inside the parentheses of the function. The values passed to these parameters during function calls are known as arguments.

    Syntax:

    function functionName($param1, $param2) {
        // Code to be executed
    }

    Example:

    <?php
    
    function add($a, $b) {
        $sum = $a + $b;
        echo "The sum is $sum";
    }
    
    // Calling the function with arguments
    add(5, 10);
    
    ?>

    Output:

    The sum is 15
    Setting Default Parameter Values

    PHP allows setting default values for parameters. If an argument isn’t passed during the function call, the default value is used.

    Example:

    <?php
    
    function introduce($name, $age = 30) {
        echo "$name is $age years old.\n";
    }
    
    // Function calls
    introduce("John", 25);  // Passes both parameters
    introduce("Jane");      // Uses default age
    
    ?>

    Output:

    John is 25 years old.
    Jane is 30 years old.
    Returning Values from Functions

    A function can also return a value using the return keyword. The returned value can be of any type, such as strings, numbers, arrays, or objects.

    Example:

    <?php
    
    function multiply($a, $b) {
        return $a * $b;
    }
    
    // Storing the returned value
    $result = multiply(4, 5);
    echo "The product is $result";
    
    ?>

    Output:

    The product is 20
    Passing Parameters by Value and Reference

    PHP allows you to pass function arguments either by value or by reference:

    • Pass by Value: A copy of the original value is passed to the function. Changes made inside the function don’t affect the original value.
    • Pass by Reference: The actual memory reference of the variable is passed, so changes made inside the function affect the original variable.

    Example:

    <?php
    
    // Pass by value
    function incrementByValue($num) {
        $num += 5;
        return $num;
    }
    
    // Pass by reference
    function incrementByReference(&$num) {
        $num += 10;
        return $num;
    }
    
    $number = 20;
    
    incrementByValue($number);
    echo "After pass by value: $number\n";  // Original value unchanged
    
    incrementByReference($number);
    echo "After pass by reference: $number\n";  // Original value changed
    
    ?>

    Output:

    After pass by value: 20
    After pass by reference: 30

    PHP Arrow Functions

    Arrow functions, introduced in PHP 7.4, provide a compact syntax for defining anonymous functions. They offer a more concise way to write single-line functions, which makes the code more readable and easier to manage.

    Syntax:

    $fn = fn($x) => expression;

    Example 1: Calculating the Product of Array Elements Using Arrow Functions

    In this example, we’ll declare an array and use the array_reduce() function combined with an arrow function to calculate the product of all the elements in the array.

    <?php
    
    // Declare an array
    $numbers = [2, 3, 4];
    
    // Using array_reduce with an arrow function to find the product
    $product = array_reduce($numbers, fn($carry, $item) => $carry * $item, 1);
    
    echo $product;
    
    ?>

    Output:

    24

    Example 2: Squaring Each Element of an Array Using Arrow Functions

    In this example, we’ll declare an array and use the array_map() function to square each element in the array using an arrow function.

    <?php
    
    // Declare an array
    $values = [2, 3, 4, 5];
    
    // Using array_map with an arrow function to square each element
    $squares = array_map(fn($n) => $n ** 2, $values);
    
    print_r($squares);
    
    ?>

    Output:

    Array
    (
        [0] => 4
        [1] => 9
        [2] => 16
        [3] => 25
    )

    Anonymous recursive function in PHP

    Anonymous recursive functions are a type of recursion where a function doesn’t explicitly call another function by name. Instead, recursion is achieved through the function referring to itself implicitly, often via closures or higher-order functions. These functions enable recursion without requiring a named function, which is particularly useful in scenarios where anonymous functions (closures) are used.

    Use of Anonymous Recursion:
    • Anonymous recursion is primarily used for recursion in anonymous functions, especially in closures or as callbacks.
    • It avoids the need to bind the function’s name explicitly, making the code more flexible in certain contexts.
    Alternatives:
    • Named functions can be used for recursion, but with anonymous functions, recursion can still be implemented by referring to the function within itself using mechanisms like closures.

    Example 1: Countdown with Anonymous Recursive Function

    The following example demonstrates anonymous recursion in PHP, where a function counts down from a specific number to 1.

    <?php
    // PHP program demonstrating anonymous recursion
    
    $countdown = function ($limit = null) use (&$countdown) {
        static $current = 5;
    
        // If $current reaches 0, stop recursion.
        if ($current <= 0) {
            return false;
        }
    
        // Print the current value
        echo "$current\n";
    
        // Decrement the value of $current
        $current--;
    
        // Recursive call
        $countdown();
    };
    
    // Function call
    $countdown();
    ?>

    Output:

    5
    4
    3
    2
    1

    Example 2: Calculating Factorial with Anonymous Recursive Function

    The next example calculates the factorial of a given number using anonymous recursion.

    <?php
    // PHP program demonstrating anonymous recursive function
    
    $factorial = function($num) use (&$factorial) {
    
        // Base case for recursion
        if ($num == 1)
            return 1;
    
        // Recursive case: multiply the current number by factorial of (num - 1)
        return $num * $factorial($num - 1);
    };
    
    // Function call to compute the factorial of 4
    echo $factorial(4);
    ?>

    Output:

    24
  • PHP Loops

    PHP Loops

    Similar to other programming languages, loops in PHP are used to repeatedly execute a block of code multiple times based on a condition. PHP offers several types of loops to handle different situations, including forwhiledo...while, and foreach loops. Let’s explore each of these loops, their syntax, and examples.

    Why Use Loops?

    Loops are useful for executing code repeatedly, which helps in:

    • Iterating through arrays or other data structures.
    • Performing actions multiple times.
    • Pausing execution until a condition is satisfied.

    1. PHP for Loop: The for loop is used when you know in advance how many times you want to execute a block of code. It consists of three parts:

    • Initialization: Sets the initial value of the loop variable.
    • Condition: Evaluates whether the loop should continue.
    • Increment/Decrement: Updates the loop variable after each iteration.

    Syntax:

    for (Initialization; Condition; Increment/Decrement) {
        // Code to execute
    }

    Example:

    <?php
    
    // Code to demonstrate for loop
    for ($num = 10; $num <= 15; $num++) {
        echo $num . " ";
    }
    
    ?>

    Output:

    10 11 12 13 14 15

    2. PHP while Loop: The while loop is an entry-controlled loop, meaning it first checks the condition before entering the loop. It continues running as long as the condition remains true.

    Syntax:

    while (condition) {
        // Code to execute
    }

    Example: Printing numbers from 5 to 9.

    <?php
    
    $num = 5;
    
    while ($num <= 9) {
        echo $num . " ";
        $num++;
    }
    
    ?>

    Output:

    5 6 7 8 9

    3. PHP do...while Loop: The do...while loop is an exit-controlled loop. It executes the code block first and then checks the condition, which means the code will run at least once, regardless of the condition.

    Syntax:

    do {
        // Code to execute
    } while (condition);

    Example:

    <?php
    
    $num = 20;
    
    do {
        echo $num . " ";
        $num++;
    } while ($num <= 25);
    
    ?>

    Output:

    20 21 22 23 24 25

    4. PHP foreach Loop: The foreach loop is used to iterate over arrays. For each iteration, it assigns the current array element to a variable and moves on to the next one.

    Syntax:

    foreach ($array as $value) {
        // Code to execute
    }
    
    // or
    
    foreach ($array as $key => $value) {
        // Code to execute
    }

    Example:

    <?php
    
    // foreach loop over a simple array
    $arr = array(100, 200, 300, 400);
    
    foreach ($arr as $val) {
        echo $val . " ";
    }
    
    echo "\n";
    
    // foreach loop over an associative array
    $fruits = array(
        "Apple" => 50,
        "Banana" => 30,
        "Orange" => 20
    );
    
    foreach ($fruits as $fruit => $price) {
        echo $fruit . " => " . $price . "\n";
    }
    
    ?>

    Output:

    100 200 300 400
    Apple => 50
    Banana => 30
    Orange => 20

    PHP while Loop

    The while loop is one of the simplest looping structures in PHP, used to repeatedly execute a block of code as long as the condition evaluates to true. The condition is evaluated at the start of each iteration, and if it’s true, the code block is executed. If the condition becomes false, the loop terminates.

    Syntax:

    while (condition) {
        // Code to be executed
    }

    Example 1: Using a while loop to display even numbers from 2 to 8.

    <?php
    
        // Initial number
        $num = 2;
    
        // While loop to print numbers
        while ($num <= 8) {
            echo $num . "\n";
            $num += 2;
        }
    
    ?>

    Output:

    2
    4
    6
    8
    while-endwhile Loop

    In PHP, there’s an alternate syntax for the while loop known as the while-endwhile structure. This style is often used in PHP templating to improve readability.

    Syntax:

    while (condition):
        // Code to execute
    endwhile;

    Example 2: Using the while-endwhile loop to display odd numbers from 3 to 9.

    <?php
    
        // Initial number
        $num = 3;
    
        // While loop with alternative syntax
        while ($num <= 9):
            echo $num . "\n";
            $num += 2;
        endwhile;
    
    ?>

    Output:

    3
    5
    7
    9

    PHP do-while Loop

    The do-while loop is quite similar to the while loop, with the key difference being that the do-while loop checks the condition at the end of each iteration. This means that the block of code inside the do-while loop is executed at least once, even if the condition is initially false.

    do {
        // Code to execute
    } while (condition);

    Example 1: Displaying numbers starting from 15, incrementing by 3 until the number is less than 25.

    <?php
    
        // Starting number
        $num = 15;
    
        // do-while Loop
        do {
            echo $num . "\n";
            $num += 3;
        } while ($num < 25);
    
    ?>

    Output:

    15
    18
    21
    24

    Example 2: Adding 7 to a number in each iteration until the number exceeds 30.

    <?php
    
        // Starting number
        $num = 1;
    
        // do-while Loop
        do {
            $num += 7;
            echo $num . "\n";
        } while ($num <= 30);
    
    ?>

    Output:

    8
    15
    22
    29
    36

    PHP for Loop

    The for loop in PHP is a powerful and flexible control structure, typically used when the number of iterations is known in advance. The loop involves three main expressions: initialization, condition testing, and updating the loop variable (increment or decrement).

    for (initialization expression; test condition; update expression) {
       // Code to be executed
    }
    Parameters of the for Loop:

    1. Initialization Expression: This sets the starting value of the loop control variable. For example: $num = 0;.
    2. Test Condition: This condition is evaluated at the start of each loop iteration. If it returns true, the loop body is executed; if it returns false, the loop terminates. For example: $num < 10;.
    3. Update Expression: After each loop iteration, the control variable is updated (usually incremented or decremented). For example: $num += 2;.

    Example:

    <?php
    
        // for loop to print numbers
        for( $num = 2; $num < 20; $num += 4) {
            echo $num . "\n";
        }
    
    ?>

    Output:

    2
    6
    10
    14
    18

    Example 2: Printing numbers divisible by 6 between 1 and 36.

    <?php
    
        // for loop to display multiples of 6
        for( $num = 1; $num < 40; $num++)
        {
            if($num % 6 == 0)
                echo $num . "\n";
        }
    
    ?>

    Output:

    6
    12
    18
    24
    30
    36

    PHP foreach Loop

    The foreach loop in PHP is designed specifically for working with arrays and objects. Unlike other loops, such as for or while, it automatically iterates over each element of the array or object without the need for manually managing indices or counters, making the code more readable and less error-prone.

    Key Benefits of foreach Loop:
    • Simple and clean syntax.
    • Automatically handles both keys and values in associative arrays.
    • Reduces the need for manual index management.

    Syntax of foreach Loop:

    foreach( $array as $element ) {
        // Code to be executed
    }

    Or, to access both keys and values:

    foreach( $array as $key => $element ) {
        // Code to be executed
    }
    Examples of foreach Loop:

    1. Iterating through Indexed Arrays: Indexed arrays contain elements that are stored with numeric keys. The foreach loop can iterate over them easily.

    <?php
    
    $numbers = [5, 10, 15, 20, 25];
    
    foreach ($numbers as $number) {
        echo $number . PHP_EOL;
    }
    
    ?>

    Output:

    5
    10
    15
    20
    25

    2. Iterating through Associative Arrays: Associative arrays store elements in key-value pairs. The foreach loop can handle both the key and the value, making it ideal for these types of arrays.

    <?php
    
    $user = [
        "username" => "john_doe",
        "age" => 28,
        "email" => "john.doe@example.com"
    ];
    
    foreach ($user as $attribute => $detail) {
        echo "$attribute: $detail" . PHP_EOL;
    }
    
    ?>

    Output:

    username: john_doe
    age: 28
    email: john.doe@example.com

    3. Iterating through Multidimensional Arrays: A multidimensional array contains other arrays as its elements. The foreach loop can be nested to handle multidimensional arrays.

    <?php
    
    $products = [
        ["name" => "Laptop", "price" => 1200],
        ["name" => "Smartphone", "price" => 800],
        ["name" => "Tablet", "price" => 400]
    ];
    
    foreach ($products as $product) {
        foreach ($product as $key => $value) {
            echo "$key: $value" . PHP_EOL;
        }
        echo "-----" . PHP_EOL;
    }
    
    ?>

    Output:

    name: Laptop
    price: 1200
    -----
    name: Smartphone
    price: 800
    -----
    name: Tablet
    price: 400
    -----

    4. Iterating through Object Properties: The foreach loop can also be used to iterate through the properties of an object. This is useful when dealing with data stored in objects.

    <?php
    
    class Book {
        public $title;
        public $author;
        public $year;
    
        public function __construct($title, $author, $year) {
            $this->title = $title;
            $this->author = $author;
            $this->year = $year;
        }
    }
    
    $book = new Book("1984", "George Orwell", 1949);
    
    foreach ($book as $property => $value) {
        echo "$property: $value" . PHP_EOL;
    }
    
    ?>

    Output:

    title: 1984
    author: George Orwell
    year: 1949

    5. Using break and continue in foreach Loop: The break statement exits the loop, while continue skips the current iteration and proceeds to the next one.

    <?php
    
    $numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    foreach ($numbers as $number) {
        if ($number % 2 !== 0) {
            continue;  // Skip odd numbers
        }
    
        echo $number . PHP_EOL;
    
        if ($number === 6) {
            break;  // Stop the loop once we reach 6
        }
    }
    
    ?>

    Output:

    2
    4
    6