33 PHP – 1
Dr S. Abirami
1. Learning Objectives:
This module is intended to learn the functionality and utility of PHP along with the usage of syntax, variables and data types available in PHP. This module is also intended to learn the installation and deployment of PHP.
2. SERVER-SIDE PROGRAMMING
Server side programming is a server side scripting used for web development where the server sends response according to the requests sent by the clients. The request can be static or dynamic. The request to a static site involves a server with homepage lookup and it sends the response as a HTTP Response to the clients. The request to a dynamic site involves the server to respond dynamically, as it needs to provide different client-side code depending on the situation such as date and time, based on the specifics of the user’s request or database contents – forms and authentication.
3. PHP
PHP stands for PHP: Hypertext Preprocessor, a Server-Side Scripting language like ASP. PHP scripts are executed on the server. PHP is open source software (OSS), which means it’s free to use and isn’t being controlled by a single entity. It also supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.).
PHP syntax resembles that of JavaScript and ActionScript in different ways.PHP isdeveloped by a group of developers which is free to download and use. PHP is an interpreted language, i.e. there is no need for compilation.PHP is faster than other scripting language e.g. ASP and JSP.
3.1 PHP Characteristics
PHP is web-specific and open source. Here, the scripts are embedded into static HTML files and it ensures fast execution of scripts. It provides fast access to the database tier of applicationsand it is supported by most of the web servers and operating systems. PHP supports many standard network protocols libraries available for IMAP, NNTP, SMTP and POP3. It also supports many database management systems libraries available for UNIX DBM, MySQL and Oracle. It generates dynamic output text (HTML XHTML and any other XML file) and dynamic output images (PDF files and even Flash movies). It comprises of text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents. PHP is a fully featured programming language suitable for complex systems development.
3.2 PHP File
PHP files can contain text, HTML tags and scripts. PHP files are returned to the browser as plain HTML. These files have a file extension of “.php”, “.php3”, or “.phtml”. PHP can generate dynamic page content and can create, open, read, write, delete, and close files on the server. This can collect data from forms and can send and receive cookies. This files can also add, delete and modify data in your database. It controls user-access andcan encrypt data as well. With PHP you are not limited to output HTML. You can also output images, PDF files, and even flash movies. You can also output any text, such as XHTML and XML through PHP files.
PHP is free and can be downloaded from the official PHP resource: www.php.net. PHP runs on various platforms (Windows, Linux, UNIX, Mac OS X, etc.) and is compatible with almost all servers used today (Apache, IIS, etc.). PHP supports a wide range of databases and it is easy to learn. This can also run efficiently on the server side.
To get access to a web server with PHP support, you can install Apache (or IIS) on your own server, install PHP and MySQL(For testing, we installed XAMMP server which is a 3 in 1 software comprising of PHP, MySQL and Apache) or find a web hosting plan with PHP and MySQL support.
If your server supports PHP you don’t need to do anything. Just create some .php files in your web directory, and the server will parse them.Because it is free and most web hosts offer PHP support. However, if your server does not support PHP, you must install PHP.
3.3 PHP Installation and Deployment
PHP programs can be executed under various servers like WAMP, XAMPP etc.
WAMP Server: This server is used for web development platform which helps in creating dynamic web applications.
XAMPP Server: This is a free open source cross-platform web server package.Xamppserver can be used to execute the PHP programs. The server can be downloaded from the following link:http://www.apachefriends.org/en/xampp-windows.html //wampserver.com
After downloading, just follow the steps given below to start the XAMPP server:
- Step1:Install XAMPP
- Step2:Assume you installed xampp in C Drive. Go to: C:\xampp\htdocs and create your own folder. Name the folder, say for example “Sample”.
- Step3: Now create your first php program inxampp and name it as “add.php”.
<html>
<head>
<title>Addition php</title>
</head>
<body>
<?php # operator print “
<h2>php program to add two numbers…</h2><br />”; $val1 = 20; $val2 = 20;
$sum = $val2 + $val2; /* Assignment operator */ echo “Result(SUM): $sum”; ?> </body></html>
- Step4:Now double click on “XAAMP CONTROL PANEL” on desktop and START “Apache” (icon also appears on the bottom) as shown below in Figure 1.
- Step5:Type localhost on your browser and press enter. It will show you the following homepage of XAMPP server as shown in Figure 2.
Now type the following on browser:http://localhost/Sample/. The screenshot shown in Figure 3 displays the php files created under folder “Sample”.
3.4 History of PHP
PHP was developed on June 1995 as Personal Home Page Tools. RasmusLerdorf developed the CGI scripts written in C. In April 1996, PHP/FI scripting language was developed by RasmusLerdorf. In June 1998 the engine was rewritten by ZeevSuraski andAndy Gutsmans in Tel Aviv. In May 2000 the parser was rewritten again by “Zend Engine”. In May 2004, PHP5 the current language version was developed. It started the evolution from script collection to scripting language. Like PHP, the other server-side languages embedded in HTML areASP and JSP.
3.5 Uses of PHP:
Three main uses of PHP involves the following:
Server-side scripting: This is the most traditional and main target field for PHP. You need three things to make this work:
- The PHP parser (CGI or server module),
- A web server that needs a connected PHP installation
- A web browser that can access PHP page through URL
Command line scripting: You can make a PHP script to run without any server or browser. For this, you need the PHP parser to use it in this way. These scripts can also be used for simple text processing tasks similar to PERL.
Writing client-side GUI applications: PHP is probably not the very best language to write windowing applications, but PHP-GTK (PHP Graphics Tool Kit) can be used to write such programs.
3.6 Advantages of PHP:
This is included inside HTML pages. This means that all your work can be done in the same directory, and a single file can contain HTML as well as PHP code.
Much easier to edit/maintain web pages.
This greatly improves tasks like dynamic page processing. Checking and doing simple HTML form based tasks.
Database connectivity
4. Basic PHP Syntax
A PHP script can be placed anywhere in the document.A PHP script starts with the tag <?php and ends with ?>
<?php
// PHP code goes here
?>
The default file extension for PHP files is “.php”. Servers with shorthand support enabled, we can start a scripting block with <? and end with ?>.For maximum compatibility, it is recommend that we can use the standard form (<?php) rather than the shorthand form.A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code.Below, is an example of a simple PHP script which sends the text “Hello World” to the browser
<html>
<body>
<?php echo “Hello World”; ?>
</body></html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to differentiate one block of instructions from another.There are two basic statements to output text with PHP, which are echo and print. In the example above, echo statement has been used to output the text “Hello World”.Here, the file must have a .php extension and if the file has a .html extension, the PHP code will not be executed.
Example of a simple PHP program:
File: hello.php
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?phpecho “Hello World!”;?>
</body>
</html>
Output:
My first PHP page
Hello World!
4.1 PHP Echo Statement
PHP echo statement is a language construct but not a function, so there is no need to use parenthesis with it. If we want to use more than one parameter with an echo statement, it is required to use parenthesis.The syntax of PHP echo statement is given below:
void echo ( string $arg1 [, string $… ] )
PHP echo statement can be used to print string, multi line strings, escaping characters, variable, array etc.
PHP echo example to print a string
File: echo1.php
<?phpecho “Hello by PHP echo”;?>
Output:
Hello by PHP echo
4.2 Variables in PHP
PHP variables include the following:
A variable in PHP is a name of memory location that holds data.
A variable is a temporary storage that is used to store data temporarily.
In PHP, a variable is declared using $ sign followed by variable name. The syntax of declaring a variable in PHP is given below:
$variablename=value;
Variables are used for storing values, like text strings, numbers or arrays.
When a variable is declared, it can be used over and over again in the script.
- A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). The variable naming rules comprises of the following:
- 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).
Example of PHP Variable: Declaring string, integer and float variables
File: variable1.php
<?php
$str=”hello string”;
$x=200;
$y=44.6;
echo “string is: $str<br/>”;
echo “integer is: $x <br/>”;
echo “float is: $y <br/>”;?>
Output:
string is: hello string
integer is: 200
float is: 44.6
PHP is a Loosely Typed Language. In the example above, notice that it is not mentioned to PHP that which data type the variable it is. PHP automatically converts the variable to the suitable 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.
4.2.1 PHP Variables Scope
In PHP, variables can be declared anywhere in the script.The scope of the variable is the part of the script where the variable can be referenced or used.PHP has three different variable scopes such as local, global and static.
Global Scope: A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
Example:
<?php
$x = 5; // global scope functionmyTest() {
// using x inside this function will generate an error
echo “<p>Variable x inside function is: $x</p>”;
}
myTest();
echo “<p>Variable x outside function is: $x</p>”;
?>
Output:
Variable x inside function is:
Variable x outside function is: 5
Local Scope: A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
Example:
<?php
functionmyTest() {
$x = 5; // local scope
echo “<p>Variable x inside function is: $x</p>”;
}
myTest();
// using x outside the function will generate an error echo “<p>Variable x outside function is: $x</p>”;?>
Output:Variable x inside function is: 5
Variable x outside function is:
PHP the global keyword: The global keyword is used to access a global variable from within a function.To do this, it is needed to 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
4.3 PHP – Constants
A constant is an identifier (name) for a simple value.PHP constants are names or identifier that cannot be changed during the execution of the script. PHP constants can be defined by 2 ways using define () function and using const keyword. PHP constants follow the same PHP variable rules. For example, it can be started with a letter or underscore only.Conventionally, PHP constants should be defined in uppercase letters.
PHP constant: define().The syntax of define() function in PHP isdefine(name, value, case-insensitive) where “name” specifies the constant name, “value” specifies the constant valueand “case-insensitive” specifies that the default value is false. It means it is case sensitive by default.
An Example to define PHP constant using define ():
<?php define(“MESSAGE”,”HelloJava PHP”); echo MESSAGE; ?>
Output:
Hello JavaPHP
In PHP constants, the keywordused here is const. The const keyword defines the constants at the compilation time. This is a language construct and not a function.This is bit faster than define () and is always case sensitive.
Example to define PHP constant using const keyword
<?php const MESSAGE=”Hello const by JavaTpoint PHP”; echo MESSAGE; ?>
Output:
Hello const by JavaTpoint PHP
4.4 Comments in PHP
PHP supports three types of comments:
- Shell style comments which is denoted as #THIS IS A COMMENT
- C++ style comments which is denoted as //THIS IS A COMMENT—
- C style comments which isdenoted as /* ALL THIS COMMENTED! */
Example of PHP comments:
<?php
// 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
*/?>
4.5 PHP Data Types
PHP data types are used to hold different types of data or values. PHP supports primitive data types that can be categorized further in 3 types:
Scalar Types
Compound Types Special Types
Scalar Types: There are 4 scalar data types in PHP which are Boolean, integer, floatand string.
Compound Types:There are 2 compound data types in PHP which are array and objects. Special Types: There are 2 special data types in PHP: resource and NULL
Let us see an example here which makes use of the PHP scalar data types Boolean, integer, float and string along with its output. The next two data types of Compound types and Special types will be discussed in the next module.
Output of the above example
Car
555
120.7
1
Summary
In this module, the characteristics and significance of PHP has been learnt along with the procedures stating about the installation and deployment of PHP. Also, we have learnt about the syntax of PHP scripts with small examples.
Web Links
- https://www.w3schools.com/php/
- http://www.c4learn.com/php/php-continue-statement/
- http://www.webstepbook.com/supplements.shtml
- http://sg2.php.net/manual/en/
- http://www.javatpoint.com/php-tutorial
- http://www.w3schools.com/php/default.asp
- https://github.com/linghangedu/PHP-Primer
- https://www.javatpoint.com/php-tutorial
- http://www.php.net/
- Steven Holzner, “PHP: The Complete Reference”, First Edition, McGraw-Hill Education,2007.
- Deitel and Deitel, “Internet and World Wide Web: How to Program”, Fifth Edition, Pearson Education, 2012.