Introduction of PHP

 

Unit - I

Introduction to PHP

1.1 Introduction to PHP, History, and Features of PHP
1.2 Installation & Configuration of PHP
1.3 Embedding PHP Code in Your Web Pages
1.4 Understanding PHP, HTML, and White Space. Writing Comments in PHP
1.5 Sending Data to the Web Browser
1.6 Data Types in PHP, Keywords in PHP
1.7 Using Variables and Constants in PHP
1.8 Expressions in PHP
1.9 Operators in PHP

 1.1 Introduction to PHP, History, and Features of PHP

PHP: Hypertext Pre-processor, it is an open-source, server-side scripting language for web development. It is also called a personal home page. The great feature of embedding code into HTML makes it a more powerful tool, as it supports the creation of dynamic and interactive web pages. PHP handles data processing and interacts with databases like MySQL. 

History

Version

Year

Creator

Description

PHP

1994

Rasmus Lerdorf

It is released as the Personal Home Page Tools

PHP/FI

1997

Rasmus Lerdorf

extended  to include a package Form Interpreter

PHP3

1998

Zeev Suraski and Andi Gutmans

Include a Zend engine feature

PHP 4

2000

Zeev Suraski and Andi Gutmans

Improved performance, scalability, and features.

PHP 5

2004

Zeev Suraski and Andi Gutmans

Use object-oriented programming features.

PHP 7

2015

Dmitry Stogov, Xinchen Hui and Nikita Popov

Introduce new features like scalar type declarations.

PHP 8

2020

Nikita Popov

Introduced JIT compilation, arguments, attributes

PHP 8.4

2024

Nikita Popov

Included property hooks, asymmetric visibility, an updated DOM API, performance improvements, bug fixes, and general cleanup.


Features of PHP

Open Source:

PHP is an open-source language. open-source language means it’s completely free. No payment is required for the users.

Benefits:

  • User can download PHP freely and use it for their applications or projects.
  • Provide free source code for users to modify and distribute. 
  • It has contributed to its widespread adoption and popularity in the web development community. 

Server-side scripting:

PHP is a server-side scripting language. Server-side scripting is the execution of web page scripts on a web server, then forwarded to the client web browser.

Benefits:

  • Before sending it to the client's web browser, it generates dynamic content.
  • Customized web pages according to user input or other data.
  • Server-side scripting provides security for authentication. It also supports access to databases,  among other things.
  • Server-side scripting helps developers with form submission and session management for users across multiple requests.                             

Dynamic content generation:

PHP generates dynamic content in HTML templates by embedding PHP code within HTML files. Developers can create dynamic web pages based on various conditions and user inputs.

Benefits:

  • HTML Integration makes it relatively easy to integrate dynamic elements into existing web pages.

Cross-Platform development:

Cross-Platform development means running your script on any operating system and server software, like Windows, Linux,  macOS, and Unix.

Benefits:

  • web application deployed anywhere,
  • It is accessible to a global audience regardless of their platform

Database Connectivity:

PHP supports various database systems, like MySQL, PostgreSQL, and Oracle, making it easy to interact with and manage data.

Benefits:

  • Store data, 
  • execute data, 
  • retrieve data by SQL queries, and
  • perform CRUD operations.

Loosely Typed Language:

Loosely typed language means you don't need an explicit declaration of the data type of a variable. It is determined by the value assigned to it at runtime.

 Benefits:

  •  Automatically associates a data type with the variable.

1.3     Embedding PHP Code in Your Web Pages

PHP code is written in HTML code, which is called Embedding PHP code in HTML.

Embedded HTML and PHP code run in a normal browser because the source of the raw PHP code is not visible in the browser. Because the PHP interpreter runs in script mode. It will display the output as expected from the script results.

Structure of PHP

<?PHP
//Block of code;
….;
?>

The structure of a PHP script is, 

PHP code blocks are embedded within HTML. Which is enclosed in special tags that are greater than operator and question mark with PHP keyword “<?php “ ……, and end with question mark and less than symbol “?>”.

Each PHP sentence ends with a semicolon  ”;”.

Keywords are not case sensitive, but variables are.

                ECHO “hello”;
                EcHo “hello”;
                Echo “hello”;
                All have the same result.

  • The PHP codes have to be followed by the C, Java, and Perl script languages.
  • PHP uses single-line as well as multiple-line comments with a pair of forward slashes “//” and
  • a hashtag “#” for single-line comments.
  • PHP supports loosely coupled data, so there is no need to declare variables explicitly. 
  • The dollar sign symbol “$” with a variable name recognizes which kind of data is stored, according to the stored data value. PHP is a loosely typed language,
  • So it supports dynamic variable declaration. 

