Welcome To PHP language

PHP Introduction

The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development

The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP with client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser.

  • Websites like www.facebook.com, www.yahoo.com are also built on PHP.
  • One of the main reason behind this is that PHP can be easily embedded in HTML files and HTML codes can also be written in a PHP file.
  • The thing that differentiates PHP with client-side language like HTML is, PHP codes are executed on server whereas HTML codes are directly rendered on the browser. PHP codes are first executed on the server and then the result is returned to the browser.
  • The only information that the client or browser knows is the result returned after executing the PHP script on the server and not the actual PHP codes present in the PHP file. Also, PHP files can support other client-side scripting languages like CSS and JavaScript.


Why should we use PHP SCRIPTING LANGUAGE ?

PHP can actually do anything related to server-side scripting or more popularly known as the backend of a website. For example, PHP can receive data from forms, generate dynamic page content, can work with databases, create sessions, send and receive cookies, send emails etc. There are also many hash functions available in PHP to encrypt user’s data that makes PHP secure and reliable to be used as a server-side scripting language. So these are some of the abilities of PHP that makes it suitable to be used as server-side scripting language. You will get to know more of these abilities in further tutorials.

Even if you are not convinced by the above abilities of PHP, there are some more features of PHP. PHP can run on all major operating systems like Windows, Linux, Unix, Mac OS X etc. Almost all of the major servers available today like Apache supports PHP. PHP allows using wide range of databases. And the most important factor is that it is free to use and download and anyone can download PHP from its official source : www.php.net.



Syntax for PHP

A PHP script can be placed anywhere in the document. A PHP script starts with <?php and ends with ?>:

<!DOCTYPE html>
<html>
<body>
<h1>
My first PHP page</h1>
<?php echo "Hello World!"; ?>
</body>
</html>


Now the time has come to diccuss about php case senstivness

In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not case-sensitive. In the example below, all three echo statements below are equal and legal:

<!DOCTYPE html>
<html>
<body>
<?php ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>


COMMENTS and VARIABLES in php



comment

A comment is something which is ignored and not read or executed by PHP engine or the language as part of a program and is written to make the code more readable and understandable. These are used to help other users and developers to describe the code and what it is trying to do. It can also be used in documenting a set of code or part of a program. You must have noticed this in above sample programs.


This scripting language PHP supports only two types of comment:

  1. SINGLE LINE COMMENT
  2. MULTI-LINE COMMENT

Single Line Comment: As the name suggests these are single line or short relevant explanations that one can add in there code. To add this, we need to begin the line with (//) or (#).

<?php
// This is a single line comment
// These cannot be extended to more lines

echo "hello world!";

# This is also a single line comment
?>


Multi-line or Multiple line Comment: These are used to accomodate multiple lines with a single tag and can be extended to many lines as required by the user. To add this, we need to begin and end the line with (/*…*/)

<?php
/* This is a multi line comment
In PHP variables are written
by adding a $ sign at the beginning.*/

$codolearn = "hello world!";
echo $codolearn;
?>


VARIABLES IN PHP

variables in a program are used to store some values or data that can be used later in a program . php has it own way to declaring and storing variables . there are few rules , that are needed to be followed and facts that needs to be kept in mind while dealing with variables in PHP SCRIPTING LANGUAGE



  • Any variables declared in PHP must begin with a dollar sign ($), followed by the variable name.
  • A variable can have long descriptive names (like $factorial, $even_nos) or short names (like $n or $f or $x)
  • A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-z’, ‘A-Z’, ‘0-9 and ‘_’) in their name.
  • Assignment of variables are done with assignment operator, “equal to (=)”. The variable names are on the left of equal and the expression or values are to the right of the assignment operator ‘=’.
  • One must keep in mind that variable names in PHP names must start with a letter or underscore and no numbers.
  • PHP is a loosely typed language and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values. Same happens while conversion.
  • PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.


<?php

// These are all valid declarations
$val = 5;
$val2 = 2;
$x_Y = "CODOLEARN";
$_X = "CODOLEARNERS";

// This is an invalid declaration as it
// begins with a number
$10_ val = 56;
// This is also invalid as it contains
// special character other than _
$f.d = "num";
?>


SCOPES IN VARIABLE

Scope of a variable is defined as its extent in program within which it can be accessed, i.e. the scope of a variable is the portion of the program with in which it is visible or can be accessed. Depending on the scopes, PHP has three variable scopes:


  • LOCAL VARIABLE
  • GLOBEL VARIABLE
  • STATIC VARIABLE

LOCAL VARIABLE : The variables declared within a function are called local variables to that function and has its scope only in that particular function. In simple words it cannot be accessed outside that function. Any declaration of a variable outside the function with same name as that of the one within the function is a complete different variable. We will learn about functions in details in later articles. For now consider a function as a block of statements.
<?php
$num = 100;

function codolearn()
{
// This $num is local to this function
// the variable $num outside this function
// is a completely different variable
$num = 50;
echo "local num = $num \n";
}

codolearn();
// $num outside function codolearn() is a
// completely different Variable than that of
// inside codolearn()
echo "Variable num outside codolearn() is $num \n";
?>


GLOBAL VARIABLE: The variables declared outside a function are called global variables. These variables can be accessed directly outside a function. To get access within a function we need to use the “global” keyword before the variable to refer to the global variable.
<?php

$num = 20;
// function to demonstrate use of global variable function CODOLEARN()
{
// we have to use global keyword before
// the variable $num to access within
// the function
global $num;

echo "Variable num inside function : $num \n";
}

CODOLEARN();

echo "Variable num outside function : $num \n";
?>


STATIC VARIABLE: It is the characteristic of PHP to delete the variable, ones it completes its execution and the memory is freed. But sometimes we need to store the variables even after the completion of function execution. To do this we use static keyword and the variables are then called as static variables.
<?php
// function to demonstrate static variables
function static_var()
{
// static variable
static $num = 5;
$sum = 2;

$sum++;
$num++;

echo $num, "\n";
echo $sum, "\n";
}

// first function call
static_var();

// second function call
static_var();
?>


ECHO IN PHP

What is echo() in php

basically PHP echo statement can be used to print the string, multi-line strings, escaping characters, variable, array, etc. Some important points that you must know about the echo statement are: echo is a statement, which is used to display the output. echo can be used with or without parentheses: echo(), and echo.

