Chapter - 5
Chapter - 5
Basics of PHP
1 PHP
PHP
What is PHP?
PHP is an acronym for "PHP: Hypertext
Preprocessor“
PHP is a widely-used, open source scripting
language.
PHP scripts are executed on the server
PHP is free to download and use
PHP is a server scripting language, and a powerful
tool for making dynamic and interactive Web pages.
PHP is a widely-used, free, and efficient alternative
to competitors such as Microsoft's ASP.
2 PHP
Cont…
PHP is an amazing and popular language!
It is powerful enough to be at the core of the biggest
blogging system on the web (WordPress)!
It is deep enough to run the largest social network
(Facebook)!
It is also easy enough to be a beginner's first server side
language!
What is a PHP File?
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is
returned to the browser as plain HTML
PHP files have extension ".php"
3 PHP
Cont..
What Can PHP Do?
PHP can generate dynamic page content
PHP can create, open, read, write, delete, and close files
on the server
PHP can collect form data
PHP can send and receive cookies
PHP can add, delete, modify data in your database
PHP can be used to control user-access
PHP can encrypt data
With PHP you are not limited to output HTML. You can
output images, PDF files, and even Flash movies. You
can also output any text, such as XHTML and XML.
4 PHP
Cont…
Why PHP?
PHP runs on various platforms (Windows, Linux,
Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
PHP supports a wide range of databases (MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL, etc.)
PHP is free.
PHP is easy to learn and runs efficiently on the
server side
PHP is free to download and use
5 PHP
Where To Start?
1. Open your browser write localhost on the URL and click enter
2. Sometimes, when you start apache(listens port 80) port 80
may be used by other process, at this time you can change the
port# by clicking on config in front of apace in the xampp
control panel and change the port# to 8080 and save it
3. Then write localhost:8080 and click enter
Write your first php file
When you want to work on PHP code you need to start Apache/MySQL on the
XAMPP control panel
Save all of your PHP documents into the htdocs folder with the file
extension .php
PHP files can be inside subfolders of htdocs
Run your PHP file by browsing to http://localhost/foldername
The default page (home page) of each folder is index.php
If you want to view a page with a different name, open
http://localhost/foldername/pagename.php
Php Syntax
<?php
// This won't work because of the quotes around left!
echo "<h5 id=“left">I love using PHP!</h5>";
// OK because we escaped the quotes!
echo "<h5 class=\“left\">I love using PHP!</h5>";
// OK because we used an apostrophe '
echo "<h5 class=‘left'>I love using PHP!</h5>";
?>
Alternative way of writing php
In addition to the basic syntax,
You can write php file in the following ways but not
commonly used
Short style
<?
echo “Welcome to Today’s class!";
?>
Script style
<script language=”php”>
echo “Welcome to Today’s class!";
<script>
ASP style
<%
echo “Welcome to Today’s class!";
%>
Cont…
Basic PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".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:
18 PHP
Cont…
Example
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Note: PHP statements end with a semicolon (;).
19 PHP
Cont…
Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the
program. Its only purpose is to be read by someone who is looking at the code.
Example
<html>
<body>
<?pup
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body></html>
20 PHP
Cont…
PHP Case Sensitivity
In PHP, all 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 legal
(and equal):
Example
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body></html>
21 PHP
Cont…
However; all variable names are case-sensitive.
In 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
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
22 PHP
Cont…
Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the
value Hello world!, the variable $x will hold the value 5, and the variable $y
will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for
declaring a variable. It is created the moment you first assign a value to it.
Think of variables as containers for storing data.
23 PHP
Cont…
PHP Variables
A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the
variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different
variables)
Remember that PHP variable names are case-sensitive!
24 PHP
Cont…
Output Variables
The PHP echo statement is often used to output data
to the screen. The following example will show how
to output text and a variable:
Example
<?php
$txt = “w3schools.com";
echo "I love $txt!";
?>
The following example will produce the same
output as the example above:
25 PHP
Cont…
Example
<?php
$txt = “w3schools.com";
echo "I love " . $txt . "!";
?>
The following example will output the sum of two variables:
Example
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
26 PHP
Cont…
PHP is a Loosely Typed Language
In the example above, notice that we did not have to tell PHP
which data type the variable is.
PHP automatically converts the variable to the correct data
type, depending on its value. In other languages such as C, C+
+, and Java, the programmer must declare the name and type of
the variable before using it.
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the
variable can be referenced/used.
PHP has three different variable scopes:
local
global
27 PHP
Local and Global Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function. within the function use global keyword.
A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function.
The following example tests variables with local and global scope :
Example
<?php
$x=5; // global scope
function myTest() {
$y=10; // local scope
echo "<p>Test variables inside the function:</p>";
echo "Variable x is: $x";// Error
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:</p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>
28 PHP
Cont…
Note: You can have local variables with the same name in different
functions, because local variables are only recognized by the function in
which they are declared.
PHP The global Keyword
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x=5;
$y=10;
function myTest() {
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
29 PHP
Cont…
PHP String Functions
Get the Length of a String
The PHP strlen() function returns the length of a
string. The example below returns the length of
the string "Hello world!":
Example
<?php
echo strlen("Hello world!"); // outputs 12
?>
The output of the code above will be: 12.
30 PHP
Cont…
Count the Number of Words in a String
The PHP str_word_count() function counts the
number of words in a string:
Example
<?php
echo str_word_count("Hello world!"); //
outputs 2
?>
The output of the code above will be: 2.
31 PHP
Cont…
Reverse a String
The PHP strrev() function reverses a string:
Example
<?php
echo strrev("Hello world!"); // outputs !dlrow
olleH
?>
The output of the code above will be: !dlrow olleH.
32 PHP
Cont…
Search for a Specific 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. The example below
searches for the text "world" in the string "Hello world!":
Example
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
The output of the code above will be: 6.
Tip: The first character position in a string is 0 (not 1).
33 PHP
Cont…
Replace Text within a String
The PHP str_replace() function replaces some
characters with some other characters in a string.
The example below replaces the text "world" with
"Dolly":
Example
<?php
echo str_replace("world", "Dolly", "Hello
world!"); // outputs Hello Dolly!
?>
The output of the code above will be: Hello Dolly!
34 PHP
PHP Operators
Operators are used to perform operations on variables
and values. PHP divides the operators in the following
groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
35 PHP
Cont…
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to
perform common arithmetical operations, such as addition,
subtraction, multiplication etc.
36 PHP
Cont…
PHP Assignment Operators
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.
37 PHP
Cont…
PHP Comparison Operators
The PHP comparison operators are used to compare two values
(number or string):
38 PHP
Cont…
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's
value. The PHP decrement operators are used to decrement a
variable's value.
39 PHP
Cont…
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.
40 PHP
Cont…
PHP String Operators
PHP has two operators that are specially designed for
strings.
41 PHP
Cont…
Example:
<?php
$string1="Hello ";
$string2="World";
echo $string1 . " " . $string2;
?>
Output
Hello World
42 PHP
Cont…
PHP Conditional Statements
Very often when you write code, you want to perform
different actions for different conditions. You can use
conditional statements in your code to do this. In PHP we
have the following conditional statements:
if statement - executes some code if one condition is
true
if...else statement - executes some code if a condition
is true and another code if that condition is false
if...elseif....else statement - executes different codes
for more than two conditions
43 PHP
Cont…
The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the
current time (HOUR) is less than 20:
Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
44 PHP
Cont…
The if...else Statement
The if....else statement executes some code if a condition is true and another code if that condition
is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and
"Have a good night!" otherwise:
Example
<?php
$t = date("H");
46 PHP
Cont…
The example below will output "Have a good morning!" if
the current time is less than 10, and "Have a good day!" if the
current time is less than 20. Otherwise it will output "Have a
good night!":
Example
<?php
$t = date("H");
{
code to be executed;
}
48 PHP
Cont…
Example:
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
49
</html> PHP
Cont…
case "Thu":
Switch Statement
echo "Today is Thursday";
<html>
break;
<body>
case "Fri":
<?pup
echo "Today is Friday";
$d=date("D");
break;
switch ($d)
case "Sat":
{
echo "Today is Saturday";
case “Mon":
break;
echo "Today is Monday"; case "Sun":
break; echo "Today is Sunday";
case "Tue": break;
echo "Today is Tuesday"; default:
break; echo "Wonder which day is this ?";
case "Wed": }
echo "Today is Wednesday"; ?>
break; </body></html>
50 PHP
PHP Functions with Parameters
<html> <head>
PHP gives you option to
<title>Writing PHP Function with
pass your parameters inside
Parameters</title>
a function. You can pass as </head> <body>
many as parameters your <?pup
like. These parameters function addFunction($num1,
work like variables inside $num2)
your function. {
The following example $sum = $num1 + $num2;
echo "Sum of the two numbers is :
takes two integer
$sum";
parameters and adds them }
together and then prints addFunction(10, 20);
them. ?>
</body> </html>
51 PHP