Introduction to PHP
By Adam Majczak
3/5
()
About this ebook
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.
Read more from Adam Majczak
Introduction to PHP, Part 1, Second Edition Rating: 0 out of 5 stars0 ratingsIntroduction to PHP, Part 2, Second Edition Rating: 0 out of 5 stars0 ratingsIntroduction to PHP, Part 4, Second Edition Rating: 0 out of 5 stars0 ratingsIntroduction to PHP, Part 3, Second Edition Rating: 0 out of 5 stars0 ratingsIntroduction to PHP, Part 5, Second Edition Rating: 0 out of 5 stars0 ratingsReference to PHP, Second Edition Rating: 0 out of 5 stars0 ratings
Related to Introduction to PHP
Related ebooks
PHP for Beginners: Your Guide to Easily Learn PHP In 7 Days Rating: 4 out of 5 stars4/5Learn PHP Programming in 7Days: Ultimate PHP Crash Course For Beginners Rating: 3 out of 5 stars3/5PHP Examples Part 3 Rating: 5 out of 5 stars5/5HTML5 & CSS3 For Beginners: Your Guide To Easily Learn HTML5 & CSS3 Programming in 7 Days Rating: 4 out of 5 stars4/5HTML, CSS, Bootstrap, Php, Javascript and MySql: All you need to know to create a dynamic site Rating: 4 out of 5 stars4/5HTML & CSS For Beginners: Your Step by Step Guide to Easily HTML & CSS Programming in 7 Days Rating: 4 out of 5 stars4/5PHP & MySQL Practice It Learn It Rating: 3 out of 5 stars3/5Introduction to HTML & CSS Rating: 4 out of 5 stars4/5Learn PHP in 24 Hours Rating: 0 out of 5 stars0 ratingsPHP MySQL Development of Login Modul: 3 hours Easy Guide Rating: 5 out of 5 stars5/5P.H.P Simple C.R.U.D Design Rating: 4 out of 5 stars4/5PHP Examples Part 4 Rating: 0 out of 5 stars0 ratingsPractical Web Development Rating: 5 out of 5 stars5/5PHP Examples, Part 2 Rating: 1 out of 5 stars1/5The PHP Workshop: Learn to build interactive applications and kickstart your career as a web developer Rating: 0 out of 5 stars0 ratingsIntroduction to PHP Web Services: PHP, JavaScript, MySQL, SOAP, RESTful, JSON, XML, WSDL Rating: 0 out of 5 stars0 ratingsLearning PHP 7 Rating: 4 out of 5 stars4/5phpMyAdmin Starter Rating: 0 out of 5 stars0 ratingsJavaScript Unlocked Rating: 5 out of 5 stars5/5PHP Error Reporting: How To Do It Right Rating: 0 out of 5 stars0 ratingsJavascript For Beginners: Your Guide For Learning Javascript Programming in 24 Hours Rating: 3 out of 5 stars3/5PHP 7 Programming Blueprints Rating: 0 out of 5 stars0 ratingsHTML5,CSS3,Javascript and JQuery Mobile Programming: Beginning to End Cross-Platform App Design Rating: 5 out of 5 stars5/5Learning PHP 7 High Performance Rating: 0 out of 5 stars0 ratingsJavaScript and AJAX For Dummies Rating: 4 out of 5 stars4/5XHTML Rating: 0 out of 5 stars0 ratingsjQuery 1.3 with PHP Rating: 0 out of 5 stars0 ratingsPHP for Beginners Rating: 0 out of 5 stars0 ratingsHypertext Markup Language (HTML) Fundamentals: How to Master HTML with Ease Rating: 0 out of 5 stars0 ratings
Programming For You
Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Learn SQL in 24 Hours Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Web Designer's Idea Book, Volume 4: Inspiration from the Best Web Design Trends, Themes and Styles Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Unity from Zero to Proficiency (Beginner): Unity from Zero to Proficiency, #2 Rating: 5 out of 5 stars5/5C Programming for Beginners: Your Guide to Easily Learn C Programming In 7 Days Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Python Projects for Beginners: A Ten-Week Bootcamp Approach to Python Programming Rating: 0 out of 5 stars0 ratingsLearn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 0 out of 5 stars0 ratingsOneNote: The Ultimate Guide on How to Use Microsoft OneNote for Getting Things Done Rating: 1 out of 5 stars1/5
Reviews for Introduction to PHP
5 ratings0 reviews
Book preview
Introduction to PHP - Adam Majczak
Introduction to PHP
Adam Majczak
C. Adam Majczak, 2013, All Rights Reserved
Smashwords English Edition
E-Edition, License Notes
This e-book is licensed for your personal use only. This e-book may not be re-sold or given away to others. If you would like to share this book with another person, please purchase an additional copy for each recipient.
While every precaution has been taken in the preparation of this book, the publisher and the author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
ENGLISH EDITION
Using PHP and based on this book:
* You can check real connection speed with your remote server in any your application:
* You can implement interactive data processing in real time:
* You can generate HTML pages in real time with dynamically self-changing graphics:
* You can create interactive games in PHP to use on your Web pages,
// A. Majczak: The shortest interactive PHP game in the World :-)
* You can simply create boxes inside your web pages like this:
* You can rotate plot coordinates and drawings.
… and much more…
CONTENTS:
CHAPTER 1: Introduction to the e-book edition
Similarities and differences: PHP vs. C/C++
What and how can PHP do for us?
What for? To get visitor’s IP, for example
What do I need for beginning?
How to use a web host with PHP support?
How to use PHP?
Embedding PHP
Comments in PHP
How to use PHP interpreter online
Running PHP from the command line
Command line input (STDIN)
CHAPTER 2: PHP variables
Case sensitivity
Error messages and warnings
Data types in PHP
Using constants in PHP
Integer data type
Floating-point numbers
Bool type (Boolean values)
Null type variable and type checking in PHP
Dynamic variables
CHAPTER 3: Operators
Arithmetic operators
Assignment operator and combined operators
Pre / post - increment and decrement operators
Comparison operators
Logical operators
Base converting functions and bitwise operators
Operator precedence
CHAPTER 4: PHP Arrays, array constructor, array types in PHP
Numeric indexed arrays, runtime array size change
Associative arrays and string arrays
Character strings as 1D array
Mixed arrays
Multi-dimensional arrays, hash table
Array elements can be sorted
Internal pointer and some useful functions
CHAPTER 5: If we need conditional statements or loops
If statement (if-elseif-else) and switch-case statement
The while and do-while loops
The for and foreach loops
The break, continue and goto keywords
Filtering mask with binary operators
CHAPTER 6: PHP functions
Argument passing by value and using default values
Variable argument list
Argument passing by reference
Returning an array or modifying values by reference
Locals vs. globals
Variable scope in PHP vs. JavaScript
Math functions
Searching and sorting
Quick binary search
PHP runtime-created functions
Date and time
CHAPTER 7: Introduction to OOP
Properties
Creating an object (a class new instance)
Constructor
Destructor
Included and required file(s)
CHAPTER 8: Programming practice
Static methods
Declaring constants within classes
Magic constants
Static properties in use
Recommended OOP practice and The Gold Rule
BC Math functions vs. PHP operators
CHAPTER 9: Object-oriented programming
Inheritance – first glance
Overriding class members
Final keyword and instanceof operator
Access levels before and after inheritance
Generating HTML page using PHP functions
Generating the same HTML page using classes and methods
A few words about PHP scope
Interfaces, abstract classes and traits
Abstract data types (ADT) and the abstract keyword
Traits
CHAPTER 10: Data input in PHP
How HTML forms work
Variables and superglobal PHP arrays
Processing forms in PHP
Simple form example and a little more about form processing
Intermixing HTML and PHP
Using PHP interpreter online and JavaScript codes
PHP intermixing with JavaScript, how it works
Information Feedback: Client-Server-Client-Server dialogue
The precise Real Time Clock in PHP
CHAPTER 11: PHP interaction with operating system and file system
PHP interaction with operating systems being system-dependent
Pointer to an external process
Basic file-related functions
More about opening a file by fopen() function
SPLFileObject, SPLFileInfo objects
Directory – related functions
STDIN and STDOUT streams and piping
A simple way to place an image in PHP
How to create graphs and function plots in PHP
CHAPTER 12: Effective programming in PHP
Algorithm complexity and recursive functions
Fibonacci sequence and factorials
Programming errors
Type setting and casting to avoid some errors
CHAPTER 13: Using local storage in JavaScript and with PHP
Counting views in JavaScript on the client side
Single file PHP calculator
PHP Cookies
Creating Cookies in PHP
$_COOKIE[] array and $HTTP_COOKIE_VARS[] array
Deleting cookies
Checking a cookie value in JavaScript
Sessions
CHAPTER 14: Advanced object oriented programming
Using __set() and __get() methods
Property and function overloading
More about lambda functions and closures
Namespaces
Namespace aliases
CHAPTER 15: Data validation and error handling
Listing form variables
Error handling
Switching form On/Off using a single flag (the simplest validation)
Data validation on the client side (JavaScript)
Validation on the server side using PHP
The NaN and Infinity errors
Exception handling
CHAPTER 16: XML, TCP/IP and Real Time data processing
SimpleXML in PHP
XML processing in PHP
The DOM and SimpleXML examples
TCP/IP
How to evaluate real speed of our Client-Server feedback loop
Function call time measuring
Random numbers and a simple PHP game
CHAPTER 17: Simple examples
Shared operating memory in PHP
Login and password – why data encryption is needed
A few words about data encryption in PHP
APPENDIX
Polymorphism example
Converting relative path to absolute path
How to get visitor’s IP?
File uploading from user’s disk
Setting timeout on the client side and on the server side
Regular expressions – what it is and what for?
Creating and showing an image gallery
Drawing boxes by intermixing PHP, HTML and CSS
Drawing y = cos( x ) graph in PHP
Unicode in PHP
Simple geo-location based on IP
Some useful links
An ERROR in PHP5 discovered
Backward incompatibilities of PHP 5.5.x
A simple HEREDOC example (drawing rotation clockwise)
Besides of numerous PHP examples this e-book contains also some simple JavaScript code snippets to show how to perform data processing on the client side by JavaScript and on the server side by PHP. I have compared hereby some popular programming techniques being frequently used and providing complementary solutions. Because this e-book and these examples were written by and for programmers, PHP comes here with an extensive set of features and functions. PHP is one of the world’s most popular programming languages for web programming. If you work in the cloud, you can create, test and deploy your PHP projects from your browser using cloud IDEs.
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++
Similarities:
* 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 = example@email.com
; //his / her e-mail
$recipient = your@mail.eu
; //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:
action=mailto: adam_majczak@mydomain.eu
>
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 (PHP.net) has installation instructions. A number of WAMP, MAMP, LAMP, XAMP (Windows/Mac/Linux, Apache, MySQL, and PHP) and similar packages have sprung up.