However, there are two basic ways to get output in PHP:-

  • echo
  • print

ECHO STATEMENT IN PHP

In PHP ‘echo’ statement is a language construct and never behaves like a function, hence no parenthesis required. The end of echo statement is identified by the semi-colon (‘;’). We can use ‘echo’ to output strings or variables. Below are some of the usage of echo statement in PHP:

  • Displaying Strings: We can simply use the keyword echo followed by the string to be displayed withing quotes. Below example shows how to display strings with PHP:

  • <?php
    echo "Hello,This is a display string example!";
    ?>
    


  • Displaying strings as multiple arguments : We can pass multiple string arguments to the echo statement instead of single string argument, separating them by comma (‘,’) operator. For example, if we have two strings say “Hello” and “World” then we can pass them as (“Hello”,”World”). Below example shows how to do this:

  • <?php
    echo "Multiple ","argument ","string!";
    ?>
    


  • Displaying variables : Displaying variables with echo statement is also as easy as displaying normal strings. Below example shows different ways to display variables with the help of PHP echo statement:-

  • <?php
    //defining the variables
    $text = "Hello, World!";
    
    $num1 = 100;
    
    $num2 = 50;
    
    //echoing the variables
    echo $text."\n";
    
    echo $num1."+".$num2."=";
    
    echo $num1 + $num2;
    ?>
    


    The (.) operator in the above code can be used to concatenate two strings in PHP and the “\n” is used for a new line and is also known as line-break. We will learn about these in further articles.



PRINT STATEMENT IN PHP

The PHP print statement is similar to the echo statement and can be used alternative to echo at many times.It is also language construct and so we may not use parenthesis : print or print(). The main difference between the print and echo statement is that print statement can have only one argument at a time and thus can print a single string. Also, print statement always returns a value 1. Like echo, print statement can also be used to print strings and variables. Below are some examples of using print statement in PHP:

  • Displaying string of text: We can display strings with print statement in the same way we did with echo statements. The only difference is we can not display multiple strings separated by comma(,) with a single print statement. Below example shows how to display strings with the help of PHP print statement:-

  • <?php
    print "Hello, world!";
    ?>
    


  • Displaying variables : Displaying variables with print statement is also same as that of echo statement. The example below shows how to display variables with the help of PHP print statement :-

  • <?php
    //defining the variables
    $text = "Hello, World!";
    
    $num1 = 10;
    
    $num2 = 20;
    
    //echoing the variables
    print $text."\n";
    
    print $num1."+".$num2."=";
    
    print $num1 + $num2;
    ?>
    




DATA TYPES IN PHP

Data Types defines the type of data a variable can store. PHP allows eight different types of data types. All of them are discussed below. The first five are called simple data types and the last three are compound data types:

  • INTERGER : Integers hold only whole numbers including positive and negative numbers, i.e., numbers without fractional part or decimal point. They can be decimal (base 10), octal (base 8) or hexadecimal (base 16). The default base is decimal (base 10). The octal integers can be declared with leading 0 and the hexadecimal can be declared with leading 0x. The range of integers must lie between -2^31 to 2^31.

  • <?php
    
    // decimal base integers
    $deci1 = 50;
    $deci2 = 654;
    
    // octal base integers
    $octal1 = 07;
    
    // hexadecimal base integers
    $octal = 0x45;
    
    $sum = $deci1 + $deci2;
    echo $sum;
    ?>
    


  • DOUBLE : Can hold numbers containing fractional or decimal part including positive and negative numbers. By default, the variables add a minimum number of decimal places.

  • <?php
    
    $value1 = 50.85;
    $value2 = 654.26;
    
    $sum = $value1 + $value2;
    
    echo $sum;
    ?>


  • STRING : Hold letters or any alphabets, even numbers are included. These are written within double quotes during declaration. The strings can also be written within single quotes but it will be treated differently while printing variables. To clarify this look at the example below.

  • <?php
    
    $name = "CODOLEARN";
    echo "THIS IS CODOLEARN $name \n";
    echo 'this is codolearner $name';
    
    ?>


  • NULL : These are special types of variables that can hold only one value i.e., NULL. We follow the convention of writing it in capital form, but its case sensitive.

  • <?php
    
    $nm = NULL;
    echo $nm; // This will give no output
    
    ?>
    


  • Boolean: Hold only two values, either TRUE or FALSE. Successful events will return true and unsuccessful events return false. NULL type values are also treated as false in Boolean. Apart from NULL, 0 is also consider as false in boolean. If a string is empty then it is also considered as false in boolean data type

  • <?php
    
    if(TRUE)
    echo "This condition is TRUE";
    if(FALSE)
    echo "This condition is not TRUE";
    
    ?>
    


  • Arrays: Array is a compound data-type which can store multiple values of same data type. Below is an example of array of integers.

  • <?php
    
    $intArray = array( 10, 20 , 30);
    
    echo "First Element: $intArray[0]\n";
    echo "Second Element: $intArray[1]\n";
    echo "Third Element: $intArray[2]\n";
    
    ?>
    




STRINGS IN PHP

PHP String Functions

In this chapter we will look at some commonly used functions to manipulate strings.

strlen() - Return the Length of a String

The PHP strlen() function returns the length of a string.


<?php
echo strlen("Hello world!!!!"); // outputs 15
?>


str_word_count() - Count Words in a String

The PHP str_word_count() function counts the number of words in a string.


<?php
echo str_word_count("Hello world!"); // it will return only 2
?>


strrev() - Reverse a String

The PHP strrev() function reverses a string.


<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>


strpos() - Search For a Text Within a String

The PHP strpos() function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.


<?php

echo strpos("Hello world!", "world"); // outputs 6

?>


str_replace() - Replace Text Within a String

The PHP str_replace() function replaces some characters with some other characters in a string.


<?php

echo str_replace("world", "CODOLEARN", "Hello world!"); // outputs Hello CODOLEARN!

?>



CONSTANT IN PHP

Constants are either identifiers or simple names that can be assigned any fixed values. They are similar to a variable except that they can never be changed. They remain constant throughout the program and cannot be altered during execution. Once a constant is defined, it cannot be undefined or redefined. Constant identifiers should be written in upper case following the convention. By default, a constant is always case-sensitive, unless mentioned. A constant name must never start with a number. It always starts with a letter or underscores, followed by letter, numbers or underscore. It should not contain any special characters except underscore, as mentioned.