For example,
         <html>
        <head>
        <title>First Application of PHP</title></head>
        <body>
        <h3>Welcome to HTML</h3>
        <?php
        echo "Welcome to PHP";
        ?>
        </body>
        </html>
        Output:
        Welcome to HTML
        Welcome to PHP

1.4    White Space

In PHP, whitespace plays a crucial role in how code is structured and perceived.
Whitespace refers to the character spacing in code, including spaces, tabs, and newlines, considered white space. To improve code readability and functionality, we use white space in our code. PHP handles whitespace in various ways, but it generally serves the purpose of separating tokens (like keywords, variables, etc.) and structuring code blocks. 
            HTML ignores extra whitespace (spaces, tabs, newlines) between words. It executes only tag restrictions and allows developers to format code for readability without affecting the code's execution.
For example,
<html>
<head><title>my page</title></head>
<body>
<h3> Welcome          to          PHP</h3>
</body>
</html>

OUT-PUT
Welcome to PHP

Description:
According to this program, our output must be displayed with a space, but it doesn’t, because HTML ignores these white spaces.
    When you write the same code with PHP, the PHP view source displays the space between words.
<html>
<head><title>my page</title></head>
<body>
<h3>
<?php
Echo ”Welcome          to          PHP”;
?></h3>
</body>
</html>
 OUT-PUT In view source
Welcome             to            PHP

PHP handles the whitespace issue using some built-in string functions.
For example,
Ltrim(): The ltrim function removes the left space from the given character set.

For example,
<html>
<head><title>my page</title></head>
<body>
<h3>
<?php
$ch=”    hello      ”;
Echo ltrim;
?></h3>
</body>
</html>
 OUT-PUT In view source
Hello

Rtrim(): The Rtrim function removes the right space from the given character set.

For example,
<html>
<head><title>my page</title></head>
<body>
<h3>
<?php
$ch=”    hello      ”;
Echo ltrim;
?></h3>
</body>
</html>
 OUT-PUT In view source
          hello

trim(): The trim function removes the left and right spaces from the given character set.
For example,
<html>
<head><title>my page</title></head>
<body>
<h3>
<?php
$ch=”    hello      ”;
Echo ltrim;
?></h3>
</body>
</html>
 OUT-PUT In view source
hello

Writing Comments in PHP

A comment line in PHP is a section of text within the source code that is ignored by the compiler during compilation. Commented line provides human-readable explanations, notes, or documentation about the code, making it easier for programmers to understand and maintain.

 PHP provides a single-line comment and a multi-line comment.

Single line comment:

PHP provides two ways to produce a single-line comment.

1.   Pair of forward slashes use “//” for single-line comment.

2.   Hashtag also uses “#” for a single-line comment.

     <html>
    <head><title>my page</title></head>
    <body>
    <h3>
    <?php
    // This is a single comment line.
    # This is a single comment line.
    Echo “Welcome to PHP”;
    ?></h3>
    </body>
    </html>
     OUT-PUT
    Welcome to PHP

Multi-line comment: 

When programmers want to comment more than one line at a time in their program, they use a multiline comment.

Multi-line comments start with the “/*and end with “*/”.

    <html>
    <head><title>my page</title></head>
    <body>
    <h3>
    <?php
    /* This is a multiline comment.
    More than one lines are commented */
    Echo “Welcome to PHP”;
    ?></h3>
    </body>
    </html>
     OUT-PUT
    Welcome to PHP

1.5    Sending Data to the Web Browser:

PHP creates a dynamic website; in this process, it needs to send data to the Web Browser. PHP uses the echo and print built-in functions to send data to the Web Browser.

Echo: In PHP, the echo is the most common function used to output data. Echo is preferred due to its slightly better performance and ability to handle multiple arguments. Echo is a language construct. It is used with or without parentheses. It is generally faster than print, even though it handles more than one argument (separated by commas) and does not return any value. so it contributes to its slight performance advantage in some cases. 

For example:

<?php
$ch1 = ” Hello ”;
$ch2 = ” word”
Echo $ch1, $ch2;
?>
 OUT-PUT
Hello word

Print:

Another common function used in PHP is the print() function. It is used with or without parentheses. It is used as a language construct. Print accepts only one argument and always returns the integer value 1. Print is used in expressions.

