Introduction to PHP by Adam Majczak - Read Online
Introduction to PHP
0% of Introduction to PHP completed



PHP Programming, Web App Programming, PHP Syntax. This book describes also Real Time Data Processing in PHP, PHP intermixing with HTML, CSS and with JavaScript, information feedback between Client side and Server side.

Published: Adam Majczak on
ISBN: 9781301267613
List price: $0.99
Availability for Introduction to PHP
With a 30 day free trial you can read online for free
  1. This book can be read on up to 6 mobile devices.


Book Preview

Introduction to PHP - Adam Majczak

You've reached the end of this preview. Sign up to read more!
Page 1 of 1


CHAPTER 1: Introduction to the e-book edition

PHP is like C and C++, but interpreted (not compiled) server-side universal programming language (named also the server scripting language) used for dynamic websites and interactive web applications. PHP codes as input produce HTML as output. The PHP script is executed on the server, and the plain HTML result is sent back to the browser. Users do not need to install any additional software to be able to view PHP generated web pages. All being required is that the web server has PHP installed in order to interpret PHP scripts.

What is a PHP File?

* PHP files can contain text, HTML, CSS, JavaScript, and PHP code.

* PHP codes are executed on the server, and the result is returned to the browser as plain HTML.

* PHP files have extension *.php (* = file name, php = reserved extension).

* So named pure PHP files contain PHP codes only (without HTML, JavaScript, CSS).

In contrast with static HTML sites, PHP sites are dynamically generated. Instead of the site containing a large number of static HTML files, a PHP-based site may consist of only a few template files (even Single PHP pages are in use). With PHP we are not limited to output HTML. We can output images, PDF files and Flash movies or any text, such as XHTML or XML. Even all HTML code can be dynamically generated by pure PHP files.

The simplest way to think of PHP is as it would be an interpreted C++ that you can embed in HTML pages. PHP itself is written entirely in C. The language itself is a lot like C and C++, except a lot of Web-specific built in functions. The syntax of statements and functions should be familiar for C/C++ programmers, except that variable names are always preceded by $ sign. At the beginning I would like to list some important similarities and differences between PHP nad C/C++.

Similarities and differences: PHP vs. C/C++


* Syntax: basic (excluding OOP) PHP syntax is the same as in C: Code is blank insensitive (i.e. additional spaces and additional Enters do not change code interpretation in any way), statements are terminated with semicolons, and function calls have the same structure.

* Operators: The assignment operators (=, +=, *=, and so on), the Boolean operators (&&, ||, !), the comparison operators (<,>, <=, >=, ==, !=), and the basic arithmetic operators (+, -, *, /, %) all behave in PHP as they do in C/C++.

* Control statements: The control statements (if, switch, while, for) behave as they do in C/C++, including goto, break and continue, but switch-case in PHP can accept strings as case labels.

The key differences:

* All variables are denoted with a leading $ sign. Variables do not need to be declared in advance of assignment, and they have no intrinsic type.

* PHP has only two numerical types: integer (corresponding to a long in C++) and float (corresponding not to float, but to a double in C++). There is no separate short nor char type for short integers in PHP.

* Instead, variables and values are automatically converted across types as needed based on context.

* Arrays have syntax similar to C++, but they are implemented differently. They are associative arrays or hashes, and array index can be either a number or a string.

* There are no pointers available in PHP, but PHP does support references.

* PHP is more forgiving than C++, especially about data types.

* PHP does not use struct (-ures) / records nor union (-s), but data records / structures can be indirectly implemented using parallel arrays, multidimensional mixed arrays or directly using classes.

I hope this e-book could be helpful and useful in practice for many users creating own web pages and beginning programming in PHP. See CHAPTER 2: Running PHP from the command line (CLI) to know how to get additional help about PHP syntax and PHP native functions.

What and how can PHP do for us?

PHP is universal programming language so it is the Functionally Complete System like C++ or C#. In each Functionally Complete System we can implement all tasks and all algorithms which belong to certain category. But we know that sometimes it is easier and sometimes it could be more difficult and complicated. Take it easy. PHP is a convenient and effective programming tool. That is why PHP is so popular and so commonly used. Using ready to use native built-in functions in PHP you can easy implement the following.

* PHP runs on various platforms (Unix, Windows, Linux, Mac OS X, so on)

* PHP is compatible with almost all servers available (IIS, Apache, so on)

* PHP supports a wide range of databases

* PHP can create, open, read, write, and close files on the server

* PHP can send and receive cookies