this is basic syntax just below the para


define(name, value, case_insensitive)


  • name: The name of the constant.
  • value: The value to be stored in the constant.
  • case_insensitive: Defines whether a constant is case insensitive. By default this value is False, i.e., case sensitive.

<?php

// This creates a case-sensitive constant
define("WELCOME", "CODOLEARN");
echo WELCOME, "\n";

// This creates a case-insensitive constant
define("HELLO", "CODOLEARN", true);
echo hello;

?>


CONTANT FUNCTION()

Instead of using the echo() statement , there is an another way to print Constants using constant() function .


<?php

define("WELCOME", "CODOLEARN !!");

echo WELCOME, "\n";

echo constant("WELCOME");
// same as previous

?>


constant are global : By default, constants are automatically global, and can be used throughout the script, accessible inside and outside of any function.

CONTANT VS VARIABLES

  • A constant, once defined can never be undefined but a variable can be easily undefined.
  • There is no need to use dollar sign($) before constants during assignment but while declaring variables we use a dollar sign.
  • A constant can only be defined using a define() function and not by any simple assignment.
  • Constants dont need to follow any variable scoping rules and can be defined anywhere.

Constants are Global


<?php
define("GREETING", "Welcome to CODOLEARN!");

function myTest() {
echo hi;
}
+
myTest();
?>



OPERATOR IN PHP

Operators are used to perform operations on some values. In other words, we can describe operators as something that takes some values, performs some operation on them and gives a result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes two values 1 and 2, performs addition operation on them to give 3. Just like any other programming language, PHP also supports various types of operations like the arithmetic operations(addition, subtraction, etc), logical operations(AND, OR etc), Increment/Decrement Operations etc. Thus, PHP provides us with many operators to perform such operations on various operands or variables or values. These operators are nothing but symbols needed to perform operations of various types. Given below are the various groups of operators:

  • Arithmetic Operators
  • Logical or Relational Operators
  • Comparison Operators
  • Conditional or Ternary Operators
  • Assignment Operators
  • Spaceship Operators (Introduced in PHP 7)
  • Array Operators
  • Increment/Decrement Operators
  • String Operators


Arithmetic Operator in php

Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power


Assignment Operators in php

The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.

Assignment Same as... Description
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus


Comparision Operators

The PHP comparison operators are used to compare two values (number or string):

Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.


INCREMENT / DECREMENT OPERATOR

The PHP increment operators are used to increment a variable's value. The PHP decrement operators are used to decrement a variable's value.

Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one


LOGICAL OPERATOR IN PHP

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true


STRING OPERATORS IN PHP

PHP has two operators that are specially designed for strings.

Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1


ARRAY OPERATORS IN PHP

This array oprator is used to compare arrays

Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y


CONDITIONAL ASSIGNMENT OPERATORS IN PHP

The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y


DECISION MAKING IN PHP

PHP allows us to perform actions based on some type of conditions that may be logical or comparative. Based on the result of these conditions i.e., either TRUE or FALSE, an action would be performed as asked by the user. It’s just like a two- way path. If you want something then go this way or else turn that way. To use this feature, PHP provides us with four conditional statements:

  • if statement
  • if…else statement
  • if…elseif…else statement
  • switch statement
  • if statement: this statement allows us to to set a conditional . on being TRUE , the following block of code enclosed within the if clause will be executed .
  • if (condition) {
    // if statemtent execute the code when it returns true
    }


    <?php
    $x = 12;
    
    if ($x > 0) {
    echo "The number is positive";
    }
    ?>
    




  • if... else statemtent: We understood that if a condition will hold i.e., TRUE, then the block of code within if will be executed. But what if the condition is not TRUE and we want to perform an action? This is where else comes into play. If a condition is TRUE then if block gets executed, otherwise else block gets executed
  • <?php
    $x = -12;
    
    if ($x > 0) {
    echo "The number is positive";
    }
    
    else{
    echo "The number is negative";
    }
    ?>
    




  • if…elseif…else Statement: This allows us to use multiple if…else statments. We use this when there are multiple conditions of TRUE cases.
  • <?php
    $x = "August";
    
    if ($x == "January") {
    echo "Happy Republic Day";
    }
    
    elseif ($x == "August") {
    echo "Happy Independence Day!!!";
    }
    
    else{
    echo "Nothing to show";
    }
    ?>
    




  • switch Statement: The “switch” performs in various cases i.e., it has various cases to which it matches the condition and appropriately executes a particular case block. It first evaluates an expression and then compares with the values of each case. If a case matches then the same case is executed. To use switch, we need to get familiar with two different keywords namely, break and default.

    1. The break statement is used to stop the automatic control flow into the next cases and exit from the switch case.
    2. The default statement contains the code that would execute if none of the cases match.
    <?php
    $n = "February";
    
    switch($n) {
    case "January":
    echo "Its January";
    break;
    case "February":
    echo "Its February";
    break;
    case "March":
    echo "Its March";
    break;
    case "April":
    echo "Its April";
    break;
    case "May":
    echo "Its May";
    break;
    case "June":
    echo "Its June";
    break;
    case "July":
    echo "Its July";
    break;
    case "August":
    echo "Its August";
    break;
    case "September":
    echo "Its September";
    break;
    case "October":
    echo "Its October";
    break;
    case "November":
    echo "Its November"; break; case "December":
    echo "Its December"; break; default:
    echo "Doesn't exist";
    }
    ?>
    


    Ternary Operators

    In addition to all this conditional statements, PHP provides a shorthand way of writing if…else, called Ternary Operators. The statement uses a question mark (?) and a colon (:) and takes three operands: a condition to check, a result for TRUE and a result for FALSE.

    (condition) ? if TRUE execute this : otherwise execute this;


    <?php
    $x = -12;
    
    if ($x > 0) {
    echo "The number is positive \n";
    }
    else {
    echo "The number is negative \n";
    }
    
    // This whole lot can be written in a
    // single line using ternary operator
    echo ($x > 0) ? 'The number is positive' :
    'The number is negative';
    ?>
    




How to use a switch case ‘or’ in PHP?

Problem: How to use a switch case ‘or’ in PHP?

Solution: This can be achieved in 2 ways. They are as follows:

Method 1: Without using break keyword in one of the switch case.
<?php
$option = 1;
switch ($option)
{
case 1:
case 2:
echo "The option is either 1 or 2.";
break;
}
?>


