Center Image of Mission image


The PHP Language

I wrote this article to share some key PHP concepts.  Even though it is a smaller language I can't write about every PHP feature.  I will try to give what I consider the important parts.  We will definitely talk about the CRUD (create,read,update,delete) concepts.

I love this language! Coming from classic ASP and working with JavaScript I feel this is a powerful scripting server-side language.  It is easy to learn and runs efficiently on an Apache server.  You can build dynamic and interactive Web pages.  It is widely used by major companies like WordPress, Facebook, Wikipedia, etc.   Let us not forget Twitter.

Check the PHP resources.

The PHP language stands for "Hypertext Preprocessor" and was developed in 1994 by Rasmus Lerdorf.  PHP is a server-side language and with MySQL, it is a powerful language capable of creating Dynamic websites.

In June of 1995, Rasmus released the PHP source code to the public.  This way the public can play with it and fix that bugs.

And in April of 1996, Rasmus introduced PHP/FI (Fast implementation).  In June the PHP/FI was given a version 2.0 status which made it a full-blown programming language.

Once it graduated to version 2.0 beta status, the underlined parsing engine was already being entirely rewritten in November 1997.  As I mentioned above WordPress, Facebook, Wikipedia, Twitter, MailChimp, Slack, and Dailymotion with MySQL are driving these companies.  It runs on various platforms (Windows, Linux, Unix, Mac OS X, more).

The common uses of PHP are to perform system functions.  It can generate dynamic page content  It can create, open, read, write, delete, and close files on the server.  It can handle forms of data collection and access cookies variables.  It can perform "CRUD" create, read, update and delete data from the MySQL database.  It can restrict users to access pages and encrypt data.



PEAR stands for PHP Extensions and Applications Repository.  It is a framework used to provide structure and open-source library of reusable PHP code for the Developer.  It is a community-driven project with the PEAR Group as the governing body and it was founded by Stig S. Bakken in 1999.  It also provides the command-line capability to install packages.


Command-Line Interface

To execute a PHP script from the command line use the PHP command-line interface (CLI) and specify the file name of the script.  Once you are in the command line all you have to do is enter "PHP script.php".


Case Sensitive

PHP is a partially case sensitive language.  The variable names are case sensitive, but functions, classes, and user-defined functions are not.


PHP Block

I should have mentioned earlier that to create a PHP block you use '<?php' and end the block using '?>'.  You can also use it this way '<?' And end with '?>'.  When you have a PHP block embedded within the HTML code this is considered escaping to PHP mode.


We would love to hear from you



These are the rules of a PHP variable.  You need to start a variable with a $ dollar sign in front of it and define it by simple assignment.  Other then the $ sign a variable needs to start with a letter character or underscore and after that, you can add any other character.

You can't start a variable with a number and characters like +,-,%,(,), . and &.

A function can create and access a variable within its scope and can be redefined for each path individually unlike the PHP constant.


Summary The Characteristics Of A PHP Variable

  • Variables are denoted with a dollar sign.
  • Variables are the value of its most recent assignment.
  • Variables are assigned with the = operator.
  • Variables can be, but do not need to be declared before the assignment.
  • Variables in PHP do not have intrinsic types which means you do not need to tell the interpreter that the variable will be an integer type.



Data Types Of Variables

In PHP there are eight different data types of variables.

  • Integers - these are whole numbers.
  • Doubles (floating points) - these are numbers with decimal points.
  • Null - is a special data type that can have only one value.  A variable of data type 'null' is a variable that has no value assigned to it - doesn't exist.
  • Boolean - these hold 'true' or 'false' values.
  • Strings - these are sequences of characters.
  • Arrays - are a name and key collections of other values.
  • Objects - these are define classes of collections of other values.
  • Resources - are special variables that hold references to external resources for PHP.




A PHP constant is an identifier for a simple value.  To define a constant in PHP you have to use the define() function and to retrieve the value of a constant you have to simply specify its name.  Once defined a constant can not be changed.

I want to mention that you can create a "constant" with a case-sensitive name, but if you include a third parameter "true" you can make it case-insensitive.

To define a constant use the 'define("MYCONSTANT", 300)' function and to retrieve the constant value use the 'constant("MYCONSTANT")' function.