* PHP can collect form data and add, delete, modify data in our database

* PHP can restrict users to access some pages on your website

* PHP can encrypt data

* PHP can compress and decompress data

* PHP comes with an extension called SimpleXML to share data and to format data into structures

* Associative and mixed multidimensional arrays allow implementing easy data records, data structures and database queries.

* Another way to implement data structures / data records in PHP is using classes or parallel arrays.

PHP was originally developed in 1994 by Rasmus Lerdorf to replace a set of Perl scripts He had been using to maintain his web site. The acronym originally stood for Personal Home Page, but when he released a version to the public the following year it was recursively re-titled PHP: Hypertext Processor. Today PHP comes with numerous extension libraries available through the PEAR (PHP Extension and Application Repository) add-on. But even without these extensions, PHP comes supplied with hundreds of ready-made functions, more than in most other programming languages, making it a rich and convenient development platform.

Since 1995 PHP has evolved from a simple scripting language to a fully featured web programming language. The official implementation is now released by The PHP Group, with PHP 5.5.6 being the most recent version (released: 14 Nov 2013). The language is open source, allowing developers to extend it for their own use. PHP is the most popular server-side programming language used today. One of the reasons (and the most important one) is its platform independence. PHP has simple-to-use syntax based on C and Perl, which is easy to learn for a newcomer and for C/C++ programmers.

PHP is developed as a project of the Apache Software Foundation - thus, it works best with Apache. PHP also works properly with Microsoft IIS / PWS, iPlanet, and others.

When creating websites using PHP a Content Management System (CMS) is generally considered and used (see also: APPENDIX). A CMS tool provides a fully integrated platform for website development consisting of a backend and a frontend.

* The frontend is what visitors see when they arrive to the site,

* The backend is where the site may be configured, updated and managed by an administrator.

The most popular examples of free PHP-based CMS tools include WordPress, Joomla, ModX and Drupal.

What for? To get visitor IP, for example

Many www programmers want to know first who their visitor is. It is simple to get the visitor's IP in PHP, just using the $_SERVER['REMOTE_ADDR'] variable.

print 'Your IP is: '. $ip; ?>

If the code above returns the IP of the server, there is also another way. This function returns the visitor IP (even if the $_SERVER['REMOTE_ADDR'] contains the server IP) because it gets the IP from $_SERVER['HTTP_X_FORWARDED_FOR'].

if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER))

{ $x = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])); }

return ($x); } $myVar = get_IP(); print $myVar; ?>

This is a short and simple (but a little exciting) example of PHP power. I would like to show you at the beginning that PHP really can be interesting and useful in practice for many of us (see also geo-locaton example in Appendix). The visitor’s IP can be sent to you using HTML mailto or PHP mail() function like this:

$Name = Sender's name from a form; //senders name

$email =; //his / her e-mail

$recipient =; //recipient: You

$mail_body = The text for the mail...; //mail body

$subject = Subject for review; //subject

$header = From: . $Name . < . $email . >\r\n; //optional header

$msg = (int) mail($recipient, $subject, $mail_body, $header); // PHP mailto command :)

if($msg = 0) { echo ERROR; } else { echo OK;}

// mail() returns true if the mail is accepted to send, else - false


Inside our pages we can also of course use classic HTML-based methods to send data selected by users. For example:

POST ENCTYPE=text/plain


submit value=Mail it to me.>

(More details – see: examples in Appendix).

What do I need for beginning?

To start using PHP, you should:

* Find a web host with PHP support

* Install a web server on your own PC, and then install PHP

* or choose the most convenient for you cloud-based online IDE for PHP

(I have used IDEONE.COM and WWW.COMPILR.COM running and testing examples used in this book, but it is up to you, in accordance with your preferences. See also: Appendix: Some useful links.)

How to use a web host with PHP support?

If your server has activated PHP, just create php files, place them in your web directory, and the server will automatically parse them. Else, set up PHP on your own PC. If your server does not support PHP, you should:

* Install a web server

* Install PHP

* Install a database, such as MySQL