Method 2: Using or operator in switch case.

<?php
$option = 1;
switch ($option) {
case ($option == 1 || $option == 2):
echo 'The option is either 1 or 2';
break;
}
?>


LOOPS IN PHP

Often when you write code, you want the same block of code to run over and over again a certain number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.

Loops are used to execute the same block of code again and again, as long as a certain condition is true.

In PHP, we have the following loop types:

  • for loop
  • while loop
  • do-while loop
  • foreach loop

  1. for loop: This type of loops is used when the user knows in advance, how many times the block needs to execute. That is, the number of iterations is known beforehand. These type of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the initialization, the test condition and the counter.
for (initialization expression; test condition; update expression) {
// code to be executed
}


In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.

  • Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: $num = 1;
  • Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 10;
  • Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: $num += 2;
<?php

// code to illustrate for loop
for ($num = 1; $num <= 10; $num +=2) {
echo "$num \n";
}
?>




while loop: The while loop is also an entry control loop like for loops i.e., it first checks the condition at the start of the loop and if its true then it enters the loop and executes the block of statements, and goes on executing it as long as the condition holds true.

<?php

// PHP code to illustrate while loops
$num = 2;

while ($num < 12) {
$num += 2;
echo $num, "\n";
}

?>


do-while loop: This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition. Therefore, a statement is executed at least once on using the do…while loop. After executing once, the program is executed as long as the condition holds true.

<?php

// PHP code to illustrate do...while loops
$num = 2;
do {
$num += 2;
echo $num, "\n";
} while ($num < 12);

?>




FUNCTION IN PHP

A function is a block of code written in a program to perform some specific task. We can relate functions in programs to employees in a office in real life for a better understanding of how functions work. Suppose the boss wants his employee to calculate the annual budget. So how will this process complete? The employee will take information about the statics from the boss, performs calculations and calculate the budget and shows the result to his boss. Functions works in a similar manner. They take informations as parameter, executes a block of statements or perform operations on this parameters and returns the result. PHP provides us with two major types of functions:

  • Built-in functions : PHP provides us with huge collection of built-in library functions. These functions are already coded and stored in form of functions. To use those we just need to call them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so on.
  • User Defined Functions : Apart from the built-in functions, PHP allows us to create our own customised functions called the user-defined functions.
    Using this we can create our own packages of code and use it wherever necessary by simply calling it.


WHY SHOULD YOU USE THE FUNCTION IN PHP ?

  • Reusability: If we have a common code that we would like to use at various parts of a program, we can simply contain it within a function and call it whenever required. This reduces the time and effort of repetition of a single code. This can be done both within a program and also by importing the PHP file, containing the function, in some other program
  • Easier error detection: Since, our code is divided into functions, we can easily detect in which function, the error could lie and fix them fast and easily.
  • Easily maintained: As we have used functions in our program, so if anything or any line of code needs to be changed, we can easily change it inside the function and the change will be reflected everywhere, where the function is called. Hence, easy to maintain.


HOW TO CREATING FUNCTION IN PHP

While creating a user defined function we need to keep few things in mind:

  1. Any name ending with an open and closed parenthesis is a function.
  2. A function name always begins with the keyword function.
  3. To call a function we just need to write its name followed by the parenthesis
  4. A function name cannot start with a number. It can start with an alphabet or underscore.
  5. A function name is not case-sensitive.
<?php

function CODOLEARN()
{
echo "This is CODOLEARN ";
}

// Calling the function
CODOLEARN();

?>


FUNCTION PARAMETER AND ARGUMENT IN PHP

The information or variable, within the function’s parenthesis, are called parameters. These are used to hold the values executable during runtime. A user is free to take in as many parameters as he wants, separated with a comma(,) operator. These parameters are used to accept inputs during runtime. While passing the values like during a function call, they are called arguments. An argument is a value passed to a function and a parameter is used to hold those arguments. In common term, both parameter and argument mean the same. We need to keep in mind that for every parameter, we need to pass its corresponding argument.

<?php

// function along with three parameters
function CODOLEARN($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}

// Caling the function
// Passing three arguments
CODOLEARN(2, 3, 5);

?>


Setting Default Values for Function parameter in PHP

PHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call.

<?php

// function with default parameter
function CODOLEARN($str, $num=12)
{
echo "$str is $num years old \n";
}

// Caling the function
CODOLEARN("Ram", 15);

// In this call, the default value 12
// will be considered
CODOLEARN("Adam");

?>


In the above example, the parameter $num has a default value 12, if we do not pass any value for this parameter in a function call then this default value 12 will be considered. Also the parameter $str has no default value , so it is compulsory.



Returning Values from Functions in PHP

Functions can also return values to the part of program from where it is called. The return keyword is used to return value back to the part of program, from where it was called. The returning value may be of any type including the arrays and objects. The return statement also marks the end of the function and stops the execution after that and returns the value.

<?php

// function with default parameter
function CODOLEARN($str, $num=12)
{
echo "$str is $num years old \n";
}

// Caling the function
CODOLEARN("Ram", 15);

// In this call, the default value 12
// will be considered
CODOLEARN("Adam");

?>


<?php

// function along with three parameters
function CODOLEARN($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;

return $product; //returning the product
}

// storing the returned value
$retValue = CODOLEARN(2, 3, 5);
echo "The product is $retValue";

?>


PARAMETER PASSING TO FUNCTION

PHP allows us two ways in which an argument can be passed into a function:

  • Pass by Value: On passing arguments using pass by value, the value of the argument gets changed within a function, but the original value outside the function remains unchanged. That means a duplicate of the original value is passed as an argument.
  • Pass by Reference: On passing arguments as pass by reference, the original value is passed. Therefore, the original value gets altered. In pass by reference we actually pass the address of the value, where it is stored using ampersand sign(&).
<?php

// pass by value
function codolearn($num) {
$num += 2;
return $num;
}

// pass by reference
function codo(&$num) {
$num += 10;
return $num;
}

$n = 10;

codolearn($n);
echo "The original value is still $n \n";

codo($n);
echo "The original value changes to $n";

?>


ARRAYS | PHP

Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. Suppose we want to store five names and print them accordingly. This can be easily done by the use of five different string variables. But if instead of five, the number rises to a hundred, then it would be really difficult for the user or developer to create so many different variables. Here array comes into play and helps us to store every element within a single variable and also allows easy access using an index or a key. An array is created using an array() function in PHP.