The "constant()" function is used to return the value that you defined as a constant.

There are differences between a 'constant()' and a regular variable.  A constant variable does not need a dollar sign. You define a constant using the 'define()' function.  You can define and access a constant value from anywhere.  Again, when you make a variable a constant it can't be changed during the script.

Now, a valid constant name starts with a letter or underscore and it doesn't need a $ sign before it like a variable.  Plus, constants are automatically global across the entire script


PHP Built-in Constants

PHP constants that are built-in within the language.

  • __LINE__ = it represents the current line number of the file.
  • __FILE__ = it represents the full path and filename of the file.
  • __function__ = it represents the function name.
  • __class__ = it returns the class name as it was declared.
  • __method__ = it represents the class method name.



Break And Continue

I want to talk about two statements that PHP provides 1 called 'break' and the other one call 'continue'.  These are used within 'loops' and the 'switch' statement.

  • Break - it terminates the full loop or switch statement and transfers execution to the statement immediately following the full loop or switch.
  • Continue - it causes the loop to skip the remainder of its body and immediately retest its condition before reiterating.




PHP uses several different operators to accomplish comparison, arithmetic, assignment, increment/decrement, logical and string. Let's break down the different operators.  The "Comparison" operator is used to compare two values.  It uses the "==" operator to test if two objects are instances from the same class, same attributes and if it is equal.

But in strict mode, you use the three equal signs "===" which is used to test two objects that are referring to the same instance of the same class.

The PHP "Arithmetic" operators are used with numeric values to perform common arithmetical operations, like "+" addition, "-" subtraction, "*" multiplication, "/" division, "%" modulus, and "**" exponentiation.

The PHP "Assignment" operators are used with numeric values to assign a value to a variable.  The assignment operator "=" is used to assign a value that sits on the right of the expression to the left operand.

The PHP "Increment" operators are used to increment a variable's value and the "Decrement" operators are used to decrement the value.

The PHP "Logical" operators are used to combine conditional statements.  The PHP uses the "and", "our", "xor", "&&", "|", and "||".  The "String" operator has two operators a "." which concatenate 2 values and a ".=" to append a value to the same value.




In all programming languages, they all have a conditional statement that branches a program to go a different direction depending on an action you want your progam to take.

If a variable is true then it will perform an action based on that truth and if it is false do something else.

The below conditional statements will help you follow which direction to take.

  • if statement - will execute some code if one condition is true.
  • if...else statement - will execute some code if a condition is true and another code if that condition is false.
  • if...elseif...else statement - will execute different codes for more than two conditions.
  • switch statement - this will select one of many blocks of code to be executed.




The "include/require" statement takes all the content of one file and imports it in the current file before the server executes it.  Including content from another file make it useful when you want to "include/require" the same PHP, HTML, or text on multiple pages of a website.  Including files saves a lot of work.  This means that you can create a standard header, footer, or menu file for all your web pages.  Then, when the header needs to be updated, you can only update the header include file.

The "include" and require statements are identical, except upon failure.  When a file is included with the include statement and the it can't find it, the script will continue to execute.  If you use "require" then the execution of your program will fail and stop.

  • require - produces a fatal error (E_COMPILE_ERROR) and stop the script
  • include - only produce a warning (E_WARNING) and the script will continue



File Handling

When you want to run a block of code repeatedly you use "loops" in your programs.  They are used to execute the same block of code especially repeating it on other parts of your program, as long as a certain condition is true.

Like any other languages you will need to handle files in web application and PHP has several functions to choose from.  Like any language you can create, read, upload and edit a file.

PHP has the "readfile()" function is useful if all you want to do read its contents.  This function is the easiest way to read a file, but there's a better way to read a file.  I will explain in a little bit.


    echo readfile("sandcastle.txt");

As I mentioned above there's a better way to read a file.  The better method to open a file is to use "fopen()" function, it gives you more options than the readfile() function.

You start by putting the filename in the first parameter and the second is the mode that you need if you want to read and write to a file.


    $filename = fopen("sandcastle.txt", "r") or die("Unable to open file!");

    echo fread($filename,filesize("sandcastle.txt"));


