Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Introduction to PHP
Introduction to PHP
Introduction to PHP
Ebook428 pages5 hours

Introduction to PHP

Rating: 3 out of 5 stars

3/5

()

Read preview

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.

LanguageEnglish
PublisherAdam Majczak
Release dateSep 19, 2013
ISBN9781301267613
Introduction to PHP

Read more from Adam Majczak

Related to Introduction to PHP

Related ebooks

Programming For You

View More

Related articles

Reviews for Introduction to PHP

Rating: 3.2 out of 5 stars
3/5

5 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    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:

    POST ENCTYPE=text/plain

    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.

    Enjoying the preview?
    Page 1 of 1