There are only three types of arrays in PHP:

  • Indexed or Numeric Arrays: An array with a numeric index where values are stored linearly.
  • Associative Arrays: An array with a string index where instead of linear storage, each value can be assigned a specific key.
  • Multidimensional Arrays: An array which contains single or multiple array within it and can be accessed via multiple indices.


Indexed or Numeric Arrays

These type of arrays can be used to store any type of elements, but an index is always a number. By default, the index starts at zero. These arrays can be created in two different ways as shown in the following example:

<?php

// One way to create an indexed array
$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");

// Accessing the elements directly
echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";

// Second way to create an indexed array
$name_two[0] = "ZACK";
$name_two[1] = "ANTHONY";
$name_two[2] = "RAM";
$name_two[3] = "SALIM";
$name_two[4] = "RAGHAV";

// Accessing the elements directly
echo "Accessing the 2nd array elements directly:\n";
echo $name_two[2], "\n";
echo $name_two[0], "\n";
echo $name_two[4], "\n";
?>


ASSOCIATIVE ARRAYS

These types of arrays are similar to the indexed arrays but instead of linear storage, every value can be assigned with a user-defined key of string type.

<?php

// One way to create an associative array
$name_one = array("Zack"=>"Zara", "Anthony"=>"Any", "Ram"=>"Rani", "Salim"=>"Sara",
"Raghav"=>"Ravina");
// Second way to create an associative array
$name_two["zack"] = "zara";
$name_two["anthony"] = "any";
$name_two["ram"] = "rani";
$name_two["salim"] = "sara";
$name_two["raghav"] = "ravina";

// Accessing the elements directly
echo "Accessing the elements directly:\n";
echo $name_two["zack"], "\n";
echo $name_two["salim"], "\n";
echo $name_two["anthony"], "\n";
echo $name_one["Ram"], "\n";
echo $name_one["Raghav"], "\n";

?>


MULTIDIMENSIONAL Multidimensional ARRAYS

Multi-dimensional arrays are such arrays that store another array at each index instead of a single element. In other words, we can define multi-dimensional arrays as an array of arrays. As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions.

<?php

// Defining a multidimensional array
$favorites = array(
array(
"name" => "Dave Punk",
"mob" => "5689741523",
"email" => "codolearner@gmail.com",
),
array(
"name" => "Monty Smith",
"mob" => "2584369721",
"email" => "codolearner@gmail.com",
),
array( "name" => "John Flinch",
"mob" => "9875147536",
"email" => "codolearner@gmail.com",
)
);

// Accessing elements
echo "Dave Punk email-id is: " . $favorites[0]["email"], "\n";
echo "John Flinch mobile number is: " . $favorites[2]["mob"];

?>


FORM IN PHP


FORM HANDLING IN PHP

SIMPLE HTML FORM EXAMPLE

<html>
<body>
<form action="userinfo.php" method="post">
Name: <input type="text" name="name">
<br>
E-mail: <input type="text" name="email">
<br>
<input type="submit">
</form>
</body>
</html>


When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?>
<br>
Your email address is:
<?php echo $_POST["email"]; ?>
</body>
</html>


GET VS POST METHOD IN PHP

Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

$_POST is an array of variables passed to the current script via the HTTP POST method.



WHEN TO USE GET ?

Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.

Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.



FORM VALIDATION IN PHP

The HTML form we will be working at in these chapters, contains various input fields: required and optional text fields, radio buttons, and a submit button:

before using this you have follow some rules are shown below .

Field Validation Rules
Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one


Text Fields

The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks like this:

Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40">
</textarea>


Radio Buttons

age:
<input type="radio" name="age" value="30">30
<input type="radio" name="age" value="55">55
<input type="radio" name="age" value="21">21


FORM ELEMENT

<form method="post" action="">


What is the $_SERVER["PHP_SELF"] variable?
The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script.

So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error messages on the same page as the form.

What is the htmlspecialchars() function?

The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and> with < and >. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.


Big Note on PHP Form Security

The $_SERVER["PHP_SELF"] variable can be used by hackers!
If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.


Assume we have the following form in a page named "codolearn.php":

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">


Now, if a user enters the normal URL in the address bar like "http://www.example.com/codolearn.php", the above code will be translated to:

<form method="post" action="codolearn.php">


So far, so good.
However, consider that a user enters the following URL in the address bar:

http://www.example.com/codolearn.php/%22%3E%3Cscript%3Ealert('not available)%3C/script%3E


In this case, the above code will be translated to:

<form method="post" action="codolearn.php/"><script>alert('not available)</script>


This code adds a script tag and an alert command. And when the page loads, the JavaScript code will be executed (the user will see an alert box). This is just a simple and harmless example how the PHP_SELF variable can be exploited.

Be aware of that any JavaScript code can be added inside the <script> tag! A hacker can redirect the user to a file on another server, and that file can hold malicious code that can alter the global variables or submit the form to another address to save the user data, for example.

How To Avoid $_SERVER["PHP_SELF"] Exploits?

$_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function.
The form code should look like this:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">


The htmlspecialchars() function converts special characters to HTML entities. Now if the user tries to exploit the PHP_SELF variable, it will result in the following output:

<form method="post" action="test_form.php/"><script>alert('not available)</script>">


HOW TO VALIDATE FORM DATA IN PHP

The first thing we will do is to pass all variables through PHP's htmlspecialchars() function. When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field:

<script>location.href('http://www.notavaialiable.com')</script>
- this would not be executed, because it would be saved as HTML escaped code, like this:

<script>location.href('http://www.notavaialiable.com')</script>
The code is now safe to be displayed on a page or inside an e-mail. We will also do two more things when the user submits the form:

1. Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes() function)

The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again). We will name the function test_input(). Now, we can check each $_POST variable with the test_input() function, and the script looks like this:

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) { $data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>


Notice that at the start of the script, we check whether the form has been submitted using $_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has been submitted - and it should be validated. If it has not been submitted, skip the validation and display a blank form. However, in the example above, all input fields are optional. The script works fine even if the user does not enter any data. The next step is to make input fields required and create error messages if needed.



HERE IS THE BASIC OF FORM VALIDATION JUST BELOW THIS



<?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 using 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>";
}
}
?>
FirstName: <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>

REQUIRED FIELD IN FORM IN PHP