The official PHP website ( has installation instructions. A number of WAMP, MAMP, LAMP, XAMP (Windows/Mac/Linux, Apache, MySQL, and PHP) and similar packages have sprung up. They provide an integrated installation environment to automatically configure the various elements to properly interact with each other.

How to use PHP?

The smallest building blocks of PHP are tokens, such as numbers (3.1416), characters (’A’), strings (’a string’), variables ($two), constants (TRUE), and the special reserved words (keywords) that make up the syntax of PHP itself like if, else, for and so on. 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 AM Hello World! on a web page:

My first PHP-based page

echo Adam Majczak: PHP Manual ;

echo written for the Smashwords;

echo C. 2013 ;

echo AM Hello World! ;

echo This PHP script is really running in my browser.;


* Copy it to the Notepad

* Save it as a php1.html file

If you see correctly all the messages than your local server (Apache, IIS, localhost, WAMP, so on) works correctly. PHP should convert the code above to pure HTML like this:

My first PHP-based page

Adam Majczak: PHP Manual written for the Smashwords C. 2013 AM Hello World! This PHP script is really running in my browser.

The PHP script is running in the IDEONE.COM environment.

When you see in your browser window the My first PHP-based page only, you should turn back and correct this problem by installing the software tools described above.

To view PHP code effects in a browser the code first has to be parsed on a web server having the PHP module installed. A simple way to set up a PHP environment is to download and install a distribution of the Apache web server called XAMPP, which comes pre-installed with PHP, Perl and MySQL. This will allow you to experiment with PHP on your own computer.

After installing the web server point your browser to http://localhost to make sure that the server is on and ready. It should display the index.php file, which by default is located under C:\xampp\htdocs\index.php on Windows machines. ..\htdocs is the folder that the Apache Web Server looks to for files to serve on your domain.

The XAMPP Control Panel.


If you are using Windows Vista or Windows 7, make sure that you deactivate the User Account Control feature. To do this, select

Control Panel > User Accounts > Change User Access Control settings.

and set Never notify.

The default directory structure after XAMPP installation in Windows environment is shown below. The \htdocs this is the web root directory. All of our PHP codes will be placed in this directory.

The C:\xampp\htdocs\ path in Windows. Note that there you have the following additional and very useful components: integrated FTP server, E-mail server, mySQL database and Perl compiler.

Embedding PHP

The PHP file (a plain text file with a *.php extension) can include any HTML, as well as PHP scripting code. Begin by first entering the following standard HTML elements into the document. You can use for example Notepad, NetBeans or PHPEclipse to edit PHP source codes. First you can create an html frame like this:

PHP Code Embedded

// <-- PHP codes will be embedded here

PHP code can be embedded anywhere in a web document in one of four different ways. First, the standard notation is to delimit the PHP code by and ?>. This is called a PHP code block.

Within a PHP block the engine is said to be in PHP mode, and outside of the block the engine (interpreter) is in HTML mode. In PHP mode everything will be parsed (executed) by the PHP engine, whereas in HTML mode everything will be sent to the generated web page without any modification.

The second notation for switching to PHP mode is a shorter version where the php part is left out. Although this notation is shorter, the longer version is preferable if the PHP code needs to be portable. This is because support for the short delimiter can be disabled in the php.ini configuration file.

A third alternative possibility is to embed the PHP code with the language attribute set to php.

One remaining style is when the script is embedded between ASP tags. This style is disabled by default, but can be enabled by the PHP configuration file.

<% ... %>

The last closing tag in a script file may be omitted if the file ends in PHP mode.

Another way to place a PHP code (sometimes additionally intermixed with JavaScript) inside a HTML file is to use < script src = phpfile.php > tags like this:

alert(JavaScript code. );

Note: HTML comments can not be embedded in PHP and vice versa.

Comments in PHP

PHP has the two standard C++ notations for single-line (//) and multi-line (/* */) comments. The Perl comment notation (#) may be used to make single-line comments. A comment in PHP is a line that is not executed as a part of the program. PHP supports the three ways of commenting:

// a single line comment like C++

# a single line comment like Perl


a multiple lines comment block

that spans over more than

one line like C/C++



You can print text in PHP by either typing echo or print followed by the output. Each statement must end (as in C++) with a semicolon (;) in order to separate it from other statements. The semicolon for the last statement in a PHP block is optional.

echo AM, Hello World ; // semicolon [;] must be used

print AM, Hello World // semicolon optional


There are some differences between echo and print (print is working as a function):

* echo - can output one or more strings

* print - can only output one string, and returns always 1

So echo is a little faster comparing to print, because echo does not return any value (echo is working as a procedure).

Output can also be generated using the open delimiter. As of PHP 5.4 this syntax is valid, even if the short PHP delimiter is disabled.

AM Hello World ?>

The text output will only be visible if it is located within the HTML body element.

PHP Test

How you do it?; ?>

This script processed on the server side by PHP will generate the following HTML code to send to your browser (on the client side):

PHP Test

How you do it?

When a request is made for the