0% found this document useful (0 votes)
46 views55 pages

Server-Side Internet and Web Programming

PHP is a server-side scripting language used to build dynamic websites. PHP code runs on the server and generates HTML that is sent to the browser. PHP scripts can be embedded within HTML pages with the .php file extension. When a PHP page is requested, the PHP code is executed and the results are returned to the browser as HTML. The document provides examples of basic PHP scripts that output text and display the current time to demonstrate how PHP code can be embedded in HTML pages to dynamically generate content.

Uploaded by

Bravalu Macpha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views55 pages

Server-Side Internet and Web Programming

PHP is a server-side scripting language used to build dynamic websites. PHP code runs on the server and generates HTML that is sent to the browser. PHP scripts can be embedded within HTML pages with the .php file extension. When a PHP page is requested, the PHP code is executed and the results are returned to the browser as HTML. The document provides examples of basic PHP scripts that output text and display the current time to demonstrate how PHP code can be embedded in HTML pages to dynamically generate content.

Uploaded by

Bravalu Macpha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Server-Side Internet and Web

Programming

Variables and Datatypes(2)


What is PHP?


PHP is a programming language for building dynamic,
interactive Web sites.

As a general rule, PHP programs run on a Web server, and
serve(show) Web pages to visitors on request.

Dynamic: contents can change automatically each time the
page is viewed

Interactive: responds to input from its visitors.

Pages including PHP codes must have the extension .php
What is PHP?


PHP stands(is short for) for PHP: Hypertext Preprocessor,

aim: to process information and produce hypertext (HTML)
as a result.

PHP is a server - side scripting language , which means that
PHP scripts, or programs, usually run on a Web server

PHP is an interpreted language — a PHP script is processed
by the PHP engine each time it ’s run.

3
Process of Running PHP Scripts

The process of running a PHP script on a Web server looks
like this:

1. A visitor requests a Web page by clicking a link, or typing the page
’ s URL into the browser ’ s address bar. The visitor might also send
data to the Web server at the same time, either using a form
embedded in a Web page, or via AJAX (Asynchronous JavaScript
And XML).

2. The Web server recognizes that the requested URL is a PHP script,
and instructs the PHP engine to process and run the script.


3. The script runs, and when it ’ s finished it usually sends an HTML
page to the Web browser, which the visitor then sees on their screen. 4
Why use PHP?


The large number of Internet service providers (ISPs) and
Web hosting companies that support it. Today hundreds of
thousands of developers are using PHP.

Another great feature of PHP is that it ’ s cross - platform —
you can run PHP programs on Windows, Linux, FreeBSD,
Mac OS X, and Solaris, among others.

What is more, the PHP engine can integrate with all common
Web servers, including Apache, Internet Information Server
(IIS), Zeus, and lighttpd.
5
How to run PHP?

You’ll first need access to a Web server running PHP.
 Xampp server:

X: for cross platform

A: apache web server

M: mysql RDBMS

P: php engine.

P:Perl

Can be downloaded from:

https ://www.apachefriends.org
 Or you can install a web server and then install and
configure: php engine from www.php.net and mysql RDBMS
from mysql.com.
6
How to Test your installation

Open your text editor and create a new file with the
following contents:
< ?php
phpinfo();
?>


Then run through the server.
 Example: http://localhost/testing.php

7
Sample Testing Correct Result

8
How can you understand that sample test is failed


If you see a 404 or a Connection Refused error, check your
document root folder location and server configuration.

On the other hand, if you get a Save As dialog, it means that
either PHP is not installed properly, or the Web server
doesn’t know about the installed PHP module. Check the
documentation that came with your package.

9
Before Your First Script

In PHP, code is inserted between the scripting delimiters <?php and ?>. PHP
code can be placed anywhere in XHTML markup, as long as the code is
enclosed in these delimiters.

Variables are preceded by a $ and are created the first time they are encountered.

PHP statements terminate with a semicolon (;).