From the validation rules table on the previous page, we see that the "Name", "E-mail", and "Gender" fields are required. These fields cannot be empty and must be filled out in the HTML form.

Field Validation Rules
Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one

In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These error variables will hold error messages for the required fields. We have also added an if else statement for each $_POST variable. This checks if the $_POST variable is empty (with the PHP empty() function). If it is empty, an error message is stored in the different error variables, and if it is not empty, it sends the user input data through the test_input() function:

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>


HOW TO DISPLAY THE ERROR MESSAGE IN PHP

Then in the HTML form, we add a little script after each required field, which generates the correct error message if needed (that is if the user tries to submit the form without filling out the required fields):

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">
* <?php echo $nameErr;?>
</span>
<br>
<br>
E-mail: <input type="text" name="email">
<span class="error">
* <?php echo $emailErr;?>
</span>
<br>
<br>
Website: <input type="text" name="website">
<span class="error">
<?php echo $websiteErr;?>
</span>
<br>
<br>
Comment: <textarea name="comment" rows="5" cols="40">
</textarea>
<br>
<br>
Gender: <input type="radio" name="gender" value="female">
Female <input type="radio" name="gender" value="male">
Male <input type="radio" name="gender" value="other">
Other <span class="error">
* <?php echo $genderErr;?>
</span>
<br>
<br>
<input type="submit" name="submit" value="Submit">
</form>


HOW TO VALIDATE E-MAIL AND URL USING PHP



VALIDATE NAME IN PHP

This code below shows a simple way to check if the name field only contains letters, dashes, apostrophes and whitespaces. If the value of the name field is not valid, then store an error message:

$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}


VALIDATE EMAIL USING PHP

The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function. In the code below, if the e-mail address is not well-formed, then store an error message:

$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}


VALIDATE URL USING PHP

The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message:

$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}


HOW TO VALIDATE NAME , E-MAIL AND URL AT SAME TIME

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>


COMPLETE FORM EXAMPLE IN PHP



To show the values in the input fields after the user hits the submit button, we add a little PHP script inside the value attribute of the following input fields: name, email, and website. In the comment textarea field, we put the script between the <textarea> and </textarea> tags. The little script outputs the value of the $name, $email, $website, and $comment variables.

Then, we also need to show which radio button that was checked. For this, we must manipulate the checked attribute (not the value attribute for radio buttons):

<?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 using 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>";
}
}
?>
FirstName: <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>



PHP ADVANCED

date() Function in PHP

The PHP date() function formats a timestamp to a more readable date and time.

Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time

HOW TO GET A DATE

The required format parameter of the date() function specifies how to format the date (or time). Here are some characters that are commonly used for dates:

1. d - Represents the day of the month (01 to 31)
2. m - Represents a month (01 to 12)
3. Y - Represents a year (in four digits)
4. l (lowercase 'L') - Represents the day of the week

Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional formatting. The example below formats today's date in three different ways:
<?php
echo "Today is " . date("Y/m/d") . "
"; echo "Today is " . date("Y.m.d") . "
"; echo "Today is " . date("Y-m-d") . "
"; echo "Today is " . date("l"); ?>


AUTOMATIC COPYWRITE YEAR IN PHP

Use the date() function to automatically update the copyright year on your website:

&copy; 2021-<?php echo date("Y");?>


HOW TO GET A TIME IN PHP

Here are some characters that are commonly used for times:

1. H - 24-hour format of an hour (00 to 23)
2. h - 12-hour format of an hour with leading zeros (01 to 12)
3. i - Minutes with leading zeros (00 to 59)
4. s - Seconds with leading zeros (00 to 59)
5. a - Lowercase Ante meridiem and Post meridiem (am or pm)

The example below outputs the current time in the specified format:

<?php
echo "The time is " . date("h:i:sa");
?>


HOW TO GET OUR TIME ZONE

If the time you got back from the code is not correct, it's probably because your server is in another country or set up for a different timezone. So, if you need the time to be correct according to a specific location, you can set the timezone you want to use. The example below sets the timezone to "America/New_York", then outputs the current time in the specified format:

<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>


HOW TO CREATE A DATE WITH mktime()

The optional timestamp parameter in the date() function specifies a timestamp. If omitted, the current date and time will be used (as in the examples above).

The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.



HOW TO CREATE A DATE FROM A STRING WITH STRTOTIME() IN PHP

The PHP strtotime() function is used to convert a human readable date string into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>


<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>


INCLUDE AND REQUIRED METHOD IN PHP

As we know PHP allows us to create various functions and various elements that are used multiple times in multiple pages. Scripting the same function in multiple pages is a task of great effort and would consume time. This can be avoided if we follow and use the concept of file inclusion which helps us to include various files including text or codes into a single program which saves the effort of writing the full function or code multiple times. This also provides another advantage. If we want to change any code then instead of editing it in all the files, we just need to edit the source file and all codes will be automatically changed. There are two functions which help us to include files:

  • INCLUDE() FUNCTION
  • REQUIRE() FUNCTION


THE IN INCLUDE() FUNCTION

This function is used to copy all the contents of a file called within the function, text wise into a file from which it is called. This happens before the server exceutes the code. Example:

Lets have a file called codolearn.php with the following code:

<?php
// file to be included
echo "Hello codolearner"
?>


after creating this file you have again create a another file with the name index.php and write these code just below this

<?php
include("codolearn.php");
echo "
Above File is Included" ?>


THE REQUIRE FUNCTION

The require() function performs same as the include() function. It also takes the file that is required and copies the whole code into the file from where the require() function is called. There is a single difference between the include() and require() function which we will see following this example: Lets have a file called codolearn.php with the following code:

<?php
// file to be included
echo "Hello codolearn"
?>


then you have to create a another file with the name index.php

<?php
require("codolearn.php");
echo "
Above File is Required" ?>


FILE HANDLING IN PHP