These are the modes and description that you will need to open a file using "fopen".

  • r - Open Read-only: File pointer starts at the beginning of the file.
  • w - Open Write-only: Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file.
  • a - Open Write-only: The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist.
  • x - Create Write-only: Returns FALSE and an error if file already exists.
  • r+ - Open Read/Write: File pointer starts at the beginning of the file.
  • w+ - Open Read/Write: Erases the contents of the file or creates a new file if it doesn't exist.  File pointer starts at the beginning of the file.
  • a+ - Open Read/Write: The existing data in file is preserved.  File pointer starts at the end of the file.  Creates a new file if the file doesn't exist.
  • x+ - Create Read/Write: Returns FALSE and an error if file already exists.


* Open File - fopen()

This function is a better way to open a file.  It gives you more options than the limited "readfile()" function.  After a call to the "fgets()" function, the pointer moved to the next line.

* Read File - fread()

This function reads from an open file.  It contains the name of the file to read and the second parameter specifies the maximum number of bytes to read.

* Read Single Line - fgets()

This function is used to read a single line of data from a file.

    $filename = fopen("sandcastle.txt", "r") or die("Unable to open file!");

    echo fgets($filename);

f    close($filename);

* Check End-Of-File - feof()

This function checks if the file reached the end of file (EOF) and it is useful for looping the file of unknown length.

    $filename = fopen("sandcastle.txt", "r") or die("Unable to open file!");

    // Output one line until end-of-file
    while(!feof($filename)) {
    echo fgets($filename);


* Read Single Character - fgetc()

This function is used to read a single character from a file.

$filename = fopen("sandcastle.txt", "r") or die("Unable to open file!");

    // Output one character until end-of-file
    while(!feof($filename)) {
     echo fgetc($filename);

* Close File - fclose()

This function is used to close an open file.

    $filename = fopen("webdictionary.txt", "r");

    // some code to be executed....

* Create File - fopen()

You are going to notice that this function was use above to open and read a file, that 's because it is also used to create a file. This function will create your file if it doesn't exist as long as you use mode "w" write. If you are appending to the file use "a" append.

Example:     $filename = fopen("sandcastle.txt", "w");

PHP File Permissions You have to make sure your PHP file have write access on your hard drive.

* Write to File - fwrite()

This function is used to write to a file and the first parameter of "fwrite()" contains the name of the file your are writing to. The second parameter is the string that you are adding .

PHP Overwriting The "sandcastle.txt" file contains data and when we open an existing file for writing and all the existing data will be erased by using the "w" mode.  If you want to append use the "a" mode.



Reading a JSON File

* Read a complete file - file_get_contents()

We talked about about using "fgets" to get content, there's other command that reads the whole file. It is great when you want a whole file, it is called "file_get_contents".

It is a fantastic way to read a JSON (Javascript Object Notation) file.

Here's the JSON file:
        "description":"a count of an array"

We will create two variables, one will hold the whole json file by using "file_get_contents". The other command (json_decode) decodes the json file where you are going to use the "foreach" statement to iterate through it.

Add the below to your HTML file.

$jsondata = file_get_contents("phpcode.json");
$json = json_decode( $jsondata,true );

Create the html code to display your json data.

<!DOCTYPE html> <html>
<div id="container">

/* Since the actual data is sitting in an array we will use the "foreach" command to iterate through the object and display them.*/

Foreach( $json['phpCommand'] as $key => $value ) {
    echo $value['command'] ."=". $value['description'];


Use the above technique is not just for JSON file, use the "file_get_contents()" to read any file.




We use a cookie to identify a user.  A cookie is a small file and it only holds up to 4096 Bytes.  The server embeds information on the user's computer and the same computer requests a page that access the cookies value that you create earlier.

Create Cookies With PHP

You use the "setcookie()" function to set a value in a cookie.

Create/Retrieve a Cookie

I assigned two variables the values "oil" to "$cType" and the color red to "$cColor", then set the cookie using the "setcookie" function.

Use the global variable $_COOKIE to retrieve the values you assigned using the "setcookie" function.


    $cType = oil";
    $cColor = "red";
    setcookie($cookie_name, $cookie_value);

    echo "Value is: " . $_COOKIE[cType];
    echo "Value is: " . $_COOKIE[$cColor ];

Modify a Cookie Value

Look how easy it is to modify your cookie.  All you have to do is set your cookie again using the "setcookie" function.

Delete a Cookie

To delete a cookie use the same "setcookie()" function, but instead of assigning an expiration to a future date just set your expiration date to one hour ago.

Check if Cookies are Enabled

Check to see if cookies are enabled.  Create a cookie with the "setcookie()" function, then count the $_COOKIE array variable.


    setcookie("test_cookie", "test", time() + 3600, '/');

    //Check if a cookie exist
    if(count($_COOKIE) > 0) {
    echo "Cookies are enabled.";
    } else {
    echo "Cookies are disabled.";


A "Session" variables are like "Cookies" except of storing the cookie on the client-side, it stores it on the server-side.  Sessions can be used across multiple pages.

PHP Session

To start a session use the "session_start()" function.  All variables are set and stored within the PHP global variable "$_SESSION".  You can access the session information from any pages.  Session variables are passed from the "session_start()".


    session_start(); // put on top of your HTML file

    // Echo session variables that were set on previous page
    echo "I use oil paint color " . $_SESSION["oil"] . ".";
    echo "I keep it simple by using " . $_SESSION["pens"] . ".";

Modify Session Variable

To modify your session variable all you hve to do is over write it.


    $_SESSION["oil"] = "yellow";

Destroy Session Variable

If you want to remove all global session variables you must use the "session_unset()".  You can use "session_destroy()" to destroy it.


    // to remove all session variables



When you want to run a block of code repeatedly you use "loops" in your programs.  They are used to execute the same block of code especially repeating it on other parts of your program, as long as a certain condition is true.

Here are the following loop types:

  • while - it will loop through a block of code as long as the specified condition is true.
  • do...while - the "do" part loops through a block of code once, and then repeats the loop as long as the specified condition is true.
  • for - this loop goes through a block of code a specified number of times.  This loop is a more complex one.  You assign a variable, check for conditions and increments the variable as long as the condition is iterating.
  • foreach - this loop only works on arrays, and is used to loop through each key/value pair in an array.




The PHP functions have real power especially the custom function you create.  PHP comes with built-in over 500 functions that you can use by calling it directly from within your custom function.

As I mentioned you can create your functions and use the built-ins giving you the power of the language.  A function is a block of statements that can be used repeatedly in a program.  It does not execute automatically when a page loads except a call to the function.

You can pass data to a function through arguments and use commas to separate multiple arguments.  An argument is data pass to a function within the two parentheses.  Once the argument reaches the function and is being used it is called a "parameter".

Information can be passed to the functions() through arguments.  An argument is just like a variable and it is specified after the function name, inside the parentheses.  You can add as many arguments as you want, just separate them with a comma.




The "Array" function is a special variable which can hold several value at a time.  Plus, it allows you to access and manipulate simple/multi-dimensional arrays.

There are three types of arrays that you can work with.  The first array is the standard array called "Indexed Array".  The "Indexed arrays" are assigned with a numeric index automatically and it start with [0].  You can add an index manually to the array.


  • $paint = array("oil", "color_pencil", "watercolor");
  • $paint[3] = "chalk";

The Associative arrays are like the standard "indexed" array except that you use a name key that you assign to them.  There are two ways to create and assign an associative array.


  • $arts = array("oil"=>"red", "color_pencil"=>"orange", "watercolor"=>"blue");
  • $arts['chalk'] = "green";

Now, you have the multidimensional array that contains one or more arrays.  The multidimensional array is an array that can hold multiple levels of the array.  You can go very deep, but stick to 2 to 3 levels, unwise you will find you're pulling your hair out.


  • $arts = array(




Superglobals are built-in variables that are available in all scopes which means that they are always accessible.  PHP "superglobals" was introduce in version 4.1.0. and regardless of scope you can access them from any function, class or file without having to do anything special.

The PHP $GLOBALS is variable which is used to access the built-in global variables across your progam which means that it can be use from every part of your program scope.  It can go across all functions, even within itself.

It can store all global variables in an array called $GLOBALS[index].  The index holds the name of the variable.

The "$_SERVER" super global variable holds information about headers, paths, and script locations.  Three about 24 elements that you can use with "$_SERVER" and I am not going to list them here.

Here's 5 that I use all the time: 'PHP_SELF", "SERVER_NAME", "HTTP_HOST", "QUERY_STRING", "REMOTE_ADDR", and "REMOTE_HOST".


  • $_SERVER['PHP_SELF'] - this element returns the filename of the currently executing script.
  • $_SERVER['HTTP_HOST'] - this element returns the Host header from the current request.
  • $_SERVER['SERVER_NAME'] - this element returns the name of the host server (such as arj-web-designs.com).
  • $_SERVER['QUERY_STRING'] - this element returns the query string if the page is accessed via a query string.
  • $_SERVER['REMOTE_ADDR'] - this element returns the IP address from where the user is viewing the current page.
  • $_SERVER['REMOTE_HOST'] - this element returns the Host name from where the user is viewing the current page.

The "$_REQUEST" element is use to collect the values of your input fields in a form.  When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the



  • $name = $_REQUEST['fname'];
  • echo $name;

The PHP "$_POST" is also a super global variable like the "$_GET" element which is also used to collect form data after submitting an HTML form with method="post".  This element is widely used to pass variables.


  • $name = $_POST['fname'];
  • echo $name;

The PHP "$_GET" is also a super global variable like the "$_POST" element which is also used to collect form data after submitting an HTML form with method="get".  his element is widely used to pass variables.  Since you are using the "get" method the data will be sent to a file with parameter via the URL.


  • index.php?catalog=PHP&web=arj-web-designs.com

You can get and print all of the parameters using "$_GET[]". See below.


  • echo "Here is your " . $_GET['catalog'] . " of website " . $_GET['web'];




Over the years, companies have come up with Frameworks in PHP that speed up your PHP programming time like jQuery which they did for JavaScript.

These are the names of the frameworks that will help you speed up your PHP projects.

  • cakePHP - CakePHP makes building web applications simpler, faster, while requiring less code.
  • CodeIgniter - CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.
  • Yii2 - Yii is a fast, secure, and efficient PHP framework. It is flexible, works right out of the box.
  • Symfony - Symfony is a set of reusable PHP components.
  • Zend Framework - Zend Framework is a collection of professional PHP packages with installations and it's used to develop web applications.



OOP - Object Oriented Programming

In the OOP - Object-Oriented Programming world, there are several advantages over procedural programming.

By programming, in this style, you can take advantage of having faster and easier execution.  It provides a clear structure for your programs.  It also helps keep your programs DRY "Don't Repeat Yourself" and makes it easier to create reusable programs with less code.  Plus, it makes it easier to maintain, debug and modify.

The PHP OOP has two main aspects called "Classes" and "Objects".  A "Class" is the blueprint where objects can be instantiated.  When you create an object, the object will inherit all the properties/behaviors from the class. We can define several different variables like $name, $color, and $weight to hold the values of these properties.

A class is created by using the "class" keyword which is followed by a name that you will give with a pair of curly braces. All properties and methods are written between the two curly braces.

We can create multiple objects from one class.  Each object inherits all the properties and methods that you defined in the class, but they all can have different properties.  And when you use the "$this" keyword it refers to the current object.  It is only available inside the methods that you create in a class.

The 'final' keyword in a method declaration indicates that the method can't be overridden by subclasses.  A 'class' that is declared final can't be a subclass.  This is particularly useful when we are creating an immutable class like the string class.

You can use the "instance of" keyword to check if an object belongs to a specific class.




Well there you have it.  I gave you enough PHP information to get you interested in the language and I hope it help you.  I will provide more in the future or add more to this page.  To next time!

Center Image of Mission image
Image of a dark blue phone that you can click to make a call.  Will only work on a mobil phone.
Enter Your Information

An image of reCapture icon

Thanks for your interest in our services. Please, leave detail Information regarding your creative needs. Someone from our professional team will get back to you at their earliest convenience.

Please, make sure you leave your name, address and your phone number or you can contact us direct at (201) 486-9155.

Note: Your email address will not be distributed in anyway.