Single-line comments which begin with two forward slashes (//) or a pound sign
(#). Text to the right of the delimiter is ignored by the interpreter.

Multiline comments begin with delimiter /* and end with delimiter */.

When a variable is encountered inside a double-quoted ("") string, PHP
interpolates the variable. In other words, PHP inserts the variable’s value where
the variable name appears in the string.

All operations requiring PHP interpolation execute on the server before the
XHTML document is sent to the client.

PHP variables are loosely typed—they can contain different types of data at
different times.
10
Your First Script


To create this very simple script, open your text editor and
enter the following:
<?php
echo "Hello, world!";
?>

Save this file as hello.php in your document root folder, and
view the results in your browser by visiting
http://localhost/hello.php.

11
Result of Your First Script

12
Comments on Your First Script

PHP’s echo() statement takes a string of text — in this
case, "Hello, world!" — and sends it as part of the Web
page to the browser. The browser then displays the "
Hello, world! " text to the visitor.


echo() doesn ’ t have to be given a string of text; it can
display anything that can be displayed, such as numbers
or the results of expressions. An alternative to echo() is
the print() statement, which works in exactly the same
way except that it also returns a value (true). Generally
speaking, you can use print() instead of echo() in your
code if you prefer. 13
Embedding PHP within HTML


As you’ve gathered by now, one of the nice things about
PHP is that you can embed PHP code within HTML. In fact,
each .php script that you write is essentially treated as an
HTML page by default. If the page contains no <?php ... ? >
tags, the PHP engine just sends the contents of the file as - is
to the browser.

14
Embedded PHP Script


You can use this feature to make your "Hello, world!"
example prettier by adding a proper HTML header and
footer and if you wish including a CSS style sheet. Enter the
following code and save it as hello_pretty.php in your
document root folder:

15
Embedded PHP Script
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello</title>
</head>
<body>
<h1><?php echo "Hello, world!"; ?></h1>
</body>
</html>

Run your new PHP script by typing http://localhost/hello_pretty.php into your
browser’s address bar. You should see a more stylish page.

16
Enhanced PHP Script
<!DOCTYPE html>
<html lang="en">
<head>
<title> Hello </title>
</head>
<body>
<h1>
<?php
$currentTime = date( "g:i:s a" );
echo "Hello, world! The current time is $currentTime";
?></h1>
</body>
</html>

Save the file as hello_with_time.php. Run your new PHP script by typing
http://localhost/hello_with_time.php 17
Enhanced PHP Script

The majority of the code is exactly the same as before. The only difference is the
PHP code itself:

< ?php

$currentTime = date("g:i:s a");

echo "Hello, world! The current time is $currentTime";

?>

The first line of PHP code takes the current time and formats it as a readable string
of text, then stores this string of text in a variable called $currentTime. To format
the time, the script uses the built - in date() function. The string of characters
between the quotation marks tells PHP how to format the time, as follows:

g, i, and s tell PHP to output the current hour, minute, and second, respectively a
tells PHP to display either " am " or ‘ pm " as appropriate. The colons (:) and the
space character are not processed by the date() function, so they’re displayed as -
is

Then the second line of code displays the " Hello, world! " message, including the
current time. Reload the page in your browser and you ’ ll see the time change.
18
Make Code More Readable

You might comment the PHP code in the hello_with_time.php
script like this:
< ?php
// Get the current time in a readable format
$currentTime = date("g:i:s a");
// Display greeting and time to the visitor
echo "Hello, world! The current time is $currentTime";
?>

The purpose of comments is to let you add messages to
yourself (and other programmers) that explain what your code
does. It’s always a good idea to add comments to your code,19
even if you’re the only programmer working on it.
PHP Language Basics

Both in PHP and in other programming languages, the
following are important concepts.

Variables , which let you store and manipulate data in your
scripts.

Data types , including which types are available in PHP,
and how to test for and change type

PHP’s available operators , which you can use to
manipulate information

Constants , which are useful for storing data that doesn’t
change in your script.

20
Variables in PHP

Variables are a fundamental part of any programming
language. A variable is simply a container that holds a
certain value. Variables get their name because that certain
value can change throughout the execution of the script. It’s
this ability to contain changing values that make variables so
useful.
echo $x + $y;

You now have a general - purpose script. You can set the
variables $x and $y to any two values you want, either at
some other place in your code, or as a result of input from
the user.
21
Naming Variables

Variable names begin with a dollar sign ( $ )

The first character after the dollar sign must be a letter or an underscore

The remaining characters in the name may be letters, numbers, or
underscores without a fixed limit.

Variable names are case - sensitive ( $Variable and $variable are two
distinct variables), so it’s worth sticking to one variable naming method
— for example, always using lowercase — to avoid mistakes.

Examples of PHP variable names:
$my_first_variable
$anotherVariable
$x
$_123 22
Creating Variables


Creating a variable in PHP is known as declaring it.
Declaring a variable is as simple as using its name in your
script:
$my_first_variable;

When PHP first sees a variable’s name in a script, it
automatically creates the variable at that point.

23
Data Types in PHP


All data stored in PHP variables fall into one of eight basic
categories, known as data types . A variable’s data type
determines what operations can be carried out on the
variable’s data, as well as the amount of memory needed to
hold the data.

PHP supports four scalar data types. Scalar data means data
that contains only a single value.

24
Data Types in PHP

Scalar Data Types and their Descriptions



Integer: A whole number ex:15

Float: A floating - point number ex: 8.23

String: A series of characters ex: "Hello, world!"

Boolean: Represents either true or false ex: true

25
Data Types in PHP


PHP supports two compound types. Compound data is data
that can contain more than one value. The following two
describes PHP’s compound types:
Compound Data Types and their Descriptions
 Array: An ordered map (contains names or numbers mapped
to values)
 Object: A type that may contain properties and methods

26
Data Types in PHP


PHP supports two special data types, so called because they
don ’ t contain scalar or compound data as such, but have a
specific meaning.
Special Data Types and Their Description
 Resource: Contains a reference to an external resource, such
as a file or database
 Null: May only contain null as a value, meaning the variable
explicitly does not contain any value

27
Loose typing

PHP is known as a loosely - typed language. This means
that it’s not particularly fussy about the type of data stored
in a variable. It converts a variable’s data type
automatically, depending on the context in which the
variable is used.

For example, PHP will happily let you pass a floating-
point value to a piece of code that expects to be working
on an integer value. You probably won ’ t see an error
message, but you may discover that the output of your
script isn’t quite what you expected! These types of errors
can be hard to track down. (Fortunately, there is a way to
test the type of a variable)
28
Testing Type of a Variable


You can determine the type of a variable at any time by using
PHP’s gettype() function. To use gettype() , pass in the
variable whose type you want to test. The function then
returns the variable’s type as a string.

29
Testing Type of a variable
<?php
$test_var; // Declares the $test_var variable without initializing it
echo gettype($test_var)."<br/>"; // Displays "NULL"
$test_var = 15;
echo gettype( $test_var ) . "<br/>"; // Displays "integer"
$test_var = 8.23;
echo gettype( $test_var ) . "<br/>"; // Displays "double"
$test_var = "Hello, world!";
echo gettype( $test_var ) . "<br/>"; // Displays "string"
?>
30
Testing Type of a Variable

You can also test a variable for a specific data type using
PHP’s type testing functions:

is_int( value ) :Returns true if value is an integer

is_float( value ) :Returns true if value is a float

is_string( value ) :Returns true if value is a string

is_bool( value ) :Returns true if value is a Boolean

is_array( value ) :Returns true if value is an array

is_object( value ) :Returns true if value is an object

is_resource( value ) :Returns true if value is a resource

is_null( value ) :Returns true if value is null 31
Changing a Variable’s Data Type


One can use PHP’s settype() function to change the type of a
variable while preserving the variable ’ s value as much as
possible.

32
Changing a Variable’s Data Type
<?php
$test_var = 8.23;
echo $test_var."<br/>"; // Displays "8.23"
settype( $test_var, "string" );
echo $test_var."<br/>"; // Displays "8.23"
settype( $test_var, "integer" );
echo $test_var."<br/>"; // Displays "8"
settype( $test_var, "float" );
echo $test_var."<br/>"; // Displays "8"
settype( $test_var, "boolean" );
echo $test_var."<br/>"; // Displays "1"
?>

Finally, after converting $test_var to a Boolean, it contains the value true (which
PHP displays as 1 ). This is because PHP converts a non - zero number to the 33
Boolean value true .
Changing Type by Casting


You can also cause a variable’s value to be treated as a
specific type using a technique known as type casting . This
involves placing the name of the desired data type in
parentheses before the variable’s name. Note that the
variable itself remains unaffected; this is in contrast to
settype() , which changes the variable’s type.

34
Changing Type By Casting
<?php
$test_var = 8.23;
echo $test_var."<br/>"; // Displays "8.23"
echo (string)$test_var."<br/>"; // Displays "8.23"
echo (int)$test_var ."<br/>"; // Displays "8"
echo (float)$test_var ."<br/>"; // Displays "8.23"
echo (boolean)$test_var." <br/>"; // Displays "1"
?>

35
Changing Type by Casting


Here ’ s the full list of casts that you can use in PHP:

(int)value or (integer)value :Returns value cast to an integer.

(float)value :Returns value cast to a float

(string)value :Returns value cast to a string

(bool)value or (Boolean)value :Returns value cast to a
Boolean.

(array)value :Returns value cast to an array

(object)value :Returns value cast to an object
36
Operators and Expressions


Some more examples of expressions:
$x + $y + $z
$x - $y
$x
5
true
gettype( $test_var )

The values and variables that are used with an operator are
known as operands . 37
Arithmetic Operators

In PHP, the arithmetic operators (plus, minus, and so on) work


much as you would expect, enabling you to write
expressions as though they were simple equations.
 For example, $c = $a + $b adds $a and $b and assigns the
result to $c .

38
Arithmetic Operators


Full list of PHP’s arithmetic operators:
+ (addition) 6 + 3 = 9
- (subtraction) 6 - 3 = 3
* (multiplication) 6 * 3 = 18
/ (division) 6 / 3 = 2
% (modulus) 6 % 3 = 0 (the remainder of 6/3)

39
Assignment & Combined Assignment Operator

The basic assignment operator ( = ) can be used to assign a value to a
variable:
$test_var = 8.23;


The equals sign ( = ) can be combined with other operators to give you a
combined assignment operator that makes it easier to write certain
expressions. The combined assignment operators (such as +=, – =, and so
on) simply give you a shorthand method for performing typical
arithmetic operations, so that you don ’ t have to write out the variable
name multiple times. For example, you can write:
$first_number += $second_number;
rather than:
$first_number = $first_number + $second_number;
40
Comparison Operators


You often use comparison operators with decision and
looping statements such as if and while.


If the comparison test is successful, the expression evaluates
to true ; otherwise, it evaluates to false .

41
Comparison Operators

42
Comparison Operators in Action
<?php
$x = 23;
echo ( $x < 24 ) . " <br/>"; // Displays 1 (true)
echo ( $x < "24 " ) . " <br/>"; // Displays 1 (true) because
// PHP converts the string to an integer
echo ( $x == 23 ) . " <br/>"; // Displays 1 (true)
echo ( $x === 23 ) . " <br/>"; // Displays 1 (true)
echo ( $x === "23 " ) . " <br/>"; // Displays "" (false) because
// $x and "23" are not the same data type
echo ( $x >= 23 ) . " <br/>"; // Displays 1 (true)
echo ( $x >= 24 ) . " <br/>"; // Displays "" (false)
?>

As you can see, comparison operators are commonly used to compare two
numbers (or strings converted to numbers). The = = operator is also frequently
43
used to check that two strings are the same.
Incrementing /Decrementing Operators

They are written as two plus signs or two minus signs, respectively,
preceding or following a variable name, like so:
++$x; // Adds one to $x and then returns the result
$x++; // Returns $x and then adds one to it
--$x; // Subtracts one from $x and then returns the result
$x--; // Returns $x and then subtracts one from it

<?php
$x = 5;
echo ++$x; // Displays "6" (and $x now contains 6) pre increment
$x = 5;
echo $x++; // Displays "5" (and $x now contains 6) post increment
44
?>
Logical Operators

PHP’s logical operators work on Boolean values. PHP
automatically evaluates expressions as either true or false when
needed.

For example, the following expressions all evaluate to true :
 1
 1 == 1
 3>2
 "hello" != "goodbye"

The following expressions all evaluate to false :
 3<2
 gettype( 3 ) == "array"
45
 "hello" == "goodbye"
Logical operators


In addition, PHP considers the following values to be false :
 The literal value false
 The integer zero ( 0 )
 The float zero ( 0.0 )
 An empty string ( " " )
 The string zero ( "0" )
 An array with zero elements
 The special type null (including any unset variables)

All other values are considered true in a Boolean context.
46
List of Logical Operators

47
Examples of Logical Operators

Here are some simple examples of logical operators in action:
<?php
$x = 2;
$y = 3;
echo ( ($x > 1) && ($x < 5) ) . " <br/>"; // Displays 1 (true)
echo ( ($x == 2) or ($y == 0) ) . " <br/>"; // Displays 1 (true)
echo ( ($x == 2) xor ($y == 3) ) . " <br/>"; // Displays "" (false) because
// both expressions are true
echo ( !($x == 5 ) ) . " <br/>"; // Displays 1 (true) because
// $x does not equal 5
?>

The main use of logical operators and Boolean logic is when making decisions
48
and creating loops
String Operators

There ’ s really only one string operator, and that ’ s the concatenation
operator , . (dot).

For example:
<?php
echo "Shaken, " . "not stirred"; // Displays " Shaken, not stirred "
?>

Another example
<?php
$tempF = 451;
echo "Books catch fire at " . ( (5/9) * ($tempF - 32) ) . " degrees C.";
// Displays " Books catch fire at 232.777777778 degrees C. "
?>
49
Operator Precedence

If you are not
sure just
overwrite
using
parenthesis.

3+(4*5)

50
Constants

You can also define value - containers called constants in PHP. The values of
constants, as their name implies, can never be changed. Constants can be
defined only once in a PHP program.

Constants differ from variables in that their names do not start with the
dollar sign, but other than that they can be named in the same way variables
are.

In addition, because constants don ’ t start with a dollar sign, you should
avoid naming your constants using any of PHP ’ s reserved words, such as
statements or function names.

For example, don ’ t create a constant called ECHO or SETTYPE .

Constants may only contain scalar values such as Boolean, integer, float, and
string (not values such as arrays and objects), can be used from anywhere in
your PHP program without regard to variable scope, and are case - sensitive.

51
Define Constants

To define a constant, use the define() function, and include inside the
parentheses the name you’ve chosen for the constant, followed by the value for
the constant, as shown here:

<?php
define( "MY_CONSTANT", "19" ); // MY_CONSTANT always has the string
value " 19 "
echo MY_CONSTANT; // Displays " 19 " (note this is a string, not an integer)
?>


Constants are useful for any situation where you want to make sure a value
does not change throughout the running of your script. Common uses for
constants include configuration files and storing text to display to the user. 52
Sample Application
(Calculate the Properties of a Circle)

• <?php
• define( "MY_PI", 3.14 ); // M_PI is predefined constant.
• $radius = 4;
• $diameter = $radius * 2;
• $circumference = MY_PI * $diameter;
• $area = MY_PI * pow( $radius, 2 );
• echo "This circle has... <br/>";
• echo "A radius of " . $radius . " <br/>";
• echo "A diameter of " . $diameter . " <br/>";
• echo "A circumference of " . $circumference . " <br/>";
• echo "An area of " . $area . " <br/>";
53
Executing Sample Application
(Calculate the Properties of a Circle)

54
Notes on Sample Application
(Calculate the Properties of a Circle)


The script uses the built - in pow() function, which takes a
base number, base , followed by an exponent, exp , and
returns base to the power of exp .


There exist built-in PHP constants, as a sample instead of
defining My_PI you can use the built in one named: M_PI ,
which stores the value of π .

55

You might also like