File handling is needed for any application. For some tasks to be done file needs to be processed. File handling in PHP is similar as file handling is done by using any programming language like C. PHP has many functions to work with normal files. Those functions are:


  • fopen() – PHP fopen() function is used to open a file. First parameter of fopen() contains name of the file which is to be opened and second parameter tells about mode in which file needs to be opened, e.g.,
  • <?php
    $file = fopen(codolearn.txt”,'w');
    ?>


    • "w" – Opens a file for write only. If file not exist then new file is created and if file already exists then contents of file is erased.
    • "r" – File is opened for read only.
    • "a" – File is opened for write only. File pointer points to end of file. Existing data in file is preserved.
    • "w+" – Opens file for read and write. If file not exist then new file is created and if file already exists then contents of file is erased.
    • "r+" – File is opened for read/write.
    • "a+" – File is opened for write/read. File pointer points to end of file. Existing data in file is preserved. If file is not there then new file is created.
    • "x" – New file is created for write only.

  • fread() –– After file is opened using fopen() the contents of data are read using fread(). It takes two arguments. One is file pointer and another is file size in bytes, e.g.,
  • <?php
    $filename = "codolearn.txt";
    $file = fopen( $filename, 'r' );
    $size = filesize( $filename );
    $filedata = fread( $file, $size );
    ?>
    


  • fwrite() – New file can be created or text can be appended to an existing file using fwrite() function. Arguments for fwrite() function are file pointer and text that is to written to file. It can contain optional third argument where length of text to written is specified, e.g.,
  • <?php
    $file = fopen("codolearn.txt", 'w');
    $text = "Hello world\n";
    fwrite($file, $text);
    ?>


  • fclose() – file is closed using fclose() function. Its argument is file which needs to be closed, e.g.,
  • <?php
    $file = fopen("demo.txt", 'r');
    //some code to be executed
    fclose($file);
    ?>
    




FILE UPLOADING FILE IN PHP

Have you ever wondered how websites build their system of file uploading in PHP? Here we will come to know about the file uploading process. A question which you can come up with – ‘Are we able to upload any kind of file with this system?’. The answer is yes, we can upload files with different types of extensions. Let’s make an HTML form for uploading the file to the server.

<?php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
File Upload Form</title>
</head>
<body>
<form action="file-upload-manager.php" method="post" enctype="multipart/form-data">
<!--multipart/form-data ensures that form data is going to be encoded as MIME data-->
<h2>
Upload File</h2>
<label for="fileSelect">
Filename:</label>
<input type="file" name="photo" id="fileSelect">
<input type="submit" name="submit" value="Upload">
<!-- name of the input fields are going to be used in our php script-->
<p>
<strong>
Note:</strong>
Only .jpg, .jpeg, .png formats allowed to a max size of 2MB.</p>
</form>
</body>
</html>


Now you have to create a upload.php file and write :

<?php

// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0)
{
$allowed_ext = array("jpg" => "image/jpg",
"jpeg" => "image/jpeg",
"gif" => "image/gif",
"png" => "image/png");
$file_name = $_FILES["photo"]["name"];
$file_type = $_FILES["photo"]["type"];
$file_size = $_FILES["photo"]["size"];

// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);

if (!array_key_exists($ext, $allowed_ext))
die("Error: Please select a valid file format.");

// Verify file size - 2MB max
$maxsize = 2 * 1024 * 1024;

if ($file_size > $maxsize)
die("Error: File size is larger than the allowed limit.");

// Verify MYME type of the file
if (in_array($file_type, $allowed_ext))
{
// Check whether file exists before uploading it
if (file_exists("upload/".$_FILES["photo"]["name"]))
echo $_FILES["photo"]["name"]." is already exists.";

else
{
move_uploaded_file($_FILES["photo"]["tmp_name"],
"uploads/".$_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
}
else
{
echo "Error: Please try again.";
}
}
else
{
echo "Error: ". $_FILES["photo"]["error"];
}
}
?>



NOW WE WILL LEARN ABOUT OPP IN PHP

OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it.


CLASSES AND OBJECTS IN PHP

OOP Case om php

Let's assume we have a class named Fruit. A Fruit can have properties like name, color, weight, etc. We can define variables like $name, $color, and $weight to hold the values of these properties. When the individual objects (apple, banana, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

HOW TO DIFINE CLASS IN PHP

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces:

<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>


HOW TO DIFINE OBJECT IN PHP

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values. Objects of a class is created using the new keyword. In the example below, $apple and $banana are instances of the class Fruit:

<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "
"; echo $banana->get_name(); ?>


WHAT IS $this KEYWORD IN PHP

The $this keyword refers to the current object, and is only available inside methods. Look at the following example:

<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>


So, where can we change the value of the $name property? There are two ways: 1. Inside the class (by adding a set_name() method and use $this):

<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>


2. Outside the class (by directly changing the property value):

<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
?>


WHAT IS instanceof IN PHP

You can use the instanceof keyword to check if an object belongs to a specific class:

<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>



CONSTRUCTOR AND DESTRUCTOR IN PHP

Constructors are special member functions for initial settings of newly created object instances from a class, which is the key part of the object-oriented concept in PHP5. Constructors are the very basic building blocks that define the future object and its nature. You can say that the Constructors are the blueprints for object creation providing values for member functions and member variables. Once the object is initialized, the constructor is automatically called. Destructors are for destroying objects and automatically called at the end of execution. In this article, we are going to learn about object-oriented concepts of constructors and destructors. Both are special member functions of any class with different concepts but the same name except destructors are preceded by a ~ Tilda operator.

<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
?>


WHAT IS instanceof IN PHP

You can use the instanceof keyword to check if an object belongs to a specific class:

<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit("Apple");
echo $apple->get_name();
?>


DESTRUCTOR IN PHP

A destructor is called when the object is destructed or the script is stopped or exited.
If you create a __destruct() function, PHP will automatically call this function at the end of the script.
Notice that the destruct function starts with two underscores (__)!
The example below has a __construct() function that is automatically called when you create an object from a class, and a __destruct() function that is automatically called at the end of the script:

<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}

$apple = new Fruit("Apple");
?>



INHERTANCE IN OOP IN PHP

Inheritance in OOP = When a class derives from another class.
The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods.
An inherited class is defined by using the extends keyword.
Let's look at an example:

<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>



EXAMPLE EXPLAINED

The Strawberry class is inherited from the Fruit class.
This means that the Strawberry class can use the public $name and $color properties as well as the public __construct() and intro() methods from the Fruit class because of inheritance.
The Strawberry class also has its own method: message().



PHP - Inheritance and the Protected Access Modifier

In the previous chapter we learned that protected properties or methods can be accessed within the class and by classes derived from that class. What does that mean?
Let's look at an example:

<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}

// Try to call all three methods from outside class
$strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public
$strawberry->message(); // OK. message() is public
$strawberry->intro(); // ERROR. intro() is protected
?>