For example;

Print “hello”,” word”; // This is invalid.

Echo “hello”,” word”; // This is valid. Display hello word

$ch1 = print "Hello"; // This is valid and returns 1. (used in expressions.)

Explanation: Here, $ch holds the print "Hello". When you display $ch it will display 1. So, the Print function can be used as an expression, but echo can’t, because it will display an error.

$ch1 = echo "Hello"; // This is invalid.

<?php

$ch1 = ” Hello ”;

print $ch1;

?>

 OUT-PUT

Hello 

1.6    Data Types in PHP

A data type is a type of data that is stored by a variable, and a variable is a memory allocation for holding this data, for example: $a1=”hello”;.

Data types not only make Code reliable and efficient but also manage memory.

 PHP has a most important characteristic, like a loosely typed language, which means an explicit declaration of the data type of a variable. It is determined by the value assigned to it at runtime.

          In PHP, let's classify its several data types into three types. Like

·     Scalar Types
·     Compound Types
·     Special Types

Scalar Types:

In this scalar type, PHP has four main data types that hold a single value, like Integer, float, string, and Boolean.

Integer:

An Integer holds a Whole number, without a decimal point between -2,147,483,648 and 2,147,483,647. It can be positive or negative. It has a three-format

Decimal integer- Its base is 10, so the values will be 0 to 9, for example: $a=11;

Hexadecimal- Its base is 16, so the values will be 0 to 9 and A to F alphabet and prefixed with '0x' or '0X'. For example: $a=OX1a;

Octal- Its base is 8, so the values will be 0 to 7. For example: $a=27;

Float:

Float holds a decimal point or exponential form value, For example: $a=2.7;

String:

The string data type can store a set of characters that must be enclosed in single or double quotes. For example: $a=”hello”;

Boolean:
In PHP, Boolean represents a value of true or false, which is represented by 1 and 0. For example $a=true;

Compound Types:

In this type of PHP, store a collection of values, like an array or an object.

Array:

An array is a set of values. In PHP, it is divided into two sections: indexed array and associative array.

Indexed array: An Indexed array stores its elements by numeric key, and its index starts from 0.

 For example:  $a= [“red”, ”green”, ”blue”];

Echo $a [0]; // OUTPUT: red.

Associative array:

 An associative array stores its elements by numeric key or string format,

for example:  $a= [1=>“red”, 2=> ”green”, 3=>”blue”];

Or $a= [“c1”=>“red”, “c2”=> ”green”,”c3”=>”blue”];

Echo $a [c1]; // OUTPUT: red.

Object:

An object is a run-time entity; it is an instance of a class.

Special Types:

Special types can be determined at runtime. A feature of PHP is a dynamically-typed programming language. These data types are,

  • NULL Type: A variable that has no value or has been explicitly set to NULL, for example: $a=NULL;
  • Resource type: It is represented as an external resource that is managed by PHP.
  • Callable type: It is used to represent functions or methods.

1.7    Using Variables and Constants in PHP:

A PHP variable is a memory allocation of stored data. PHP supports loosely coupled data, so there is no need to declare variables explicitly. The dollar sign symbol “$” with a variable name recognizes which kind of data is stored, according to the stored data value.

  • Whenever we declare any variable, we have to follow the following rule.
  • In PHP, write your variable name with the $ sign, then mention the name of the variable, for example $a=” hello”;
  • The name of a variable should start with a letter or the underscore character, with a numerical start not allowed
  • A variable name can contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive.

      Example

<html>

<body>

 <?php

 $str = "Hello Worlddd!";

$x = 5;

var_dump($x);

var_dump($str);

?>

</body>

</html>

OUTPUT

C:\wamp64\www\pp\p1.php:10:int 5

C:\wamp64\www\pp\p1.php:12:string 'Hello Worlddd!' (length=14)

Constants in PHP:

A fixed value of a variable is called a constant variable. It might be int, float, or string. Constant variables do not change their value during execution. For example, in mathematical processes, the pi value is fixed; it does not change. Or in bank-related software, keep their rent value fixed.

Syntax:

Const var-name;

define("var-name", value);

Example:

Const var= 3;

define("var1", 50);           //integer constant

define("var2", 5.5);           //float constant

define("var3", “hello”);    //string constant

Description:

Create a constant with the “const” keyword:

  • Unlike other variable declarations in PHP, a constant variable does not require the $ symbol to be declared and displayed.
  • The const keyword is sufficient to declare and display the variable.
  • We can declare and define more than one constant variable at a time with the “const” keyword.
  •  “const” can not be declared under another block or scope, like a function or an if statement.

Create a constant with the “define” function:

  • In PHP, to declare a constant variable, we can also use the “define” function with two parameters.
  • The first parameter is used for the constant variable name, and the second for the value of the constant variable.
  •  The $ sign is also prevented here.
  • We can not declare and define more than one constant variable at a time; we can declare just one constant value with a single define function. If we want a more constant variable, declare it individually.
  • The “define” can be declared under another block or scope, like a function or an if statement.Create a constant with the “define” function:
  • In PHP, to declare a constant variable, we can also use the “define” function with two parameters.
  • The first parameter is used for the constant variable name, and the second for the value of the constant variable.
  •  The $ sign is also prevented here.
  • We can not declare and define more than one constant variable at a time; we can declare just one constant value with a single define function. If we want a more constant variable, declare it individually.
  • The “define” can be declared under another block or scope, like a function or an if statement.

 

1.8    Expressions in PHP

In PHP, any type of statement that consists of operators, operands, values, and function calls is called an expression. Each expression evaluates the code.

For example:

$a=5;                //declaration and definition expression

$b= $a+$a;               //assignment expression

If($a>5)                     //conditional expression

While($a<5)            //conditional expression

For($s= 5)                 //conditional expression

Echo $a;                    //display expression

Key components of expressions

Operators:

All kinds of operators are used in expression building. The assignment operator not only assigns a value to the operand but also uses it as a comparison operator and a concatenating operator. Other operators, like arithmetical, logical, and bitwise operators, play a vital role in creating logical expressions.

Operands:

Variable declaration and definition are also a kind of expression. It is used as an operand in an expression. It comes with various data types, for example, int, float, char, string, etc.

Values:

Processed or to-be-processed values are used in the expression.

Function calls:

PHP expression uses the built-in or user-defined function call.

For example, echo and print are built-in functions. The print function can be used as an expression, but echo can’t.

$ch1 = print "Hello"; // This is valid and returns 1.

 1.9    Operators in PHP

Operators operate (perform) a specific operation on the operand. This operation might be arithmetical, logical, or bitwise. PHP provides various kinds of operators, which are divided into three types of operators: unary, binary, and ternary. Unary takes one operand only; it is also called the increment and decrement operator.

Unary operator:

Unary takes one operand only; it is also called the increment and decrement operator. For example:

$a++;             //Pre-increment

++$a;             //Post-increment

$a—;              //Pre-decrement

--$a;               //Post-decrement

 

Binary operator: It takes two operands.

Arithmetical operator:

Arithmetical operators perform addition, multiplication, division, and subtraction operations.

For Example:

<html>

<body>

<?php

$a=5;

$b=6;

echo "Addition=",$c=$a+$b;

?>

</body>

</html>

OUTPUT

Addition = 11

Assignment operator:

The assignment operator is used in any expression to assign or store a value to a variable. For example:

$c=$a+$b;

Another use of assign operator is that we can compare two values. For example

If($a==2)

Here, check whether the value of $a and 2 is the same or not.

The next use of the assignment operator is to concatenate two operands or strings. For example,

<html>

<body>

<?php

$a=”Hello”;

$b=”PHP”;

echo $a.=$b;

?>

</body>

</html>

OUTPUT

Hello PHP

Logical operator:

The logical operator creates a logical expression. For example,

$a AND $b                //Executes only when both are true

$a OR $b                   //Executes only when one of them is true

$a XOR $b                //Executes only when one of them is true, not both.

$a && $b                  // Executes only when both are true   

$a || $b                    //Executes only when one of them is true

! $b                 //Executes only when given one is not true.

Comparison operator:

It is used to compare two operands. For example.

$a<=$b;                    //Return true if a is less than or equal to b.

$a>=$b;                    //Return true if a is greater than or equal to b.

$a!=$b;                     //Return true if a is not equal to b.

$a==$b;                    //Return true if a is equal to b.

$a<>$b;                    //Return true if a is not equal to b.

Ternary operator: It takes three operands. For example, (? :)  

<html>

<body>

<?php

$a=5;

 echo($a%2==0?"Odd":"Even")

 ?>

</body>

</html>

OUTPUT

Even

 


 

Popular posts from this blog

English

Speech of Shah Rukh Khan- Towards the dream

Daily use questions English to Marathi