Unit-1 PHP
Unit-1 PHP
Introduction to PHP:
What is PHP?
History of PHP:
The first part of PHP was developed for his personal use in late 1994. This was
a CGI wrapper that helped him keep track of people who looked at his personal
site.
The next year, he put together a package called the Personal Home Page Tools
(a.k.a. the PHP Construction Kit) in response to demand from users.
Version 2 was soon released under the title PHP/FI and included the Form
Interpreter, a tool for parsing SQL queries.
By the middle of 1997, PHP was being used on approximately 50,000 sites
worldwide.
Zeev Suraski and Andi Gutmans, the two Israeli programmers who developed
the PHP3 and PHP4 parsers, have also generalized and extended their work
under the rubric of Zend.com.
The fourth quarter of 1998 initiated a period of explosive growth for PHP, as all
open source technologies enjoyed massive publicity.
In October 1998, according to the best guess, just over 100,000 unique domains
used PHP in some way. Just over a year later, PHP broke the one-million
domain mark.
Features of PHP:
PHP is very popular language because of its simplicity and open source. There
are some important features of PHP given below:
Performance:PHP script is executed much faster than those scripts which are
written in other languages such as JSP and ASP. PHP uses its own memory, so
the server workload and loading time is automatically reduced, which results in
faster processing speed and better performance.
Open Source:PHP source code and software are freely available on the web.
You can develop all the versions of PHP according to your requirement without
paying any cost. All its components are free to download and use.
Embedded:PHP code can be easily embedded within HTML tags and script.
Platform Independent:PHP is available for WINDOWS, MAC, LINUX &
UNIX operating system. A PHP application developed in one OS can be easily
executed in other OS also.
Web servers Support:PHP is compatible with almost all local servers used
today like Apache, Netscape, Microsoft IIS, etc.
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP)
software stack. It is available for all operating systems. There are many AMP
options available in the market that are given below:
If you are on Windows and don't want Perl and other features of XAMPP, you
should go for WAMP. In a similar way, you may use LAMP for Linux and
MAMP for Macintosh.
We will learn how to install the XAMPP server on windows platform step by
step. Follow the below steps and install the XAMPP server on your system.
Step 2: After downloading XAMPP, double click on the downloaded file and
allow XAMPP to make changes in your system. A window will pop-up, where
you have to click on the Next button.
Step 3: Here, select the components, which you want to install and click Next.
Step 4: Choose a folder where you want to install the XAMPP in your system
and click Next.
Step 5: Click Next and move ahead.
Step 6: XAMPP is ready to install, so click on the Next button and install the
XAMPP.
Step 9: XAMPP is ready to use. Start the Apache server and MySQL and run
the php program on the localhost.
If we want to use PHP in the Html document, then we have to follow the steps
which are given below. Using these simple steps, we can easily add the PHP
code.
Step 1: Firstly, we have to type the Html code in any text editor or open the
existing Html file in the text editor in which we want to use the PHP.
<!Doctype Html>
<Html>
<Head>
<Title>
Use a Php in Html
</Title>
</Head>
<Body>
</Body>
</Html>
Step 2: Now, we have to place the cursor in any tag of the <body> tag where
we want to add the code of PHP. And, then we have to type the start and end tag
of PHP.
<h1>
<?php ?>
</h1>
Step 3: After then, we have to type the code of PHP between the tags of PHP.
<h1>
<?php
echo "Hii User!! You are at JavaTpoint Site"
?>
</h1>
Step 4: When we successfully add the PHP code, then we have to save the Html
file and then run the file in the browser.
<!Doctype Html>
<Html>
<Head>
<Title>
Use a Php in Html
</Title>
</Head>
<Body>
<h1><?php echo "Hii User!! You are at JavaTpoint Site" ?></h1>
</Body>
</Html>
Understanding PHP:
A PHP script is executed on the server, and the plain HTML result is sent back
to the browser.
<?php
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page:
A simple .php file with both HTML code and PHP code:
<!DOCTYPE html>
<html>
<body>
?>
</body>
</html>
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:
Example
<!DOCTYPE html>
<html>
<body>
<?php
</body>
</html>
Look at the example below; only the first statement will display the value of
the $color variable! This is because $color, $COLOR, and $coLOR are treated
as three different variables:
Example
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
?>
</body>
</html>
Whitespace is the stuff you type that is typically invisible on the screen,
including spaces, tabs, and carriage returns (end-of-line characters).
PHP whitespace insensitive means that it almost never matters how many
whitespace characters you have in a row.one whitespace character is the same as
many such characters.For example, each of the following PHP statements that
assigns the sum of 2 + 2 to the variable $four is equivalent −
Comments in PHP:
A comment in PHP code is a line that is not executed as a part of the program.
Its only purpose is to be read by someone who is looking at the code.
Example
/* This is a
multi-line comment */
echo and print are more or less the same. They are both used to output data to
the screen.
The differences are small: echo has no return value while print has a return
value of 1 so it can be used in expressions. echo can take multiple parameters
(although such usage is rare) while print can take one argument. echo is
marginally faster than print.
The echo statement can be used with or without parentheses: echo or echo().
Display Text
The following example shows how to output text with the echo command
(notice that the text can contain HTML markup):
Example
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
Display Variables
The following example shows how to output text and variables with
the echo statement:
Example
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
Datatypes in php:
PHP data types are used to hold different types of data or values. PHP supports
8 primitive data types that can be categorized further in 3 types:
It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
1. resource
2. NULL
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two
values: TRUE (1) or FALSE (0). It is often used with conditional statements. If
the condition is correct, it returns TRUE otherwise FALSE.
Example:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output:
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole
numbers, i.e., numbers without fractional part or decimal points.
Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can
hold numbers with a fractional or decimal point, including a negative or positive
sign.
Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
PHP String
String values must be enclosed either within single quotes or in double quotes.
But both are treated differently. To clarify this, see the example below:
Example:
<?php
$company = "Javatpoint";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>
Output:
Hello Javatpoint
Hello $company
PHP Array
An array is a compound data type. It can store multiple values of same data type
in a single variable.
Example:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and value
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
Output:
You will learn more about array in later chapters of this tutorial.
PHP object
Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared.
Example:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store
some function calls or references to external PHP resources. For example - a
database call. It is an external resource.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention
of writing it in capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
Keywords in PHP:
PHP has a set of keywords that are reserved words which cannot be used as
function names, class names or method names. Prior to PHP 7, these keywords
could not be used as class property names either:
Keyword Description
abstract Declare a class as abstract
Variables in PHP:
1. $variablename=value;
o A variable must start with a dollar ($) sign, followed by the variable
name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a
number or special symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated
as different variable.
Let's see the example to store string, integer, and float values in PHP variables.
1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>
Output:
1. <?php
2. $x=5;
3. $y=6;
4. $z=$x+$y;
5. echo $z;
6. ?>
Output:
11
In PHP, variable names are case sensitive. So variable name "color" is different
from Color, COLOR, COLor etc.
1. <?php
2. $color="red";
3. echo "My car is " . $color . "<br>";
4. echo "My house is " . $COLOR . "<br>";
5. echo "My boat is " . $coLOR . "<br>";
6. ?>
Output:
My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is
1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
6. ?>
Output:
hello
hello
1. <?php
2. $4c="hello";//number (invalid)
3. $*d="hello";//special symbol (invalid)
4.
5. echo "$4c <br/> $*d";
6. ?>
Output:
Constant in php:
A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
Note: Unlike variables, constants are automatically global across the entire
script.
Constants are similar to the variable except once they defined, they can never be
undefined or changed. They remain constant across the entire program. PHP
constants follow the same PHP variable rules. For example, it can be started
with a letter or underscore only.
Use the define() function to create a constant. It defines constant at run time.
Let's see the syntax of define() function in PHP.
File: constant1.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?>
Output:
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE, "</br>";
4. echo message;
5. ?>
Output:
Output:
1. <?php
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE;
4. ?>
Output:
Expression in php:
Syntax
$x=100; //100 is an expression
$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression
Example
<?php
$x=10;
$y=$x++; //equivalent to $y=$x followed by $x=$x+1
echo "x = $x y = $y";
?>
Output
x = 11 y = 10
Example
<?php
$x=10;
$y=++$x;; //equivalent to $x=$x+1 followed by $y=$x
echo "x = $x y = $y";
?>
Output
x = 11 y = 11
Example
<?php
$marks=60;
$result= $marks<50 ? "fail" : "pass";
echo $result;
?>
Output:
pass
Operators in PHP:
In the above example, + is the binary + operator, 10 and 20 are operands and
$num is variable.
ADVERTISEMENT
o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators
Arithmetic Operators
Assignment Operators
The assignment operators are used to assign value to different variables. The
basic assignment operator is "=".
& And $a & $b Bits that are 1 in both $a and $b are set to
1, otherwise 0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0
are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
Comparison Operators
ADVERTISEMENT
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the
value of a variable.
Logical Operators
xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
The string operators are used to perform the operation on strings. There are two
string operators in PHP, which are given below:
Array Operators
The array operators are used in case of array. Basically, these operators are used
to compare the values of arrays.
Type Operators
The type operator instanceof is used to determine whether an object, its parent
and its derived class are the same type or not. Basically, this operator
determines which certain class the object belongs to. It is used in object-
oriented programming.
1. <?php
2. //class declaration
3. class Developer
4. {}
5. class Programmer
6. {}
7. //creating an object of type Developer
8. $charu = new Developer();
9.
10. //testing the type of object
11. if( $charu instanceof Developer)
12. {
13. echo "Charu is a developer.";
14. }
15. else
16. {
17. echo "Charu is a programmer.";
18. }
19. echo "</br>";
20. var_dump($charu instanceof Developer); //It will return true.
21. var_dump($charu instanceof Programmer); //It will return false.
22.?>
Output:
Charu is a developer.
bool(true) bool(false)
Execution Operators
PHP has an execution operator backticks (``). PHP executes the content of
backticks as a shell command. Execution operator and shell_exec() give the
same result.
`` backticks echo `dir`; Execute the shell command and return the
result.
Here, it will show the directories available in
current folder.
PHP has one error control operator, i.e., at (@) symbol. Whenever it is used
with an expression, any error message will be ignored that might be generated
by that expression.
Associativity
[ array() left
** arithmetic right
| bitwise OR left
&& logical AND left
|| logical OR left
?: ternary left
or logical left