PHP - Overriding Inherited Methods

Inherited methods can be overridden by redefining the methods (use the same name) in the child class.
Look at the example below. The __construct() and intro() methods in the child class (Strawberry) will override the __construct() and intro() methods in the parent class (Fruit):

<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

class Strawberry extends Fruit {
public $weight;
public function __construct($name, $color, $weight) {
$this->name = $name;
$this->color = $color;
$this->weight = $weight;
}
public function intro() {
echo "The fruit is {$this->name}, the color is {$this->color}, and the weight is {$this->weight} gram.";
}
}

$strawberry = new Strawberry("Strawberry", "red", 50);
$strawberry->intro();
?>



CONSTANT IN PHP

Constants cannot be changed once it is declared.
Class constants can be useful if you need to define some constant data within a class.
A class constant is declared inside a class with the const keyword.
Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.
We can access a constant from outside the class by using the class name followed by the scope resolution operator (::) followed by the constant name, like here:

<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting CODOLEARN!";
}

echo Goodbye::LEAVING_MESSAGE;
?>


Or, we can access a constant from inside the class by using the self keyword followed by the scope resolution operator (::) followed by the constant name, like here:

<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting CODOLEARN!";
public function byebye() {
echo self::LEAVING_MESSAGE;
}
}

$goodbye = new Goodbye();
$goodbye->byebye();
?>


WHAT ARE ABSTRACT CLASSES AND METHOD IN PHP ?

Abstract classes and methods are when the parent class has a named method, but need its child class(es) to fill out the tasks. An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code. An abstract class or method is defined with the abstract keyword:

<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3() : string;
}
?>


When inheriting from an abstract class, the child class method must be defined with the same name, and the same or a less restricted access modifier. So, if the abstract method is defined as protected, the child class method must be defined as either protected or public, but not private. Also, the type and number of required arguments must be the same. However, the child classes may have optional arguments in addition.

So, when a child class is inherited from an abstract class, we have the following rules:

  • The child class method must be defined with the same name and it redeclares the parent abstract method
  • The child class method must be defined with the same or a less restricted access modifier
  • The number of required arguments must be the same. However, the child class may have optional arguments in addition
<?php
// Parent class
abstract class Car {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function intro() : string;
}

// Child classes
class Audi extends Car {
public function intro() : string {
return "Choose German quality! I'm an $this->name!";
}
}

class Volvo extends Car {
public function intro() : string {
return "Proud to be Swedish! I'm a $this->name!";
}
}

class Citroen extends Car {
public function intro() : string {
return "French extravagance! I'm a $this->name!";
}
}

// Create objects from the child classes
$audi = new audi("Audi");
echo $audi->intro();
echo "
"; $volvo = new volvo("Volvo"); echo $volvo->intro(); echo "<br>";

$citroen = new citroen("Citroen");
echo $citroen->intro();
?>


EXAMPLE EXPLAINED

The Audi, Volvo, and Citroen classes are inherited from the Car class. This means that the Audi, Volvo, and Citroen classes can use the public $name property as well as the public __construct() method from the Car class because of inheritance. But, intro() is an abstract method that should be defined in all the child classes and they should return a string.



INTERFACES IN PHP

An Interface allows the users to create programs, specifying the public methods that a class must implement, without involving the complexities and details of how the particular methods are implemented. It is generally referred to as the next level of abstraction. It resembles the abstract methods, resembling the abstract classes. An Interface is defined just like a class is defined but with the class keyword replaced by the interface keyword and just the function prototypes. The interface contains no data variables. The interface is helpful in a way that it ensures to maintain a sort of metadata for all the methods a programmer wishes to work on.

HOW TO CREATE A INTERFACES IN PHP

Following is an example of how to define an interface using the interface keyword.

<?php

interface MyInterfaceName {
public function methodA();
public function methodB();
}

?>


Few characteristics of an Interface are:

  • An interface consists of methods that have no implementations, which means the interface methods are abstract methods.
  • All the methods in interfaces must have public visibility scope.
  • Interfaces are different from classes as the class can inherit from one class only whereas the class can implement one or more interfaces.

To implement an interface, use the implements operator as follows:

<?php

class MyClassName implements MyInterfaceName{
public function methodA() {

// method A implementation
}
public function methodB(){

// method B implementation
}
}

?>


Concrete Class: The class which implements an interface is called the Concrete Class. It must implement all the methods defined in an interface. Interfaces of the same name can’t be implemented because of ambiguity error. Just like any class, an interface can be extended using the extends operator as follows:

<?php

interface MyInterfaceName1{

public function methodA();

}

interface MyInterfaceName2 extends MyInterfaceName1{

public function methodB();
}

?>


ADVANTAGES OF INTERFACES IN PHP

  • An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy.
  • An interface can model multiple inheritances because a class can implement more than one interface whereas it can extend only one class.
  • The implementation of an inheritance will save the caller from full implementation of object methods and focus on just he objects interface, therefore, the caller interface remains unaffected.

STATIC FUNCTION IN PHP

In certain cases, it is very handy to access methods and properties in terms of a class rather than an object. This can be done with the help of static keyword. Any method declared as static is accessible without the creation of an object. Static functions are associated with the class, not an instance of the class. They are permitted to access only static methods and static variables. To add a static method to the class, static keyword is used.

<?php
/* Use static function as a counter */

class solution {

static $count;

public static function getCount() {
return self::$count++;
}
}

solution::$count = 1;

for($i = 0; $i < 5; ++$i) {
echo 'The next value is: '.
solution::getCount() . "\n";
}
?>


WHEN TO DIFINE STATIC METHOD IN PHP

The static keyword is used in the context of variables and methods that are common to all the objects of the class. Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method. PHP static methods are most typically used in classes containing static methods only often called utility classes of PHP frameworks like Laravel and CakePHP.

Below is the PHP code which shows the use of static methods.

Example: This example illustrates the static method in PHP.

<?php
/* Use of static method in PHP */

class A {

public function test($var = "Hello World") {
$this->var = $var;
return $this->var;
}
}

class B {
public static function test($var) {
$var = "This is static";
return $var;
}
}

// Creating Object of class A
$obj = new A();

echo $obj->test('This is non-static');
echo "\n";
echo B::test('This is non-static');

?>



© 2021 Created By "KARTIK A DIGITAL INFLUENCER" || All Rights Reserved