Tutorials Class - Logo

  • PHP All Exercises & Assignments

Practice your PHP skills using PHP Exercises & Assignments. Tutorials Class provides you exercises on PHP basics, variables, operators, loops, forms, and database.

Once you learn PHP, it is important to practice to understand PHP concepts. This will also help you with preparing for PHP Interview Questions.

Here, you will find a list of PHP programs, along with problem description and solution. These programs can also be used as assignments for PHP students.

Write a program to count 5 to 15 using PHP loop

Description: Write a Program to display count, from 5 to 15 using PHP loop as given below.

Rules & Hint

  • You can use “for” or “while” loop
  • You can use variable to initialize count
  • You can use html tag for line break

View Solution/Program

5 6 7 8 9 10 11 12 13 14 15

Write a program to print “Hello World” using echo

Description: Write a program to print “Hello World” using echo only?

Conditions:

  • You can not use any variable.

View Solution /Program

Hello World

Write a program to print “Hello PHP” using variable

Description: Write a program to print “Hello PHP” using php variable?

  • You can not use text directly in echo but can use variable.

Write a program to print a string using echo+variable.

Description: Write a program to print “Welcome to the PHP World” using some part of the text in variable & some part directly in echo.

  • You have to use a variable that contains string “PHP World”.

Welcome to the PHP World

Write a program to print two variables in single echo

Description: Write a program to print 2 php variables using single echo statement.

  • First variable have text “Good Morning.”
  • Second variable have text “Have a nice day!”
  • Your output should be “Good morning. Have a nice day!”
  • You are allowed to use only one echo statement in this program.

Good Morning. Have a nice day!

Write a program to check student grade based on marks

Description:.

Write a program to check student grade based on the marks using if-else statement.

  • If marks are 60% or more, grade will be First Division.
  • If marks between 45% to 59%, grade will be Second Division.
  • If marks between 33% to 44%, grade will be Third Division.
  • If marks are less than 33%, student will be Fail.

Click to View Solution/Program

Third Division

Write a program to show day of the week using switch

Write a program to show day of the week (for example: Monday) based on numbers using switch/case statements.

  • You can pass 1 to 7 number in switch
  • Day 1 will be considered as Monday
  • If number is not between 1 to 7, show invalid number in default

It is Friday!

Write a factorial program using for loop in php

Write a program to calculate factorial of a number using for loop in php.

The factorial of 3 is 6

Factorial program in PHP using recursive function

Exercise Description: Write a PHP program to find factorial of a number using recursive function .

What is Recursive Function?

  • A recursive function is a function that calls itself.

Write a program to create Chess board in PHP using for loop

Write a PHP program using nested for loop that creates a chess board.

  • You can use html table having width=”400px” and take “30px” as cell height and width for check boxes.

Chess-board-in-PHP-using-for-loop

Write a Program to create given pattern with * using for loop

Description: Write a Program to create following pattern using for loops:

  • You can use for or while loop
  • You can use multiple (nested) loop to draw above pattern

View Solution/Program using two for loops

* ** *** **** ***** ****** ******* ********

Simple Tips for PHP Beginners

When a beginner start PHP programming, he often gets some syntax errors. Sometimes these are small errors but takes a lot of time to fix. This happens when we are not familiar with the basic syntax and do small mistakes in programs. These mistakes can be avoided if you practice more and taking care of small things.

I would like to say that it is never a good idea to become smart and start copying. This will save your time but you would not be able to understand PHP syntax. Rather, Type your program and get friendly with PHP code.

Follow Simple Tips for PHP Beginners to avoid errors in Programming

  • Start with simple & small programs.
  • Type your PHP program code manually. Do not just Copy Paste.
  • Always create a new file for new code and keep backup of old files. This will make it easy to find old programs when needed.
  • Keep your PHP files in organized folders rather than keeping all files in same folder.
  • Use meaningful names for PHP files or folders. Some examples are: “ variable-test.php “, “ loops.php ” etc. Do not just use “ abc.php “, “ 123.php ” or “ sample.php “
  • Avoid space between file or folder names. Use hyphens (-) instead.
  • Use lower case letters for file or folder names. This will help you make a consistent code

These points are not mandatory but they help you to make consistent and understandable code. Once you practice this for 20 to 30 PHP programs, you can go further with more standards.

The PHP Standard Recommendation (PSR) is a PHP specification published by the PHP Framework Interop Group.

Experiment with Basic PHP Syntax Errors

When you start PHP Programming, you may face some programming errors. These errors stops your program execution. Sometimes you quickly find your solutions while sometimes it may take long time even if there is small mistake. It is important to get familiar with Basic PHP Syntax Errors

Basic Syntax errors occurs when we do not write PHP Code correctly. We cannot avoid all those errors but we can learn from them.

Here is a working PHP Code example to output a simple line.

Output: Hello World!

It is better to experiment with PHP Basic code and see what errors happens.

  • Remove semicolon from the end of second line and see what error occurs
  • Remove double quote from “Hello World!” what error occurs
  • Remove PHP ending statement “?>” error occurs
  • Use “
  • Try some space between “

Try above changes one at a time and see error. Observe What you did and what error happens.

Take care of the line number mentioned in error message. It will give you hint about the place where there is some mistake in the code.

Read Carefully Error message. Once you will understand the meaning of these basic error messages, you will be able to fix them later on easily.

Note: Most of the time error can be found in previous line instead of actual mentioned line. For example: If your program miss semicolon in line number 6, it will show error in line number 7.

Using phpinfo() – Display PHP Configuration & Modules

phpinfo()   is a PHP built-in function used to display information about PHP’s configuration settings and modules.

When we install PHP, there are many additional modules also get installed. Most of them are enabled and some are disabled. These modules or extensions enhance PHP functionality. For example, the date-time extension provides some ready-made function related to date and time formatting. MySQL modules are integrated to deal with PHP Connections.

It is good to take a look on those extensions. Simply use

phpinfo() function as given below.

Example Using phpinfo() function

Using-phpinfo-Display-PHP-Configuration-Modules

Write a PHP program to add two numbers

Write a program to perform sum or addition of two numbers in PHP programming. You can use PHP Variables and Operators

PHP Program to add two numbers:

Write a program to calculate electricity bill in php.

You need to write a PHP program to calculate electricity bill using if-else conditions.

  • For first 50 units – Rs. 3.50/unit
  • For next 100 units – Rs. 4.00/unit
  • For next 100 units – Rs. 5.20/unit
  • For units above 250 – Rs. 6.50/unit
  • You can use conditional statements .

php assignment pdf

Write a simple calculator program in PHP using switch case

You need to write a simple calculator program in PHP using switch case.

Operations:

  • Subtraction
  • Multiplication

simple-calculator-program-in-PHP-using-switch-case

Remove specific element by value from an array in PHP?

You need to write a program in PHP to remove specific element by value from an array using PHP program.

Instructions:

  • Take an array with list of month names.
  • Take a variable with the name of value to be deleted.
  • You can use PHP array functions or foreach loop.

Solution 1: Using array_search()

With the help of  array_search()  function, we can remove specific elements from an array.

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [3]=> string(5) “april” [4]=> string(3) “may” }

Solution 2: Using  foreach()

By using  foreach()  loop, we can also remove specific elements from an array.

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [3]=> string(5) “april” [4]=> string(3) “may” }

Solution 3: Using array_diff()

With the help of  array_diff()  function, we also can remove specific elements from an array.

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [2]=> string(5) “march” [4]=> string(3) “may” }

Write a PHP program to check if a person is eligible to vote

Write a PHP program to check if a person is eligible to vote or not.

  • Minimum age required for vote is 18.
  • You can use PHP Functions .
  • You can use Decision Making Statements .

Click to View Solution/Program.

You Are Eligible For Vote

Write a PHP program to calculate area of rectangle

Write a PHP program to calculate area of rectangle by using PHP Function.

  • You must use a PHP Function .
  • There should be two arguments i.e. length & width.

View Solution/Program.

Area Of Rectangle with length 2 & width 4 is 8 .

  • Next »
  • PHP Exercises Categories
  • PHP Top Exercises
  • PHP Variables
  • PHP Decision Making
  • PHP Functions
  • PHP Operators
  • Language Reference

Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of " $a = 3 " is 3. This allows you to do some tricky things: <?php $a = ( $b = 4 ) + 5 ; // $a is equal to 9 now, and $b has been set to 4. ?>

In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic , array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example: <?php $a = 3 ; $a += 5 ; // sets $a to 8, as if we had said: $a = $a + 5; $b = "Hello " ; $b .= "There!" ; // sets $b to "Hello There!", just like $b = $b . "There!"; ?>

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop.

An exception to the usual assignment by value behaviour within PHP occurs with object s, which are assigned by reference. Objects may be explicitly copied via the clone keyword.

Assignment by Reference

Assignment by reference is also supported, using the " $var = &$othervar; " syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.

Example #1 Assigning by reference

The new operator returns a reference automatically, as such assigning the result of new by reference is an error.

The above example will output:

More information on references and their potential uses can be found in the References Explained section of the manual.

Arithmetic Assignment Operators

Example Equivalent Operation
$a += $b $a = $a + $b Addition
$a -= $b $a = $a - $b Subtraction
$a *= $b $a = $a * $b Multiplication
$a /= $b $a = $a / $b Division
$a %= $b $a = $a % $b Modulus
$a **= $b $a = $a ** $b Exponentiation

Bitwise Assignment Operators

Example Equivalent Operation
$a &= $b $a = $a & $b Bitwise And
$a |= $b $a = $a | $b Bitwise Or
$a ^= $b $a = $a ^ $b Bitwise Xor
$a <<= $b $a = $a << $b Left Shift
$a >>= $b $a = $a >> $b Right Shift

Other Assignment Operators

Example Equivalent Operation
$a .= $b $a = $a . $b String Concatenation
$a ??= $b $a = $a ?? $b Null Coalesce
  • arithmetic operators
  • bitwise operators
  • null coalescing operator

Improve This Page

User contributed notes 4 notes.

To Top

  • ▼PHP Exercises
  • Introduction
  • Basic Algorithm
  • Exception Handling
  • File Handling
  • Cookies and Sessions
  • Object Oriented Programming
  • Regular Expression
  • Searching and Sorting
  • ▼PHP Challenges
  • Challenges-1
  • ..More to come..
  • PHP Exercises, Practice, Solution

What is PHP?

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with PHP .

Hope, these exercises help you to improve your PHP coding skills. Currently, following sections are available, we are working hard to add more exercises. Happy Coding!

Note: It's fine if you are playing around with PHP codes with the help of an online PHP editor, to enjoy a full-fledged PHP environment (since online editors have several caveats, e.g. embedding PHP within HTML) up and running on your own machine is much better of an option to learn PHP. Please read our installing PHP on Windows and Linux if you are unfamiliar to PHP installation.

List of PHP Exercises :

  • PHP Basic : 102 Exercises with Solution
  • PHP Basic Algorithm: 136 Exercises with Solution
  • PHP Error and Exception Handling [ 10 exercises with solution ]
  • PHP File Handling [ 18 exercises with solution ]
  • PHP Cookies and Sessions Exercises Practice Solution [ 16 exercises with solution ]
  • PHP OOP Exercises Practice Solution [ 19 exercises with solution ]
  • PHP arrays : 59 Exercises with Solution
  • PHP for loop : 38 Exercises with Solution
  • PHP functions : 6 Exercises with Solution
  • PHP classes : 7 Exercises with Solution
  • PHP Regular Expression : 7 Exercises with Solution
  • PHP Date : 28 Exercises with Solution
  • PHP String : 26 Exercises with Solution
  • PHP Math : 12 Exercises with Solution
  • PHP JSON : 4 Exercises with Solution
  • PHP Searching and Sorting Algorithm : 17 Exercises with Solution
  • More to Come !

PHP Challenges :

  • PHP Challenges: Part -1 [ 1- 25]
  • More to come

Note : You may accomplish the same task (solution of the exercises) in various ways, therefore the ways described here are not the only ways to do stuff. Rather, it would be great, if this helps you anyway to choose your own methods.

[ Want to contribute to PHP exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

List of Exercises with Solutions :

  • HTML CSS Exercises, Practice, Solution
  • JavaScript Exercises, Practice, Solution
  • jQuery Exercises, Practice, Solution
  • jQuery-UI Exercises, Practice, Solution
  • CoffeeScript Exercises, Practice, Solution
  • Twitter Bootstrap Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution
  • C# Sharp Programming Exercises, Practice, Solution
  • Python Exercises, Practice, Solution
  • Java Exercises, Practice, Solution
  • SQL Exercises, Practice, Solution
  • MySQL Exercises, Practice, Solution
  • PostgreSQL Exercises, Practice, Solution
  • SQLite Exercises, Practice, Solution
  • MongoDB Exercises, Practice, Solution

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Handwritten PHP notes pdf free download lecture notes bca

Php notes pdf.

Free PHP notes pdf are provided here for PHP students so that they can prepare and score high marks in their PHP exam.

In these free PHP notes pdf, we will study the ability to design and develop a dynamic website using technologies like HTML, CSS, JavaScript, PHP, and MySQL on a platform like WAMP/XAMP/LAMP.

We have provided complete PHP handwritten notes pdf for any university student of BCA, MCA, B.Sc, B.Tech CSE, M.Tech branch to enhance more knowledge about the subject and to score better marks in their PHP exam.

Free PHP notes pdf are very useful for PHP students in enhancing their preparation and improving their chances of success in PHP exam.

These free PHP pdf notes will help students tremendously in their preparation for PHP exam. Please help your friends in scoring good marks by sharing these free PHP handwritten notes pdf from below links:

TutorialsDuniya Store College Banner

Topics in our PHP Notes PDF

The topics we will cover in these PHP Notes PDF will be taken from the following list:

Introduction to Static and Dynamic Websites (Website Designing and Anatomy of Webpage).

Introduction to HTML and CSS (Basic Tags, Lists, Handling Graphics, Tables, Linking, Frames, Forms), Introduction to DOM.

Introduction to JavaScript (Basic Programming Techniques & Constructs, GET/POST Methods, Operators, Functions, DOM Event handling, Forms Validation, Cookies), Inter-page communication, and form data handling using JavaScript.

Introduction to PHP (Working, Difference with other technologies like JSP and ASP), PHP Programming Techniques (Data types, Operators, Arrays, Loops, Conditional statements, Functions, Regular expressions).

Form Data Handling with PHP, Database connectivity and handling using PHP-MySQL

PHP Notes PDF FREE Download

PHP students can easily make use of all these complete PHP notes pdf by downloading them from below links:

PHP Handwritten Notes.pdf

PHP Handwritten Notes.pdf

PHP handwritten notes pdf

PHP handwritten notes pdf Source: w3schools.com

PHP lecture notes pdf

PHP lecture notes pdf Source: tutorialspoint.com

PHP notes pdf free download

PHP notes pdf free download Source: javatpoint.com

PHP lecture notes pdf Source: phptpoint.com

PHP notes for bca

PHP notes for bca Source: guru99.com

php programming notes pdf download

php programming notes pdf download Source: goalkicker.com

PHP notes for bca Source: tutorialrepublic.com

bca php notes pdf

bca php notes pdf Source: php.net

TutorialsDuniya whatsapp channel banner

How to Download FREE PHP Notes PDF?

PHP students can easily download free PHP notes pdf by following the below steps:

  • Visit TutorialsDuniya.com to download free PHP notes pdf
  • Select ‘College Notes’ and then select ‘Computer Science Course’
  • Select ‘PHP Notes’
  • Now, you can easily view or download free PHP handwritten notes pdf

We have listed the best PHP Books that can help in your PHP exam preparation: 

PHP: The Complete Reference

PHP: The Complete Reference

Get this Book

PHP and MySQL for Dynamic Web Sites

PHP and MySQL for Dynamic Web Sites

PHP and MySQL Web Development

PHP and MySQL Web Development

PHP, MySQL & JavaScript All - in - One For Dummies

PHP, MySQL & JavaScript All – in – One For Dummies

PHP: A Beginner's Guide

PHP: A Beginner’s Guide

PHP for the Web

PHP for the Web

Learning PHP

Learning PHP

PHP Advanced and Object-Oriented Programming

PHP Advanced and Object-Oriented Programming

Benefits of FREE PHP Notes PDF

Free PHP notes pdf provide learners with a flexible and efficient way to study and reference PHP concepts. Benefits of these complete free PHP pdf notes are given below:

  • Accessibility: These free PHP handwritten notes pdf files can be easily accessed on various devices that makes it convenient for students to study PHP wherever they are.
  • Printable: These PHP free notes pdf can be printed that allows learners to have physical copies of their PHP notes for their reference and offline reading.
  • Structured content: These free PHP notes pdf are well-organized with headings, bullet points and formatting that make complex topics easier to follow and understand.
  • Self-Paced Learning: Free PHP handwritten notes pdf offers many advantages for both beginners and experienced students that make it a valuable resource for self-paced learning and reference.
  • Visual Elements: These free PHP pdf notes include diagrams, charts and illustrations to help students visualize complex concepts in an easier way.

We hope our free PHP notes pdf has helped you and please share these PHP handwritten notes free pdf with your friends as well 🙏

Download FREE Study Material App for school and college students for FREE high-quality educational resources such as notes, books, tutorials, projects and question papers.

If you have any questions feel free to reach us at [email protected] and we will get back to you at the earliest.

TutorialsDuniya.com wishes you Happy Learning! 🙂

Computer Science Notes

  • Design and Analysis of Algorithms Notes
  • Artificial Intelligence Notes
  • C++ Programming Notes
  • Combinatorial Optimization Notes
  • Computer Graphics Notes
  • Computer Networks Notes
  • Computer System Architecture Notes
  • Data Analysis & Visualization Notes
  • Data Mining Notes
  • Data Science Notes
  • Data Structures Notes
  • Deep Learning Notes
  • Digital Image Processing Notes
  • Discrete Mathematics Handwritten Notes
  • Information Security Notes
  • Internet Technologies Notes
  • Java Programming Notes
  • Machine Learning Notes
  • Microprocessor and Microcontrollers Notes
  • Operating System Notes
  • Operational Research Notes
  • PHP Lecture Notes
  • Python Programming Notes
  • R Programming Notes
  • Software Engineering Notes
  • System Programming Notes
  • Theory of Computation Notes
  • Unix Network Programming Notes
  • Web Design & Development Notes

PHP Notes FAQs

Q: Where can I get complete PHP Notes pdf FREE Download?

A: TutorialsDuniya.com have provided complete PHP free Notes pdf so that students can easily download and score good marks in your PHP exam.

Q: How to download PHP notes pdf?

A: PHP students can easily make use of all these complete free PHP pdf notes by downloading them from TutorialsDuniya.com

Software Engineering Projects with Source & Documentation

Handwritten PHP notes pdf free download lecture notes bca

You will always find the updated list of top and best free Software Engineering projects with source code in an easy and quick way. Our Free Software Engineering projects list has projects for beginners, intermediates as well as experts to learn in 2023.

URL: https://www.tutorialsduniya.com/software-engineering-projects-pdf/

Author: Delhi University

TutorialsDuniya Store College Banner

PHP Cheat Sheet

Nick Schäferhoff

Nick Schäferhoff

Editor in Chief

Our PHP cheat sheet aims to help anyone trying to get proficient in or improve their knowledge of PHP. The programming language is among the most popular in web development. It’s in the heart of WordPress, the world’s most popular CMS , and also forms the base of other platforms like Joomla and Drupal . (Don’t miss our comparison of the three .)

Aside from that, PHP is an Open Source and thus free to use. Since its inception in 1995, it has had several releases. The latest version, PHP 7.4, came out in December 2021.

PHP is a server-side language, meaning that it executes on the server, not in the user’s browser (as opposed to, for example, Javascript ). PHP scripts produce HTML which is then passed on to the browser for interpretation. Consequently, the user doesn’t see the code itself but only the result.

php cheat sheet

The programming language is relatively easy to learn for beginners, but it also offers a lot of advanced possibilities for veteran programmers.

For that reason, the following PHP cheat sheet is suitable for you no matter where you are in your journey. It covers the most important PHP concepts and functions and acts as a quick reference guide for those using PHP for web development.

We have a lot to cover, so let’s get right into it. If that’s not enough for you, we also have cheat sheets for HTML , CSS , and jQuery as well as the aforementioned  Javascript .

  • Download Link

PHP Cheat Sheet – The Basics

We are starting off with the basics – how to declare PHP in a file, write comments, and output data.

Including PHP in a File

PHP files end in .php . Besides PHP itself, they can contain text, HTML, CSS, and JavaScript. In order for a browser to recognize PHP, you need to wrap it in brackets: <?php and ?> . Consequently, you can execute PHP on a page:

Writing Comments

Like many other languages, PHP also has the ability to add comments. This is important for annotating your code for human readers but in a way that the browser doesn’t try to execute it. In PHP, you have several ways for that:

  • // — Denotes comments that only span one line
  • # — Another way of producing single-line comments
  • /* ...*/ — Everything between /* and */ is not executed, also works across several lines

A common example of the use of comments is WordPress theme headers:

Outputting Data

In PHP, data is commonly output using echo or print . For example, the title of this blog post might be displayed on a page like this:

The two commands echo and print are pretty much the same. The only difference is that the former has no return value and can take several parameters, while the latter has a return value of 1 and can only take one argument.

An important note: Like all other PHP commands, functions echo and print are not case sensitive. That means that when you write ECHO , EcHo , eCHO or any other variation, they will continue to work. As you will learn further on, that doesn’t apply to everything.

Writing PHP Functions

Functions are shortcuts for commonly used chunks of code. They make programming much easier because you don’t have to re-use long code snippets. Instead, you create them once and use the shortcuts when you need them.

It’s possible to create your own PHP functions but there also many built into the programming language. Much of this PHP cheat sheet is devoted to that.

The basic syntax to create a function:

Quick explanation: the first part is the function of a name (reminder: function names are not case sensitive). After that, everything between the curly braces is what the function does when called.

Variables and Constants

Similarly to most other programming languages, PHP lets you work with variables and constants. These are pieces of code that store different kinds of information.

Defining Variables

To do anything with variables, you first need to define them. In PHP, you denote a variable using the $ sign and assign its value using = . A typical example:

A few important points:

  • Variables need to start with a letter or underscore ( _ ) and can only be comprised of alpha-numeric characters
  • PHP variables are case sensitive, that means $myVar and $myvar are not the same thing
  • If your variable consists of more than one word either write it  $my_variable or $myVariable

Types of Data

Variables can take on different types of data:

  • Integers — Integers are non-decimal numbers between -2,147,483,648 and ,147,483,647. They must have at least one digit and no decimal point. It can be in decimal, hexadecimal, or octal.
  • Floats — This is the name for numbers with a decimal point or in exponential form.
  • Strings — This simply means text. We will talk about it in detail further below.
  • Boolean values — Meaning true/false statements.
  • Arrays — Arrays are variables that store several values. We will talk about them in detail further below.
  • Objects — Objects store both data and information on how to process it.
  • Resources — These are references to functions and resources outside of PHP.
  • NULL — A variable that is NULL doesn’t have any value.

There is no need to declare PHP variables in a certain way. They automatically take on the type of data they contain.

Variable Scope

Variables can be available in different scopes, meaning the part of a script you can access them. This can be global , local and static .

Any variable declared outside of a function is available globally. That means it can be accessed outside of a function as well.

If you declare a variable inside a function, it will have a local scope. The consequence is that it can only be accessed within that function.

A way around this is to prepend a local variable with global . That way, it becomes part of the global scope.

In both cases, the variable becomes part of the $GLOBALS variable mentioned below.

Finally, it’s also possible to add static in front of a local variable. That way, it won’t be deleted after its function is executed and can be reused.

Predefined Variables

PHP also comes with a number of default variables called superglobals . That’s because they are accessible from anywhere, regardless of scope.

  • $GLOBALS — Used to access global variables from anywhere inside a PHP script
  • $_SERVER — Contains information about the locations of headers, paths, and scripts
  • $_GET — Can collect data that was sent in the URL or submitted in an HTML form
  • $_POST — Used to gather data from an HTML form and to pass variables
  • $_REQUEST — Also collects data after submitting an HTML form

Variable-Handling Functions

Aside from that, there are a whole bunch of functions to work with variables:

  • boolval — Used to retrieve the boolean value of a variable
  • debug_zval_dump — Outputs a string representation of an internal zend value
  • empty — Checks whether a variable is empty or not
  • floatval — Get the float value of a variable ( doubleval is another possibility)
  • get_defined_vars — Returns an array of all defined variables
  • get_resource_type — Returns the resource type
  • gettype — Retrieves the variable type
  • import_request_variables — Import GET/POST/Cookie variables into the global scope
  • intval — Find the integer value of a variable
  • is_array — Checks whether a variable is an array
  • is_bool — Finds out if a variable is a boolean
  • is_callable — Verify whether you can call the contents of a variable as a function
  • is_countable — Check whether the contents of a variable are countable
  • is_float — Find out if the type of a variable is float, alternatives: is_double and is_real
  • is_int — Check if the type of a variable is an integer, is_integer and is_long also works
  • is_iterable — Verify that a variable’s content is an iterable value
  • is_null — Checks whether a variable’s value is NULL
  • is_numeric — Find out if a variable is a number or a numeric string
  • is_object — Determines whether a variable is an object
  • is_resource — Check if a variable is a resource
  • is_scalar — Tests if a variable is a scalar
  • is_string — Find out whether the type of a variable is a string
  • isset — Determine if a variable has been set and is not NULL
  • print_r — Provides human-readable information about a variable
  • serialize — Generates a representation of a value that is storable
  • settype — Sets a variable’s type
  • strval — Retrieves the string value of a variable
  • unserialize — Creates a PHP value from a stored representation
  • unset — Unsets a variable
  • var_dump — Dumps information about a variable
  • var_export — Outputs or returns a string representation of a variable that can be parsed

Aside from variables, you can also define constants which also store values. In contrast to variables their value can not be changed, it’s locked in.

In PHP you can define a constant:

The first is the name, the second the constant’s value and the third parameter whether its name should be case sensitive (the default is false ).

Constants are useful since they allow you to change the value for an entire script in one place instead of having to replace every instance of it. They are also global in nature, meaning they can be accessed from anywhere.

Aside from user-defined constants, there also a number of default PHP constants:

  • __LINE__ — Denotes the number of the current line in a file
  • __FILE__ — Is the full path and filename of the file
  • __DIR__ — The directory of the file
  • __FUNCTION__ — Name of the function
  • __CLASS__ — Class name, includes the namespace it was declared in
  • __TRAIT__ — The trait name, also includes the namespace
  • __METHOD__ —  The class method name
  • __NAMESPACE__ — Name of the current namespace

PHP Arrays – Grouped Values

Arrays are a way to organize several values in a single variable so that they can be used together. While functions are for blocks of code, arrays are for the values – a placeholder for larger chunks of information.

In PHP there are different types of arrays:

  • Indexed arrays – Arrays that have a numeric index
  • Associative arrays – Arrays where the keys are named
  • Multidimensional arrays – Arrays that contain one or more other arrays

Declaring an Array in PHP

Arrays in PHP are created with the array() function.

Array keys can either be strings or integers.

Array Functions

PHP offers a multitude of default functions for working with arrays:

  • array_change_key_case — Changes all keys in an array to uppercase or lowercase
  • array_chunk — Splits an array into chunks
  • array_column — Retrieves the values from a single column in an array
  • array_combine — Merges the keys from one array and the values from another into a new array
  • array_count_values — Counts all values in an array
  • array_diff — Compares arrays, returns the difference (values only)
  • array_diff_assoc — Compares arrays, returns the difference (values and keys)
  • array_diff_key — Compares arrays, returns the difference (keys only)
  • array_diff_uassoc — Compares arrays (keys and values) through a user callback function
  • array_diff_ukey — Compares arrays (keys only) through a user callback function
  • array_fill — Fills an array with values
  • array_fill_keys — Fills an array with values, specifying keys
  • array_filter — Filters the elements of an array via a callback function
  • array_flip — Exchanges all keys in an array with their associated values
  • array_intersect — Compare arrays and return their matches (values only)
  • array_intersect_assoc — Compare arrays and return their matches (keys and values)
  • array_intersect_key — Compare arrays and return their matches (keys only)
  • array_intersect_uassoc — Compare arrays via a user-defined callback function (keys and values)
  • array_intersect_ukey — Compare arrays via a user-defined callback function (keys only)
  • array_key_exists — Checks if a specified key exists in an array, alternative: key_exists
  • array_keys — Returns all keys or a subset of keys in an array
  • array_map — Applies a callback to the elements of a given array
  • array_merge — Merge one or several arrays
  • array_merge_recursive — Merge one or more arrays recursively
  • array_multisort — Sorts of multiple or multi-dimensional arrays
  • array_pad — Inserts a specified number of items (with a specified value) into an array
  • array_pop — Deletes an element from the end of an array
  • array_product — Calculate the product of all values in an array
  • array_push — Push one or several elements to the end of the array
  • array_rand — Pick one or more random entries out of an array
  • array_reduce — Reduce the array to a single string using a user-defined function
  • array_replace — Replaces elements in the first array with values from following arrays
  • array_replace_recursive — Recursively replaces elements from later arrays into the first array
  • array_reverse — Returns an array in reverse order
  • array_search — Searches the array for a given value and returns the first key if successful
  • array_shift — Shifts an element from the beginning of an array
  • array_slice — Extracts a slice of an array
  • array_splice — Removes a portion of the array and replaces it
  • array_sum — Calculate the sum of the values in an array
  • array_udiff — Compare arrays and return the difference using a user function (values only)
  • array_udiff_assoc — Compare arrays and return the difference using default and a user function (keys and values)
  • array_udiff_uassoc — Compare arrays and return the difference using two user functions (values and keys)
  • array_uintersect — Compare arrays and return the matches via user function (values only)
  • array_uintersect_assoc — Compare arrays and return the matches via a default user function (keys and values)
  • array_uintersect_uassoc — Compare arrays and return the matches via two user functions (keys and values)
  • array_unique — Removes duplicate values from an array
  • array_unshift — Adds one or more elements to the beginning of an array
  • array_values — Returns all values of an array
  • array_walk — Applies a user function to every element in an array
  • array_walk_recursive — Recursively applies a user function to every element of an array
  • arsort — Sorts an associative array in descending order according to the value
  • asort — Sorts an associative array in ascending order according to the value
  • compact — Create an array containing variables and their values
  • count — Count all elements in an array, alternatively use sizeof
  • current — Returns the current element in an array, an alternative is pos
  • each — Return the current key and value pair from an array
  • end — Set the internal pointer to the last element of an array
  • extract — Import variables from an array into the current symbol table
  • in_array — Checks if a value exists in an array
  • key — Fetches a key from an array
  • krsort — Sorts an associative array by key in reverse order
  • ksort — Sorts an associative array by key
  • list — Assigns variables as if they were an array
  • natcasesort — Sorts an array using a “natural order” algorithm independent of case
  • natsort — Sorts an array using a “natural order” algorithm
  • next — Advance the internal pointer of an array
  • prev — Move the internal array pointer backward
  • range — Creates an array from a range of elements
  • reset — Set the internal array pointer to its first element
  • rsort — Sort an array in reverse order
  • shuffle — Shuffle an array
  • sort — Sorts an indexed array in ascending order
  • uasort — Sorts an array with a user-defined comparison function
  • uksort — Arrange an array by keys using a user-defined comparison function
  • usort — Categorize an array by values using a comparison function defined by the user

PHP Strings

In programming, speech strings are nothing more than text. As we have settled earlier, they are also a valid value for variables.

Defining Strings

In PHP there are several ways to define strings:

  • Single quotes — This is the simplest way. Just wrap your text in ' markers and PHP will handle it as a string.
  • Double quotes — As an alternative you can use " . When you do, it’s possible to use the escape characters below to display special characters.
  • heredoc — Begin a string with <<< and an identifier, then put the string in a new line. Close it in another line by repeating the identifier. heredoc behaves like double-quoted strings.
  • nowdoc — Is what heredoc is for double-quoted strings but for single quotes. It works the same way and eliminates the need for escape characters.

Note: Strings can contain variables, arrays, and objects.

Escape Characters

  • \n — Linefeed
  • \r — Carriage return
  • \t — Horizontal tab
  • \v — Vertical tab
  • \e — Escape
  • \f — Form feed
  • \\ — Backslash
  • \$ — Dollar sign
  • /' — Single quote
  • \" — Double quote
  • \[0-7]{1,3} — Character in octal notation
  • \x[0-9A-Fa-f]{1,2} — Character in hexadecimal notation
  • \u{[0-9A-Fa-f]+} — String as UTF-8 representation

String Functions

  • addcslashes() — Returns a string with backslashes in front of specified characters
  • addslashes() — Returns a string with backslashes in front of characters that need to be escaped
  • bin2hex() — Converts a string of ASCII characters to hexadecimal values
  • chop() — Removes space or other characters from the right end of a string
  • chr() — Returns a character from a specified ASCII value
  • chunk_split() — Splits a string into a series of smaller chunks
  • convert_cyr_string() — Converts a string from a Cyrillic character set to another
  • convert_uudecode() — Decodes a uuencoded string
  • convert_uuencode() — Encodes a string using uuencode
  • count_chars() — Returns information about the characters in a string
  • crc32() — Calculates a 32-bit CRC for a string
  • crypt() — Returns a hashed string
  • echo() or echo '' — Outputs one or several strings
  • explode() — Breaks down a string into an array
  • fprintf() — Writes a formatted string to a specified output stream
  • get_html_translation_table() — Returns the translation table used by htmlspecialchars() and htmlentities()
  • hebrev() — Transforms Hebrew text to visual text
  • hebrevc() — Converts Hebrew text to visual text and implements HTML line breaks
  • hex2bin() — Translate hexadecimal values to ASCII characters
  • html_entity_decode() — Turns HTML entities to characters
  • htmlentities() — Converts characters to HTML entities
  • htmlspecialchars_decode() — Transforms special HTML entities to characters
  • htmlspecialchars() — Switches predefined characters to HTML entities
  • implode() — Retrieves a string from the elements of an array, same as join()
  • lcfirst() — Changes a string’s first character to lowercase
  • levenshtein() — Calculates the Levenshtein distance between two strings
  • localeconv() — Returns information about numeric and monetary formatting for the locale
  • ltrim() — Removes spaces or other characters from the left side of a string
  • md5() — Calculates the MD5 hash of a string and returns it
  • md5_file() — Calculates the MD5 hash of a file
  • metaphone() — Provides the metaphone key of a string
  • money_format() — Returns a string as a currency string
  • nl_langinfo() — Gives specific locale information
  • nl2br() — Inserts HTML line breaks for each new line in a string
  • number_format() — Formats a number including grouped thousands
  • ord() — Returns the ASCII value of a string’s first character
  • parse_str() — Parses a string into variables
  • print() — Outputs one or several strings
  • printf() — Outputs a formatted string
  • quoted_printable_decode() — Converts a quoted-printable string to 8-bit binary
  • quoted_printable_encode() — Goes from 8-bit string to a quoted-printable string
  • quotemeta() — Returns a string with a backslash before metacharacters
  • rtrim() — Strips whitespace or other characters from the right side of a string
  • setlocale() — Sets locale information
  • sha1() — Calculates a string’s SHA-1 hash
  • sha1_file() — Does the same for a file
  • similar_text() — Determines the similarity between two strings
  • soundex() — Calculates the soundex key of a string
  • sprintf() — Returns a formatted string
  • sscanf() — Parses input from a string according to a specified format
  • str_getcsv() — Parses a CSV string into an array
  • str_ireplace() — Replaces specified characters in a string with specified replacements (case-insensitive)
  • str_pad() — Pads a string to a specified length
  • str_repeat() — Repeats a string a preset number of times
  • str_replace() — Replaces specified characters in a string (case-sensitive)
  • str_rot13() — Performs ROT13 encoding on a string
  • str_shuffle() — Randomly shuffles the characters in a string
  • str_split() — Splits strings into arrays
  • str_word_count() — Returns the number of words in a string
  • strcasecmp() — Case-insensitive comparison of two strings
  • strcmp() — Binary safe string comparison (case sensitive)
  • strcoll() — Compares two strings based on locale
  • strcspn() — Returns the number of characters found in a string before the occurrence of specified characters
  • strip_tags() — Removes HTML and PHP tags from a string
  • stripcslashes() — Opposite of addcslashes()
  • stripslashes() — Opposite of addslashes()
  • stripos() — Finds the position of the first occurrence of a substring within a string (case insensitive)
  • stristr() — Case-insensitive version of strstr()
  • strlen() — Returns the length of a string
  • strnatcasecmp() — Case-insensitive comparison of two strings using a “natural order” algorithm
  • strnatcmp() — Same as the aforementioned but case sensitive
  • strncasecmp() — String comparison of a defined number of characters (case insensitive)
  • strncmp() — Same as above but case-sensitive
  • strpbrk() — Searches a string for any number of characters
  • strpos() — Returns the position of the first occurrence of a substring in a string (case sensitive)
  • strrchr() — Finds the last occurrence of a string within another string
  • strrev() — Reverses a string
  • strripos() — Finds the position of the last occurrence of a string’s substring (case insensitive)
  • strrpos() — Same as strripos() but case sensitive
  • strspn() — The number of characters in a string with only characters from a specified list
  • strstr() — Case-sensitive search for the first occurrence of a string inside another string
  • strtok() — Splits a string into smaller chunks
  • strtolower() — Converts all characters in a string to lowercase
  • strtoupper() — Same but for uppercase letters
  • strtr() — Translates certain characters in a string, alternative: strchr()
  • substr() — Returns a specified part of a string
  • substr_compare() — Compares two strings from a specified start position up to a certain length, optionally case sensitive
  • substr_count() — Counts the number of times a substring occurs within a string
  • substr_replace() — Replaces a substring with something else
  • trim() — Removes space or other characters from both sides of a string
  • ucfirst() — Transforms the first character of a string to uppercase
  • ucwords() — Converts the first character of every word in a string to uppercase
  • vfprintf() — Writes a formatted string to a specified output stream
  • vprintf() — Outputs a formatted string
  • vsprintf() — Writes a formatted string to a variable
  • wordwrap() — Shortens a string to a given number of characters

PHP Operators

Operators allow you to perform operations with values, arrays, and variables. There are several different types.

Arithmetic Operators

Your standard mathematic operators.

  • + — Addition
  • - — Subtraction
  • * — Multiplication
  • / — Division
  • % — Modulo (the remainder of value divided by another)
  • ** — Exponentiation

Assignment Operators

Besides the standard assignment operator ( = ), you also have the following options:

  • += — a += b is the same as a = a + b
  • -= — a -= b is the same as a = a – b
  • *= — a *= b is the same as a = a * b
  • /= — a /= b is the same as a = a / b
  • %= — a %= b is the same as a = a % b

Comparison Operators

  • == — Equal
  • === — Identical
  • != — Not equal
  • <> — Not equal
  • !== — Not identical
  • < — Less than
  • > — Greater than
  • <= — Less than or equal to
  • >= — Greater than or equal to
  • <=> — Less than, equal to, or greater than

Logical Operators

  • and — And
  • or — Or
  • xor — Exclusive or
  • ! — Not
  • && — And
  • || — Or

Bitwise Operators

  • & — And
  • | — Or (inclusive or)
  • ^ — Xor (exclusive or)
  • ~ — Not
  • << — Shift left
  • >> — Shift right

Error Control Operator

You can use the @ sign to prevent expressions from generating error messages. This is often important for security reasons, for example, to keep confidential information safe.

Execution Operator

PHP supports one execution operator, which is `` (backticks). These are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command.

Increment/Decrement Operators

  • ++$v — Increments a variable by one, then returns it
  • $v++ — Returns a variable, then increments it by one
  • --$v — Decrements the variable by one, returns it afterward
  • $v-- — Returns the variable then decrements it by one

String Operators

  • . — Used to concatenate (mean combine) arguments
  • .= — Used to append the argument on the right to the left-side argument

Loops in PHP

Loops are very common in programming. They allow you to run through the same block of code under different circumstances. PHP has several different ones.

This type goes through a block of code a specified number of times:

Foreach Loop

A loop using foreach runs through each element in an array:

Loops through a block of code as long as a specified condition is true.

Do…While Loop

The final PHP loop runs a code snippet once, then repeats the loop as long as the given condition is true.

Conditional Statements

If/else statements are similar to loops. They are statements for running code only under certain circumstances. You have several options:

If Statement

Executes code if one condition is true.

If…Else

Runs a piece of code if a condition is true and another if it is not.

If…Elseif…Else

Executes different code snippets for more than two conditions.

Switch Statement

Selects one of several blocks of code to execute.

Working with Forms in PHP

PHP is often used for handling web forms. In particular, the aforementioned $_GET and $_POST help to collect data sent via a form. Both are able to catch values from input fields, however, their usage differs.

Using GET vs POST

GET collects data via URL parameters. That means all variable names and their values are contained in the page address.

The advantage of this is that you’re able to bookmark the information. Keep in mind that it also means that the information is visible to everyone. For that reason, GET is not suitable for sensitive information such as passwords. It also limits the amount of data that can be sent in ca 2000 characters.

POST, on the other hand, uses the HTTP POST method to pass on variables. This makes the data invisible to third parties, as it is sent in the HTTP body. You are not able to bookmark it.

With POST, there are no limits to the amount of information you can send. Aside from that, it also has advanced functionality and is therefore preferred by developers.

Form Security

The most important issue when it comes to web forms is security. If not set up properly, they are vulnerable to cross-scripting attacks. The hackers add scripts to unsecured web forms to use them for their own purpose.

PHP also offers tools to thwart those attacks, namely:

  • htmlspecialchars()
  • stripslashes()

You will notice that we have encountered all of these functions in the previous section on strings. When you include them in the script that collects the form data, you can effectively strip harmful scripts of the characters they need for functioning, rendering them unusable.

Required Fields, Error Messages and Data Validation

Aside from that, PHP is able to define required fields (you can’t submit the form without filling them out), display error messages if some information is missing and to validate data. We have already talked about the necessary tools to do so.

For example, you can simply define variables for your form fields and use the empty() function to check if they have values. After that, create a simple if/else statement to either send the submitted data or output an error message.

The next step is to check the submitted data for validity. For that, PHP offers a number of filters such as FILTER_VALIDATE_EMAIL to make sure a submitted email address has the right format.

Regular Exprressions (RegEx)

$exp = "/w3schools/i";

RegEx Functions

preg_match()

Returns 1 if the pattern was found in the string and 0 if not

preg_match_all()

Returns the number of times the pattern was found in the string, which may also be 0

preg_replace()

Returns a new string where matched patterns have been replaced with another string

RegEx Modifiers

Performs a case-insensitive search

Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line)

Enables correct matching of UTF-8 encoded patterns

RegEx Patterns

[abc] – Find one character from the options between the brackets

[^abc] – Find any character NOT between the brackets

[0-9] – Find one character from the range 0 to 9

Metacharacters

Find a match for any one of the patterns separated by | as in: cat|dog|fish

Find just one instance of any character

Finds a match as the beginning of a string as in: ^Hello

Finds a match at the end of the string as in: World$

Find a digit

Find a whitespace character

Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b

Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers

Matches any string that contains at least one n

Matches any string that contains zero or more occurrences of n

Matches any string that contains zero or one occurrences of n

Matches any string that contains a sequence of X n’s

Matches any string that contains a sequence of X to Y n’s

Matches any string that contains a sequence of at least X n’s

Use parentheses ( ) to apply quantifiers to entire patterns. They cal also be used to select parts of the pattern to be used as a match.

PHP Functions

  • A function is a block of statements that can be used repeatedly in a program.
  • A function will not execute automatically when a page loads.
  • A function will be executed by a call to the function.

Function Arguments

Default argument value, returning values, php filters.

Filters are used to validate and filter data that is coming from insecure sources. As mentioned, a common example is user input. PHP offers a number of filter functions and constants for that:

Filter Functions

  • filter_has_var() — Checks if a variable of the specified type exists
  • filter_id() — Returns the ID belonging to a named filter
  • filter_input() — Retrieves a specified external variable by name and optionally filters it
  • filter_input_array() — Pulls external variables and optionally filters them
  • filter_list() — Returns a list of all supported filters
  • filter_var_array() — Gets multiple variables and optionally filters them
  • filter_var() — Filters a variable with a specified filter

Filter Constants

  • FILTER_VALIDATE_BOOLEAN — Validates a boolean
  • FILTER_VALIDATE_EMAIL — Certifies an e-mail address
  • FILTER_VALIDATE_FLOAT — Confirms a float
  • FILTER_VALIDATE_INT — Verifies an integer
  • FILTER_VALIDATE_IP — Validates an IP address
  • FILTER_VALIDATE_REGEXP — Confirms a regular expression
  • FILTER_VALIDATE_URL — Validates a URL
  • FILTER_SANITIZE_EMAIL — Removes all illegal characters from an e-mail address
  • FILTER_SANITIZE_ENCODED — Removes/Encodes special characters
  • FILTER_SANITIZE_MAGIC_QUOTES — Applies addslashes()
  • FILTER_SANITIZE_NUMBER_FLOAT — Removes all characters, except digits, +- and .,eE
  • FILTER_SANITIZE_NUMBER_INT — Gets rid of all characters except digits and + –
  • FILTER_SANITIZE_SPECIAL_CHARS — Removes special characters
  • FILTER_SANITIZE_FULL_SPECIAL_CHARS — Converts special characters to HTML entities
  • FILTER_SANITIZE_STRING — Removes tags/special characters from a string, alternative: FILTER_SANITIZE_STRIPPED
  • FILTER_SANITIZE_URL — Rids all illegal characters from a URL
  • FILTER_UNSAFE_RAW —Do nothing, optionally strip/encode special characters
  • FILTER_CALLBACK — Call a user-defined function to filter data

HTTP Functions in PHP

PHP also has the functionality to manipulate data sent to the browser from the webserver.

HTTP Functions

  • header() — Sends a raw HTTP header to the browser
  • headers_list() — A list of response headers ready to send (or already sent)
  • headers_sent() — Checks if and where the HTTP headers have been sent
  • setcookie() — Defines a cookie to be sent along with the rest of the HTTP headers
  • setrawcookie() — Defines a cookie (without URL encoding) to be sent along

Working with MySQL

Many platforms that are based on PHP work with a MySQL database in the background. For that reason, it’s important to be familiar with the functions that allow you to work with them.

MySQL Functions

  • mysqli_affected_rows() — The number of affected rows in the previous MySQL operation
  • mysqli_autocommit() — Turn auto-committing database modifications on or off
  • mysqli_change_user() — Changes the user of the specified database connection
  • mysqli_character_set_name() — The default character set for the database connection
  • mysqli_close() — Closes an open database connection
  • mysqli_commit() — Commits the current transaction
  • mysqli_connect_errno() — The error code from the last connection error
  • mysqli_connect_error() — The error description from the last connection error
  • mysqli_connect() — Opens a new connection to the MySQL server
  • mysqli_data_seek() — Moves the result pointer to an arbitrary row in the result set
  • mysqli_debug() — Performs debugging operations
  • mysqli_dump_debug_info() — Dumps debugging information into a log
  • mysqli_errno() — The last error code for the most recent function call
  • mysqli_error_list() — A list of errors for the most recent function call
  • mysqli_error() — The last error description for the most recent function call
  • mysqli_fetch_all() — Fetches all result rows as an array
  • mysqli_fetch_array() — Fetches a result row as an associative, a numeric array, or both
  • mysqli_fetch_assoc() — Fetches a result row as an associative array
  • mysqli_fetch_field_direct() — Metadata for a single field as an object
  • mysqli_fetch_field() — The next field in the result set as an object
  • mysqli_fetch_fields() — An array of objects that represent the fields in a result set
  • mysqli_fetch_lengths() — The lengths of the columns of the current row in the result set
  • mysqli_fetch_object() — The current row of a result set as an object
  • mysqli_fetch_row() — Fetches one row from a result set and returns it as an enumerated array
  • mysqli_field_count() — The number of columns for the most recent query
  • mysqli_field_seek() — Sets the field cursor to the given field offset
  • mysqli_field_tell() — The position of the field cursor
  • mysqli_free_result() — Frees the memory associated with a result
  • mysqli_get_charset() — A character set object
  • mysqli_get_client_info() — The MySQL client library version
  • mysqli_get_client_stats() — Returns client per-process statistics
  • mysqli_get_client_version() — The MySQL client library version as an integer
  • mysqli_get_connection_stats() — Statistics about the client connection
  • mysqli_get_host_info() — The MySQL server hostname and the connection type
  • mysqli_get_proto_info() — The MySQL protocol version
  • mysqli_get_server_info() — Returns the MySQL server version
  • mysqli_get_server_version() — The MySQL server version as an integer
  • mysqli_info() — Returns information about the most recently executed query
  • mysqli_init() — Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli_insert_id() — Returns the auto-generated ID used in the last query
  • mysqli_kill() — Asks the server to kill a MySQL thread
  • mysqli_more_results() — Checks if there are more results from a multi-query
  • mysqli_multi_query() — Performs one or more queries on the database
  • mysqli_next_result() — Prepares the next result set from mysqli_multi_query()
  • mysqli_num_fields() — The number of fields in a result set
  • mysqli_num_rows() — The number of rows in a result set
  • mysqli_options() — Sets extra connect options and affect behavior for a connection
  • mysqli_ping() — Pings a server connection or tries to reconnect if it has gone down
  • mysqli_prepare() — Prepares an SQL statement for execution
  • mysqli_query() — Performs a query against the database
  • mysqli_real_connect() — Opens a new connection to the MySQL server
  • mysqli_real_escape_string() — Escapes special characters in a string for use in an SQL statement
  • mysqli_real_query() — Executes an SQL query
  • mysqli_reap_async_query() — Returns the result from async query
  • mysqli_refresh() — Refreshes tables or caches or resets the replication server information
  • mysqli_rollback() — Rolls back the current transaction for the database
  • mysqli_select_db() — Changes the default database for the connection
  • mysqli_set_charset() — Sets the default client character set
  • mysqli_set_local_infile_default() — Unsets a user-defined handler for the LOAD LOCAL INFILE command
  • mysqli_set_local_infile_handler() — Sets a callback function for the LOAD DATA LOCAL INFILE command
  • mysqli_sqlstate() — Returns the SQLSTATE error code for the last MySQL operation
  • mysqli_ssl_set() — Establishes secure connections using SSL
  • mysqli_stat() — The current system status
  • mysqli_stmt_init() — Initializes a statement and returns an object for use with mysqli_stmt_prepare()
  • mysqli_store_result() — Transfers a result set from the last query
  • mysqli_thread_id() — The thread ID for the current connection
  • mysqli_thread_safe() — Returns if the client library is compiled as thread-safe
  • mysqli_use_result() — Initiates the retrieval of a result set from the last query executed using the mysqli_real_query()
  • mysqli_warning_count() — The number of warnings from the last query in the connection

Date and Time

Of course, PHP functions for date and time should not be missing from any PHP cheat sheet.

Date/Time Functions

  • checkdate() — Checks the validity of a Gregorian date
  • date_add() — Adds a number of days, months, years, hours, minutes and seconds to a date object
  • date_create_from_format() — Returns a formatted DateTime object
  • date_create() — Creates a new DateTime object
  • date_date_set() — Sets a new date
  • date_default_timezone_get() — Returns the default timezone used by all functions
  • date_default_timezone_set() — Sets the default timezone
  • date_diff() — Calculates the difference between two dates
  • date_format() — Returns a date formatted according to a specific format
  • date_get_last_errors() — Returns warnings or errors found in a date string
  • date_interval_create_from_date_string() — Sets up a DateInterval from relative parts of a string
  • date_interval_format() — Formats an interval
  • date_isodate_set() — Sets a date according to ISO 8601 standards
  • date_modify() — Modifies the timestamp
  • date_offset_get() — Returns the offset of the timezone
  • date_parse_from_format() — Returns an array with detailed information about a specified date, according to a specified format
  • date_parse() — Returns an array with detailed information about a specified date
  • date_sub() — Subtracts days, months, years, hours, minutes and seconds from a date
  • date_sun_info() — Returns an array containing information about sunset/sunrise and twilight begin/end for a specified day and location
  • date_sunrise() — The sunrise time for a specified day and location
  • date_sunset() — The sunset time for a specified day and location
  • date_time_set() — Sets the time
  • date_timestamp_get() — Returns the Unix timestamp
  • date_timestamp_set() — Sets the date and time based on a Unix timestamp
  • date_timezone_get() — Returns the time zone of a given DateTime object
  • date_timezone_set() — Sets the time zone for a DateTime object
  • date() — Formats a local date and time
  • getdate() — Date/time information of a timestamp or the current local date/time
  • gettimeofday() — The current time
  • gmdate() — Formats a GMT/UTC date and time
  • gmmktime() — The Unix timestamp for a GMT date
  • gmstrftime() — Formats a GMT/UTC date and time according to locale settings
  • idate() — Formats a local time/date as an integer
  • localtime() — The local time
  • microtime() — The current Unix timestamp with microseconds
  • mktime() — The Unix timestamp for a date
  • strftime() — Formats a local time and/or date according to locale settings
  • strptime() — Parses a time/date generated with strftime()
  • strtotime() — Transforms an English textual DateTime into a Unix timestamp
  • time() — The current time as a Unix timestamp
  • timezone_abbreviations_list() — Returns an array containing dst, offset, and the timezone name
  • timezone_identifiers_list() — An indexed array with all timezone identifiers
  • timezone_location_get() — Location information for a specified timezone
  • timezone_name_from_abbr() — Returns the timezone name from an abbreviation
  • timezone_name_get() — The name of the timezone
  • timezone_offset_get() — The timezone offset from GMT
  • timezone_open() — Creates a new DateTimeZone object
  • timezone_transitions_get() — Returns all transitions for the timezone
  • timezone_version_get() — Returns the version of the timezonedb

Date and Time Formatting

  • d — 01 to 31
  • j — 1 to 31
  • D — Mon through Sun
  • l — Sunday through Saturday
  • N — 1 (for Mon) through 7 (for Sat)
  • w — 0 (for Sun) through 6 (for Sat)
  • m — Months, 01 through 12
  • n — Months, 1 through 12
  • F — January through December
  • M — Jan through Dec
  • Y — Four digits year (e.g. 2018)
  • y — Two digits year (e.g. 18)
  • L — Defines whether it’s a leap year (1 or 0)
  • a — am and pm
  • A — AM and PM
  • g — Hours 1 through 12
  • h — Hours 01 through 12
  • G — Hours 0 through 23
  • H — Hours 00 through 23
  • i — Minutes 00 to 59
  • s — Seconds 00 to 59

Finally, for the times that things don’t go smoothly and you need to find out where the problem lies, PHP also offers functionality for errors.

Error Functions

  • debug_backtrace() — Used to generate a backtrace
  • debug_print_backtrace() — Prints a backtrace
  • error_get_last() — Gets the last error that occurred
  • error_log() — Sends an error message to the web server’s log, a file or a mail account
  • error_reporting() — Specifies which PHP errors are reported
  • restore_error_handler() — Reverts to the previous error handler function
  • restore_exception_handler() — Goes back to the previous exception handler
  • set_error_handler() — Sets a user-defined function to handle script errors
  • set_exception_handler() — Sets an exception handler function defined by the user
  • trigger_error() — Generates a user-level error message, you can also use  user_error()

Error Constants

  • E_ERROR — Fatal run-time errors that cause the halting of the script and can’t be recovered from
  • E_WARNING — Non-fatal run-time errors, execution of the script continues
  • E_PARSE — Compile-time parse errors, should only be generated by the parser
  • E_NOTICE — Run-time notices that indicate a possible error
  • E_CORE_ERROR — Fatal errors at PHP initialization, like an E_ERROR in PHP core
  • E_CORE_WARNING — Non-fatal errors at PHP startup, similar to E_WARNING but in PHP core
  • E_COMPILE_ERROR — Fatal compile-time errors generated by the Zend Scripting Engine
  • E_COMPILE_WARNING — Non-fatal compile-time errors by the Zend Scripting Engine
  • E_USER_ERROR — Fatal user-generated error, set by the programmer using trigger_error()
  • E_USER_WARNING — Non-fatal user-generated warning
  • E_USER_NOTICE — User-generated notice by trigger_error()
  • E_STRICT — Suggestions by PHP to improve your code (needs to be enabled)
  • E_RECOVERABLE_ERROR — Catchable fatal error caught by a user-defined handle
  •   E_DEPRECATED — Enable this to receive warnings about a code which is not future-proof
  • E_USER_DEPRECATED — User-generated warning for deprecated code
  • E_ALL — All errors and warnings except E_STRICT

Knowing your way around PHP is a good idea for anyone interested in web design and web development. Especially if you want to dive deeper into the technical aspects of creating your own website.

The PHP cheat sheet above provides you with an overview of some central parts of PHP. Bookmark it as a reference or use it as a springboard to learn more about the programming language. We sincerely hope you have found it a useful resource.

If you spot any errors in this cheat sheet, please contact us – [email protected]

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Latest commit

File metadata and controls.

The PHP Handbook – Learn PHP for Beginners

Flavio Copes

PHP is an incredibly popular programming language.

Statistics say it’s used by 80% of all websites. It’s the language that powers WordPress, the widely used content management system for websites.

And it also powers a lot of different frameworks that make Web Development easier, like Laravel. Speaking of Laravel, it may be one of the most compelling reasons to learn PHP these days.

Why Learn PHP?

PHP is quite a polarizing language. Some people love it, and some people hate it. If we move a step above the emotions and look at the language as a tool, PHP has a lot to offer.

Sure it’s not perfect. But let me tell you – no language is.

In this handbook, I’m going to help you learn PHP.

This book is a perfect introduction if you’re new to the language. It’s also perfect if you’ve done “some PHP” in the past and you want to get back to it.

I’ll explain modern PHP, version 8+.

PHP has evolved a lot in the last few years. So if the last time you tried it was PHP 5 or even PHP 4, you’ll be surprised at all the good things that PHP now offers.

Here's what we'll cover in this handbook:

Introduction to PHP

What kind of language is php, how to setup php, how to code your first php program, php language basics, how to work with strings in php, how to use built-in functions for numbers in php, how arrays work in php, how conditionals work in php, how loops work in php, how functions work in php, how to loop through arrays with map() , filter() , and reduce() in php, object oriented programming in php, how to include other php files, useful constants, functions and variables for filesystem in php, how to handle errors in php, how to handle exceptions in php, how to work with dates in php, how to use constants and enums in php, how to use php as a web app development platform, how to use composer and packagist, how to deploy a php application.

Note that you can get a PDF, ePub, or Mobi version of this handbook for easier reference, or for reading on your Kindle or tablet.

PHP is a programming language that many devs use to create Web Applications, among other things.

As a language, it had a humble beginning. It was first created in 1994 by Rasmus Lerdorf to build his personal website. He didn’t know at the time it would eventually become one of the most popular programming languages in the world. It became popular later on, in 1997/8, and exploded in the 2000s when PHP 4 landed.

You can use PHP to add a little interactivity to an HTML page.

Or you can use it as a Web Application engine that creates HTML pages dynamically and sends them to the browser.

It can scale to millions of page views.

Did you know Facebook is powered by PHP? Ever heard of Wikipedia? Slack? Etsy?

Let’s get into some technical jargon.

Programming languages are divided into groups depending on their characteristics. For example interpreted/compiled, strongly/loosely typed, dynamically/statically typed.

PHP is often called a “scripting language” and it’s an interpreted language . If you’ve used compiled languages like C or Go or Swift, the main difference is that you don’t need to compile a PHP program before you run it.

Those languages are compiled and the compiler generates an executable program that you then run. It’s a 2-steps process.

The PHP interpreter is responsible for interpreting the instructions written in a PHP program when it’s executed. It’s just one step. You tell the interpreter to run the program. It's a completely different workflow.

PHP is a dynamically typed language . The types of variables are checked at runtime, rather than before the code is executed as happens for statically typed languages. (These also happen to be compiled – the two characteristics often go hand in hand.)

PHP is also loosely (weakly) typed. Compared to strongly typed languages like Swift, Go, C or Java, you don’t need to declare the types of your variables.

Being interpreted and loosely/dynamically typed will make bugs harder to find before they happen at runtime.

In compiled languages, you can often catch errors at compile time, something that does not happen in interpreted languages.

But on the other hand, an interpreted language has more flexibility.

Fun fact: PHP is written internally in C, a compiled and statically typed language.

In its nature, PHP is similar to JavaScript, another dynamically typed, loosely typed, and interpreted language.

PHP supports object-oriented programming, and also functional programming. You can use it as you prefer.

There are many ways to install PHP on your local machine.

The most convenient way I’ve found to install PHP locally is to use MAMP.

MAMP is a tool that’s freely available for all the Operating Systems – Mac, Windows and Linux. It is a package that gives you all the tools you need to get up and running.

PHP is run by a HTTP Server, which is responsible for responding to HTTP requests, the ones made by the browser. So you access a URL with your browser, Chrome or Firefox or Safari, and the HTTP server responds with some HTML content.

The server is typically Apache or NGINX.

Then to do anything non-trivial you’ll need a database, like MySQL.

MAMP is a package that provides all of that, and more, and gives you a nice interface to start/stop everything at once.

Of course, you can set up each piece on its own if you like, and many tutorials explain how to do that. But I like simple and practical tools, and MAMP is one of those.

You can follow this handbook with any kind of PHP installation method, not just MAMP.

That said, if you don’t have PHP installed yet and you want to use MAMP, go to https://www.mamp.info and install it.

The process will depend on your operating system, but once you’re done with the installation, you will have a “MAMP” application installed.

Start that, and you will see a window similar to this:

Screen Shot 2022-06-24 at 15.14.05.jpg

Make sure the PHP version selected is the latest available.

At the time of writing MAMP lets you pick 8.0.8.

NOTE: I noticed MAMP has a version that’s a bit behind, not the latest. You can install a more recent version of PHP by enabling the MAMP PRO Demo, then install the latest release from the MAMP PRO settings (in my case it was 8.1.0). Then close it and reopen MAMP (non-pro version). MAMP PRO has more features so you might want to use it, but it’s not necessary to follow this handbook.

Press the Start button at the top right. This will start the Apache HTTP server, with PHP enabled, and the MySQL database.

Go to the URL http://localhost:8888 and you will see a page similar to this:

Screen Shot 2022-06-24 at 15.19.05.jpg

We’re ready to write some PHP!

Open the folder listed as “Document root”. If you're using MAMP on a Mac it’s by default /Applications/MAMP/htdocs .

On Windows it’s C:\MAMP\htdocs .

Yours might be different depending on your configuration. Using MAMP you can find it in the user interface of the application.

In there, you will find a file named index.php .

That is responsible for printing the page shown above.

Screen Shot 2022-06-24 at 15.17.58.jpg

When learning a new programming language we have this tradition of creating a “Hello, World!” application. Something that prints those strings.

Make sure MAMP is running, and open the htdocs folder as explained above.

Open the index.php file in a code editor.

I recommend using VS Code , as it’s a very simple and powerful code editor. You can check out https://flaviocopes.com/vscode/ for an introduction.

Screen Shot 2022-06-24 at 15.37.36.jpg

This is the code that generates the “Welcome to MAMP” page you saw in the browser.

Delete everything and replace it with:

Save, refresh the page on http://localhost:8888 , you should see this:

Screen Shot 2022-06-24 at 15.39.00.jpg

Great! That was your first PHP program.

Let’s explain what is happening here.

We have the Apache HTTP server listening on port 8888 on localhost, your computer.

When we access http://localhost:8888 with the browser, we’re making an HTTP request, asking for the content of the route / , the base URL.

Apache, by default, is configured to serve that route serving the index.html file included in the htdocs folder. That file does not exist – but as we have configured Apache to work with PHP, it will then search for an index.php file.

This file exists, and PHP code is executed server-side before Apache sends the page back to the browser.

In the PHP file, we have a <?php opening, which says “here starts some PHP code”.

We have an ending ?> that closes the PHP code snippet, and inside it, we use the echo instruction to print the string enclosed into quotes into the HTML.

A semicolon is required at the end of every statement.

We have this opening/closing structure because we can embed PHP inside HTML. PHP is a scripting language, and its goal is to be able to “decorate” an HTML page with dynamic data.

Note that with modern PHP, we generally avoid mixing PHP into the HTML. Instead, we use PHP as a “framework to generate the HTML” – for example using tools like Laravel. But we'll discuss plain PHP in this book, so it makes sense to start from the basics.

For example, something like this will give you the same result in the browser:

To the final user, who looks at the browser and has no idea of the code behind the scenes, there’s no difference at all.

The page is technically an HTML page, even though it does not contain HTML tags but just a Hello World string. But the browser can figure out how to display that in the window.

After the first “Hello World”, it’s time to dive into the language features with more details.

How Variables Work in PHP

Variables in PHP start with the dollar sign $ , followed by an identifier, which is a set of alphanumeric chars and the underscore _ char.

You can assign a variable any type of value, like strings (defined using single or double quotes):

Or numbers:

or any other type that PHP allows, as we’ll later see.

Once a variable is assigned a value, for example a string, we can reassign it a different type of value, like a number:

PHP won’t complain that now the type is different.

Variable names are case-sensitive. $name is different from $Name .

It’s not a hard rule, but generally variable names are written in camelCase format, like this: $brandOfCar or $ageOfDog . We keep the first letter lowercase, and the letters of the subsequent words uppercase.

How to Write Comments in PHP

A very important part of any programming language is how you write comments.

You write single-line comments in PHP in this way:

Multi-line comments are defined in this way:

What are Types in PHP?

I mentioned strings and numbers.

PHP has the following types:

  • bool boolean values (true/false)
  • int integer numbers (no decimals)
  • float floating-point numbers (decimals)
  • string strings
  • array arrays
  • object objects
  • null a value that means “no value assigned”

and a few other more advanced ones.

How to Print the Value of a Variable in PHP

We can use the var_dump() built-in function to get the value of a variable:

The var_dump($name) instruction will print string(6) "Flavio" to the page, which tells us the variable is a string of 6 characters.

If we used this code:

we’d have int(20) back, saying the value is 20 and it’s an integer.

var_dump() is one of the essential tools in your PHP debugging tool belt.

How Operators Work in PHP

Once you have a few variables you can make operations with them:

The * I used to multiply $base by $height is the multiplication operator.

We have quite a few operators – so let’s do a quick roundup of the main ones.

To start with, here are the arithmetic operators: + , - , * , / (division), % (remainder) and ** (exponential).

We have the assignment operator = , which we already used to assign a value to a variable.

Next up we have comparison operators, like < , > , <= , >= . Those work like they do in math.

== returns true if the two operands are equal.

=== returns true if the two operands are identical.

What’s the difference?

You’ll find it with experience, but for example:

We also have != to detect if operands are not equal:

and !== to detect if operands are not identical:

Logical operators work with boolean values:

We also have the not operator:

I used the boolean values true and false here, but in practice you’ll use expressions that evaluate to either true or false, for example:

All of the operators listed above are binary , meaning they involve 2 operands.

PHP also has 2 unary operators: ++ and -- :

I introduced the use of strings before when we talked about variables and we defined a string using this notation:

The big difference between using single and double quotes is that with double quotes we can expand variables in this way:

and with double quotes we can use escape characters (think new lines \n or tabs \t ):

PHP offers you a very comprehensive functions in its standard library (the library of functionalities that the language offers by default).

First, we can concatenate two strings using the . operator:

We can check the length of a string using the strlen() function:

This is the first time we've used a function.

A function is composed of an identifier ( strlen in this case) followed by parentheses. Inside those parentheses, we pass one or more arguments to the function. In this case, we have one argument.

The function does something and when it’s done it can return a value. In this case, it returns the number 6 . If there’s no value returned, the function returns null .

We’ll see how to define our own functions later.

We can get a portion of a string using substr() :

We can replace a portion of a string using str_replace() :

Of course we can assign the result to a new variable:

There are a lot more built-in functions you can use to work with strings.

Here is a brief non-comprehensive list just to show you the possibilities:

  • trim() strips white space at the beginning and end of a string
  • strtoupper() makes a string uppercase
  • strtolower() makes a string lowercase
  • ucfirst() makes the first character uppercase
  • strpos() finds the firsts occurrence of a substring in the string
  • explode() to split a string into an array
  • implode() to join array elements in a string

You can find a full list here .

I previously listed the few functions we commonly use for strings.

Let’s make a list of the functions we use with numbers:

  • round() to round a decimal number, up/down depending if the value is > 0.5 or smaller
  • ceil() to round a a decimal number up
  • floor() to round a decimal number down
  • rand() generates a random integer
  • min() finds the lowest number in the numbers passed as arguments
  • max() finds the highest number in the numbers passed as arguments
  • is_nan() returns true if the number is not a number

There are a ton of different functions for all sorts of math operations like sine, cosine, tangents, logarithms, and so on. You can find a full list here .

Arrays are lists of values grouped under a common name.

You can define an empty array in two different ways:

An array can be initialized with values:

Arrays can hold values of any type:

Even other arrays:

You can access the element in an array using this notation:

Once an array is created, you can append values to it in this way:

You can use array_unshift() to add the item at the beginning of the array instead:

Count how many items are in an array using the built-in count() function:

Check if an array contains an item using the in_array() built-in function:

If in addition to confirming existence, you need the index, use array_search() :

Useful Functions for Arrays in PHP

As with strings and numbers, PHP provides lots of very useful functions for arrays. We’ve seen count() , in_array() , array_search() – let’s see some more:

  • is_array() to check if a variable is an array
  • array_unique() to remove duplicate values from an array
  • array_search() to search a value in the array and return the key
  • array_reverse() to reverse an array
  • array_reduce() to reduce an array to a single value using a callback function
  • array_map() to apply a callback function to each item in the array. Typically used to create a new array by modifying the values of an existing array, without altering it.
  • array_filter() to filter an array to a single value using a callback function
  • max() to get the maximum value contained in the array
  • min() to get the minimum value contained in the array
  • array_rand() to get a random item from the array
  • array_count_values() to count all the values in the array
  • implode() to turn an array into a string
  • array_pop() to remove the last item of the array and return its value
  • array_shift() same as array_pop() but removes the first item instead of the last
  • sort() to sort an array
  • rsort() to sort an array in reverse order
  • array_walk() similarly to array_map() does something for every item in the array, but in addition it can change values in the existing array

How to Use Associative Arrays in PHP

So far we’ve used arrays with an incremental, numeric index: 0, 1, 2…

You can also use arrays with named indexes (keys), and we call them associative arrays:

We have some functions that are especially useful for associative arrays:

  • array_key_exists() to check if a key exists in the array
  • array_keys() to get all the keys from the array
  • array_values() to get all the values from the array
  • asort() to sort an associative array by value
  • arsort() to sort an associative array in descending order by value
  • ksort() to sort an associative array by key
  • krsort() to sort an associative array in descending order by key

You can see all array-related functions here .

I previously introduced comparison operators: < , > , <= , >= , == , === , != , !== ... and so on.

Those operators are going to be super useful for one thing: conditionals .

Conditionals are the first control structure we see.

We can decide to do something, or something else, based on a comparison.

For example:

The code inside the parentheses only executes if the condition evaluates to true .

Use else to do something else in case the condition is false :

NOTE: I used cannot instead of can't because the single quote would terminate my string before it should. In this case you could escape the ' in this way: echo 'You can\'t enter the pub';

You can have multiple if statements chained using elseif :

In addition to if , we have the switch statement.

We use this when we have a variable that could have a few different values, and we don’t have to have a long if / elseif block:

I know the example does not have any logic, but I think it can help you understand how switch works.

The break; statement after each case is essential. If you don’t add that and the age is 17, you’d see this:

Instead of just this:

as you’d expect.

Loops are another super useful control structure.

We have a few different kinds of loops in PHP: while , do while , for , and foreach .

Let’s see them all!

How to Use a while loop in PHP

A while loop is the simplest one. It keeps iterating while the condition evaluates to true :

This would be an infinite loop, which is why we use variables and comparisons:

How to Use a do while loop in PHP

do while is similar, but slightly different in how the first iteration is performed:

In the do while loop, first we do the first iteration, then we check the condition.

In the while loop, first we check the condition, then we do the iteration.

Do a simple test by setting $counter to 15 in the above examples, and see what happens.

You'll want to choose one kind of loop, or the other, depending on your use case.

How to Use a foreach Loop in PHP

You can use the foreach loop to easily iterate over an array:

You can also get the value of the index (or key in an associative array) in this way:

How to Use a for Loop in PHP

The for loop is similar to while, but instead of defining the variable used in the conditional before the loop, and instead of incrementing the index variable manually, it’s all done in the first line:

You can use the for loop to iterate over an array in this way:

How to Use the break and continue Statements in PHP

In many cases you want the ability to stop a loop on demand.

For example you want to stop a for loop when the value of the variable in the array is 'b' :

This makes the loop completely stop at that point, and the program execution continues at the next instruction after the loop.

If you just want to skip the current loop iteration and keep looking, use continue instead:

Functions are one of the most important concepts in programming.

You can use functions to group together multiple instructions or multiple lines of code, and give them a name.

For example you can make a function that sends an email. Let’s call it sendEmail , and we'll define it like this:

And you can call it anywhere else by using this syntax:

You can also pass arguments to a function. For example when you send an email, you want to send it to someone – so you add the email as the first argument:

Inside the function definition we get this parameter in this way (we call them parameters inside the function definition, and arguments when we call the function):

You can send multiple arguments by separating them with commas:

And we can get those parameters in the order they were defined:

We can optionally set the type of parameters:

Parameters can have a default value, so if they are omitted we can still have a value for them:

A function can return a value. Only one value can be returned from a function, not more than one. You do that using the return keyword. If omitted, the function returns null .

The returned value is super useful as it tells you the result of the work done in the function, and lets you use its result after calling it:

We can optionally set the return type of a function using this syntax:

When you define a variable inside a function, that variable is local to the function, which means it’s not visible from outside. When the function ends, it just stops existing:

Variables defined outside of the function are not accessible inside the function.

This enforces a good programming practice as we can be sure the function does not modify external variables and cause “side effects”.

Instead you return a value from the function, and the outside code that calls the function will take responsibility for updating the outside variable.

You can pass the value of a variable by passing it as an argument to the function:

But you can’t modify that value from within the function.

It’s passed by value , which means the function receives a copy of it, not the reference to the original variable.

That is still possible using this syntax (notice I used & in the parameter definition):

The functions we've defined so far are named functions .

They have a name.

We also have anonymous functions , which can be useful in a lot of cases.

They don’t have a name, per se, but they are assigned to a variable. To call them, you invoke the variable with parentheses at the end:

Note that you need a semicolon after the function definition, but then they work like named functions for return values and parameters.

Interestingly, they offer a way to access a variable defined outside the function through use() :

Another kind of function is an arrow function .

An arrow function is an anonymous function that’s just one expression (one line), and implicitly returns the value of that expression.

You define it in this way:

Here’s an example:

You can pass parameters to an arrow function:

Note that as the next example shows, arrow functions have automatic access to the variables of the enclosing scope, without the need of use() .

Arrow functions are super useful when you need to pass a callback function. We’ll see how to use them to perform some array operations later.

So we have in total 3 kinds of functions: named functions , anonymous functions , and arrow functions .

Each of them has its place, and you’ll learn how to use them properly over time, with practice.

Another important set of looping structures, often used in functional programming, is the set of array_map() / array_filter() / array_reduce() .

Those 3 built-in PHP functions take an array, and a callback function that in each iteration takes each item in the array.

array_map() returns a new array that contains the result of running the callback function on each item in the array:

array_filter() generates a new array by only getting the items whose callback function returns true :

array_reduce() is used to reduce an array to a single value.

For example we can use it to multiply all items in an array:

Notice the last parameter – it’s the initial value. If you omit that, the default value is 0 but that would not work for our multiplication example.

Note that in array_map() the order of the arguments is reversed. First you have the callback function and then the array. This is because we can pass multiple arrays using commas ( array_map(fn($value) => $value * 2, $numbers, $otherNumbers, $anotherArray); ). Ideally we’d like more consistency, but that’s what it is.

Let’s now jump head first into a big topic: object-oriented programming with PHP.

Object-oriented programming lets you create useful abstractions and make your code simpler to understand and manage.

How to Use Classes and Objects in PHP

To start with, you have classes and objects.

A class is a blueprint, or type, of object.

For example you have the class Dog , defined in this way:

Note that the class must be defined in uppercase.

Then you can create objects from this class – specific, individual dogs.

An object is assigned to a variable, and it’s instantiated using the new Classname() syntax:

You can create multiple objects from the same class, by assigning each object to a different variable:

How to Use Properties in PHP

Those objects will all share the same characteristics defined by the class. But once they are instantiated, they will have a life of their own.

For example, a Dog has a name, an age, and a fur color.

So we can define those as properties in the class:

They work like variables, but they are attached to the object, once it's instantiated from the class. The public keyword is the access modifier and sets the property to be publicly accessible.

You can assign values to those properties in this way:

Notice that the property is defined as public .

That is called an access modifier. You can use two other kinds of access modifiers: private and protected . Private makes the property inaccessible from outside the object. Only methods defined inside the object can access it.

We’ll see more about protected when we’ll talk about inheritance.

How to Use Methods in PHP

Did I say method? What is a method?

A method is a function defined inside the class, and it’s defined in this way:

Methods are very useful to attach a behavior to an object. In this case we can make a dog bark.

Notice that I use the public keyword. That’s to say that you can invoke a method from outside the class. Like for properties, you can mark methods as private too, or protected , to restrict their access.

You invoke a method on the object instance like this:

A method, just like a function, can define parameters and a return value, too.

Inside a method we can access the object’s properties using the special built-in $this variable, which, when referenced inside a method, points to the current object instance:

Notice I used $this->name to set and access the $name property, and not $this->$name .

How to Use the Constructor Method in PHP

A special kind of method named __construct() is called a constructor .

You use this method to initialize the properties of an object when you create it, as it’s automatically invoked when calling new Classname() .

This is such a common thing that PHP (starting in PHP 8) includes something called constructor promotion where it automatically does this thing:

By using the access modifier, the assignment from the parameter of the constructor to the local variable happens automatically:

Properties can be typed .

You can require the name to be a string using public string $name :

Now all works fine in this example, but try changing that to public int $name to require it to be an integer.

PHP will raise an error if you initialize $name with a string:

Interesting, right?

We can enforce properties to have a specific type between string , int , float , string , object , array , bool and others .

What is Inheritance in PHP?

The fun in object oriented programming starts when we allow classes to inherit properties and methods from other classes.

Suppose you have an Animal class:

Every animal has an age, and every animal can eat. So we add an age property and an eat() method:

A dog is an animal and has an age and can eat too, so the Dog class – instead of reimplementing the same things we have in Animal – can extend that class:

We can now instantiate a new object of class Dog and we have access to the properties and methods defined in Animal :

In this case we call Dog the child class and Animal the parent class .

Inside the child class we can use $this to reference any property or method defined in the parent, as if they were defined inside the child class.

It’s worth noting that while we can access the parent’s properties and methods from the child, we can’t do the reverse.

The parent class knows nothing about the child class.

protected Properties and Methods in PHP

Now that we've introduced inheritance, we can discuss protected . We already saw how we can use the public access modifier to set properties and methods callable from outside of a class, by the public.

private properties and methods can only be accessed from within the class.

protected properties and methods can be accessed from within the class and from child classes.

How to Override Methods in PHP

What happens if we have an eat() method in Animal and we want to customize it in Dog ? We can override that method.

Now any instance of Dog will use the Dog 's implementation of the eat() method.

Static Properties and Methods in PHP

We’ve seen how to define properties and methods that belong to the instance of a class , an object.

Sometimes it’s useful to assign those to the class itself.

When this happens we call them static , and to reference or call them we don’t need to create an object from the class.

Let’s start with static properties. We define them with the static keyword:

We reference them from inside the class using the keyword self , which points to the class:

and from outside the class using:

This is what happens for static methods:

From the outside of the class we can call them in this way:

From inside the class, we can reference them using the self keyword, which refers to the current class:

How to Compare Objects in PHP

When we talked about operators I mentioned we have the == operator to check if two values are equal and === to check if they are identical.

Mainly the difference is that == checks the object content, for example the '5' string is equal to the number 5 , but it’s not identical to it.

When we use those operators to compare objects, == will check if the two objects have the same class and have the same values assigned to them.

=== on the other hand will check if they also refer to the same instance (object).

How to Iterate over Object Properties in PHP

You can loop over all the public properties in an object using a foreach loop, like this:

How to Clone Objects in PHP

When you have an object, you can clone it using the clone keyword:

This performs a shallow clone , which means that references to other variables will be copied as references – there will not a “recursive cloning” of them.

To do a deep clone you will need to do some more work.

What are Magic Methods in PHP?

Magic methods are special methods that we define in classes to perform some behavior when something special happens.

For example when a property is set, or accessed, or when the object is cloned.

We’ve seen __construct() before.

That’s a magic method.

There are others. For example we can set a “cloned” boolean property to true when the object is cloned:

Other magic methods include __call() , __get() , __set() , __isset() , __toString() and others.

You can see the full list here

We’re now done talking about the object oriented features of PHP.

Let’s now explore some other interesting topics!

Inside a PHP file you can include other PHP files. We have the following methods, all used for this use case, but they're all slightly different: include , include_once , require , and require_once .

include loads the content of another PHP file, using a relative path.

require does the same, but if there’s any error doing so, the program halts. include will only generate a warning.

You can decide to use one or the other depending on your use case. If you want your program to exit if it can’t import the file, use require .

include_once and require_once do the same thing as their corresponding functions without _once , but they make sure the file is included/required only once during the execution of the program.

This is useful if, for example, you have multiple files loading some other file, and you typically want to avoid loading that more than once.

My rule of thumb is to never use include or require because you might load the same file twice. include_once and require_once help you avoid this problem.

Use include_once when you want to conditionally load a file, for example “load this file instead of that”. In all other cases, use require_once .

The above syntax includes the test.php file from the current folder, the file where this code is.

You can use relative paths:

to include a file in the parent folder or to go in a subfolder:

You can use absolute paths:

In modern PHP codebases that use a framework, files are generally loaded automatically so you’ll have less need to use the above functions.

Speaking of paths, PHP offers you several utilities to help you work with paths.

You can get the full path of the current file using:

  • __FILE__ , a magic constant
  • $_SERVER['SCRIPT_FILENAME'] (more on $_SERVER later!)

You can get the full path of the folder where the current file is using:

  • the getcwd() built-in function
  • __DIR__ , another magic constant
  • combine __FILE__ with dirname() to get the current folder full path: dirname(__FILE__)
  • use $_SERVER['DOCUMENT_ROOT']

Every programmer makes errors. We’re humans, after all.

We might forget a semicolon. Or use the wrong variable name. Or pass the wrong argument to a function.

In PHP we have:

The first two are minor errors, and they do not stop the program execution. PHP will print a message, and that’s it.

Errors terminate the execution of the program, and will print a message telling you why.

There are many different kinds of errors, like parse errors, runtime fatal errors, startup fatal errors, and more.

They’re all errors.

I said “PHP will print a message”, but.. where?

This depends on your configuration.

In development mode it’s common to log PHP errors directly into the Web page, but also in an error log.

You want to see those errors as early as possible, so you can fix them.

In production, on the other hand, you don’t want to show them in the Web page, but you still want to know about them.

So what do you do? You log them to the error log.

This is all decided in the PHP configuration.

We haven’t talked about this yet, but there’s a file in your server configuration that decides a lot of things about how PHP runs.

It’s called php.ini .

The exact location of this file depends on your setup.

To find out where is yours, the easiest way is to add this to a PHP file and run it in your browser:

You will then see the location under “Loaded Configuration File”:

Screen Shot 2022-06-27 at 13.42.41.jpg

In my case it’s /Applications/MAMP/bin/php/php8.1.0/conf/php.ini .

Note that the information generated by phpinfo() contains a lot of other useful information. Remember that.

Using MAMP you can open the MAMP application folder and open bin/php . Go in your specific PHP version (8.1.0 in my case) then go in conf . In there you’ll find the php.ini file:

Screen Shot 2022-06-27 at 12.11.28.jpg

Open that file in an editor.

It contains a really long list of settings, with a great inline documentation for each one.

We’re particularly interested in display_errors :

Screen Shot 2022-06-27 at 12.13.16.jpg

In production you want its value to be Off , as the docs above it say.

The errors will not show up anymore in the website, but you will see them in the php_error.log file in the logs folder of MAMP in this case:

Screen Shot 2022-06-27 at 12.16.01.jpg

This file will be in a different folder depending on your setup.

You set this location in your php.ini :

Screen Shot 2022-06-27 at 12.17.12.jpg

The error log will contain all the error messages your application generates:

Screen Shot 2022-06-27 at 12.17.55.jpg

You can add information to the error log by using the error_log() function:

It’s common to use a logger service for errors, like Monolog .

Sometimes errors are unavoidable. Like if something completely unpredictable happens.

But many times, we can think ahead, and write code that can intercept an error, and do something sensible when this happens. Like showing a useful error message to the user, or trying a workaround.

We do so using exceptions .

Exceptions are used to make us, developers, aware of a problem.

We wrap some code that can potentially raise an exception into a try block, and we have a catch block right after that. That catch block will be executed if there’s an exception in the try block:

Notice that we have an Exception object $e being passed to the catch block, and we can inspect that object to get more information about the exception, like this:

Let’s look at an example.

Let's say that by mistake I divide a number by zero:

This will trigger a fatal error and the program is halted on that line:

Screen Shot 2022-06-26 at 20.12.59.jpg

Wrapping the operation in a try block and printing the error message in the catch block, the program ends successfully, telling me the problem:

Screen Shot 2022-06-26 at 20.13.36.jpg

Of course this is a simple example but you can see the benefit: I can intercept the issue.

Each exception has a different class. For example we can catch this as DivisionByZeroError and this lets me filter the possible problems and handle them differently.

I can have a catch-all for any throwable error at the end, like this:

Screen Shot 2022-06-26 at 20.15.47.jpg

And I can also append a finally {} block at the end of this try/catch structure to execute some code after the code is either executed successfully without problems, or there was a catch :

Screen Shot 2022-06-26 at 20.17.33.jpg

You can use the built-in exceptions provided by PHP but you can also create your own exceptions.

Working with dates and times is very common in programming. Let’s see what PHP provides.

We can get the current timestamp (number of seconds since Jan 1 1970 00:00:00 GMT) using time() :

When you have a timestamp you can format that as a date using date() , in the format you prefer:

Y is the 4-digit representation of the year, m is the month number (with a leading zero) and d is the number of the day of the month, with a leading zero.

See the full list of characters you can use to format the date here .

We can convert any date into a timestamp using strtotime() , which takes a string with a textual representation of a date and converts it into the number of seconds since Jan 1 1970:

...it’s pretty flexible.

For dates, it’s common to use libraries that offer a lot more functionality than what the language can. A good option is Carbon .

We can define constants in PHP using the define() built-in function:

And then we can use TEST as if it was a variable, but without the $ sign:

We use uppercase identifiers as a convention for constants.

Interestingly, inside classes we can define constant properties using the const keyword:

By default they are public but we can mark them as private or protected :

Enums allow you to group constants under a common “root”. For example you want to have a Status enum that has 3 states: EATING SLEEPING RUNNING , the 3 states of a dog’s day.

So you have:

Now we can reference those constants in this way:

Enums are objects, they can have methods and lots more features than we can get into here in this short introduction.

PHP is a server-side language and it is typically used in two ways.

One is within an HTML page, so PHP is used to “add” stuff to the HTML which is manually defined in the .php file. This is a perfectly fine way to use PHP.

Another way considers PHP more like the engine that is responsible for generating an “application”. You don't write the HTML in a .php file, but instead you use a templating language to generate the HTML, and everything is managed by what we call the framework .

This is what happens when you use a modern framework like Laravel.

I would consider the first way a bit “out of fashion” these days, and if you’re just starting out you should know about those two different styles of using PHP.

But also consider using a framework like “easy mode” because frameworks give you tools to handle routing, tools to access data from a database, and they make it easier to build a more secure application. And they make it all faster to develop.

That said, we’re not going to talk about using frameworks in this handbook. But I will talk about the basic, fundamental building blocks of PHP. They are essentials that any PHP developer must know.

Just know that “in the real world” you might use your favorite framework’s way of doing things rather than the lower level features offered by PHP.

This does not apply just to PHP of course – it’s an “issue” that happens with any programming language.

How to Handle HTTP Requests in PHP

Let’s start with handling HTTP requests.

PHP offers file-based routing by default. You create an index.php file and that responds on the / path.

We saw that when we made the Hello World example in the beginning.

Similarly, you can create a test.php file and automatically that will be the file that Apache serves on the /test route.

How to Use $_GET , $_POST and $_REQUEST in PHP

Files respond to all HTTP requests, including GET, POST and other verbs.

For any request you can access all the query string data using the $_GET object. It's called superglobal and is automatically available in all our PHP files.

This is of course most useful in GET requests, but also other requests can send data as a query string.

For POST, PUT and DELETE requests you’re more likely to need the data posted as URL-encoded data or using the FormData object, which PHP makes available to you using $_POST .

There is also $_REQUEST which contains all of $_GET and $_POST combined in a single variable.

How to Use the $_SERVER Object in PHP

We also have the superglobal variable $_SERVER , which you use to get a lot of useful information.

You saw how to use phpinfo() before. Let’s use it again to see what $_SERVER offers us.

In your index.php file in the root of MAMP run:

Then generate the page at localhost:8888 and search $_SERVER . You will see all the configuration stored and the values assigned:

Screen Shot 2022-06-27 at 13.46.50.jpg

Important ones you might use are:

  • $_SERVER['HTTP_HOST']
  • $_SERVER['HTTP_USER_AGENT']
  • $_SERVER['SERVER_NAME']
  • $_SERVER['SERVER_ADDR']
  • $_SERVER['SERVER_PORT']
  • $_SERVER['DOCUMENT_ROOT']
  • $_SERVER['REQUEST_URI']
  • $_SERVER['SCRIPT_NAME']
  • $_SERVER['REMOTE_ADDR']

How to Use Forms in PHP

Forms are the way the Web platform allows users to interact with a page and send data to the server.

Here is a simple form in HTML:

You can put this in your index.php file like it was called index.html .

A PHP file assumes you write HTML in it with some “PHP sprinkles” using <?php ?> so the Web Server can post that to the client. Sometimes the PHP part takes all of the page, and that’s when you generate all the HTML via PHP – it’s kind of the opposite of the approach we're taking here now.

So we have this index.php file that generates this form using plain HTML:

Screen Shot 2022-06-27 at 13.53.47.jpg

Pressing the Submit button will make a GET request to the same URL sending the data via query string. Notice that the URL changed to localhost:8888/?name=test .

Screen Shot 2022-06-27 at 13.56.46.jpg

We can add some code to check if that parameter is set using the isset() function:

Screen Shot 2022-06-27 at 13.56.35.jpg

See? We can get the information from the GET request query string through $_GET .

What you usually do with forms, though is you perform a POST request:

See, now we got the same information but the URL didn’t change. The form information was not appended to the URL.

Screen Shot 2022-06-27 at 13.59.54.jpg

This is because we’re using a POST request , which sends the data to the server in a different way, through URL-encoded data.

As mentioned above, PHP will still serve the index.php file as we’re still sending data to the same URL the form is on.

We’re mixing a bunch of code and we could separate the form request handler from the code that generates the form.

So we can have this in index.php :

and we can create a new post.php file with:

PHP will display this content now after we submit the form, because we set the action HTML attribute on the form.

This example is very simple, but the post.php file is where we could, for example, save the data to the database, or to a file.

How to Use HTTP Headers in PHP

PHP lets us set the HTTP headers of a response through the header() function.

HTTP Headers are a way to send information back to the browser.

We can say the page generates a 500 Internal Server Error:

Now you should see the status if you access the page with the Browser Developer Tools open:

Screen Shot 2022-06-27 at 14.10.29.jpg

We can set the content/type of a response:

We can force a 301 redirect:

We can use headers to say to the browser “cache this page”, “don’t cache this page”, and a lot more.

How to Use Cookies in PHP

Cookies are a browser feature.

When we send a response to the browser, we can set a cookie which will be stored by the browser, client-side.

Then, every request the browser makes will include the cookie back to us.

We can do many things with cookies. They are mostly used to create a personalized experience without you having to login to a service.

It’s important to note that cookies are domain-specific, so we can only read cookies we set on the current domain of our application, not other application’s cookies.

But JavaScript can read cookies (unless they are HttpOnly cookies but we’re starting to go into a rabbit hole) so cookies should not store any sensitive information.

We can use PHP to read the value of a cookie referencing the $_COOKIE superglobal:

The setcookie() function allows you to set a cookie:

We can add a third parameter to say when the cookie will expire. If omitted, the cookie expires at the end of the session/when the browser is closed.

Use this code to make the cookie expire in 7 days:

We can only store a limited amount of data in a cookie, and users can clear the cookies client-side when they clear the browser data.

Also, they are specific to the browser / device, so we can set a cookie in the user’s browser, but if they change browser or device, the cookie will not be available.

Let’s do a simple example with the form we used before. We’re going to store the name entered as a cookie:

I added some conditionals to handle the case where the cookie was already set, and to display the name right after the form is submitted, when the cookie is not set yet (it will only be set for the next HTTP request).

If you open the Browser Developer Tools you should see the cookie in the Storage tab.

From there you can inspect its value, and delete it if you want.

Screen Shot 2022-06-27 at 14.46.09.jpg

How to Use Cookie-based Sessions in PHP

One very interesting use case for cookies is cookie-based sessions.

PHP offers us a very easy way to create a cookie-based session using session_start() .

Try adding this:

in a PHP file, and load it in the browser.

You will see a new cookie named by default PHPSESSID with a value assigned.

That’s the session ID. This will be sent for every new request and PHP will use that to identify the session.

Screen Shot 2022-06-27 at 14.51.53.jpg

Similarly to how we used cookies, we can now use $_SESSION to store the information sent by the user – but this time it’s not stored client-side.

Only the session ID is.

The data is stored server-side by PHP.

Screen Shot 2022-06-27 at 14.53.24.jpg

This works for simple use cases, but of course for intensive data you will need a database.

To clear the session data you can call session_unset() .

To clear the session cookie use:

How to Work with Files and Folders in PHP

PHP is a server-side language, and one of the handy things it provides is access to the filesystem.

You can check if a file exists using file_exists() :

Get the size of a file using filesize() :

You can open a file using fopen() . Here we open the test.txt file in read-only mode and we get what we call a file descriptor in $file :

We can terminate the file access by calling fclose($fd) .

Read the content of a file into a variable like this:

feof() checks that we haven’t reached the end of the file as fgets reads 5000 bytes at a time.

You can also read a file line by line using fgets() :

To write to a file you must first open it in write mode , then use fwrite() :

We can delete a file using unlink() :

Those are the basics, but of course there are more functions to work with files .

PHP and Databases

PHP offers various built-in libraries to work with databases, for example:

  • MySQL / MariaDB

I won't cover this in the handbook because I think this is a big topic and one that would also require you to learn SQL.

I am also tempted to say that if you need a database you should use a framework or ORM that would save you security issues with SQL injection. Laravel’s Eloquent is a great example.

How to Work with JSON in PHP

JSON is a portable data format we use to represent data and send data from client to server.

Here’s an example of a JSON representation of an object that contains a string and a number:

PHP offers us two utility functions to work with JSON:

  • json_encode() to encode a variable into JSON
  • json_decode() to decode a JSON string into a data type (object, array…)

How to Send Emails with PHP

One of the things that I like about PHP is the conveniences, like sending an email.

Send an email using mail() :

To send emails at scale we can’t rely on this solution, as these emails tend to reach the spam folder more often than not. But for quick testing this is just helpful.

Libraries like https://github.com/PHPMailer/PHPMailer will be super helpful for more solid needs, using an SMTP server.

Composer is the package manager of PHP.

It allows you to easily install packages into your projects.

Install it on your machine ( Linux/Mac or Windows ) and once you’re done you should have a composer command available on your terminal.

Screen Shot 2022-06-27 at 16.25.43.jpg

Now inside your project you can run composer require <lib> and it will be installed locally. For example let's install the Carbon library that helps us work with dates in PHP

It will do some work:

Screen Shot 2022-06-27 at 16.27.11.jpg

Once it’s done, you will find some new things in the folder composer.json that lists the new configuration for the dependencies:

composer.lock is used to “lock” the versions of the package in time, so the exact same installation you have can be replicated on another server. The vendor folder contains the library just installed and its dependencies.

Now in the index.php file we can add this code at the top:

and then we can use the library!

Screen Shot 2022-06-27 at 16.34.47.jpg

See? We didn’t have to manually download a package from the internet and install it somewhere...it was all fast, quick, and well organized.

The require 'vendor/autoload.php'; line is what enables autoloading . Remember when we talked about require_once() and include_once() ? This solves all of that – we don’t need to manually search for the file to include, we just use the use keyword to import the library into our code.

When you’ve got an application ready, it’s time to deploy it and make it accessible from anyone on the Web.

PHP is the programming language with the best deployment story across the Web.

Trust me, every single other programming language and ecosystem wishes they were as easy as PHP.

The great thing about PHP, the thing it got right and allowed it to have the incredible success it has had, is the instant deploy.

You put a PHP file on a folder served by a Web server, and voilà – it just works.

No need to restart the server, run an executable, nothing.

This is still something that a lot of people do. You get a shared hosting for $3/month, upload your files via FTP, and you're done.

These days, though, I think Git deploy is something that should be baked into every project, and shared hosting should be a thing of the past.

One solution is always having your own private VPS (Virtual Private Server), which you can get from services like DigitalOcean or Linode.

But managing your own VPS is no joke. It requires serious knowledge and time investment, and constant maintenance.

You can also use the so-called PaaS (Platform as a Service), which are platforms that focus on taking care of all the boring stuff (managing servers) and you just upload your app and it runs.

Solutions like DigitalOcean App Platform (which is different from a DigitalOcean VPS), Heroku, and many others are great for your first tests.

These services allow you to connect your GitHub account and deploy any time you push a new change to your Git repository.

You can learn how to setup Git and GitHub from zero here .

This is a much better workflow compared to FTP uploads.

Let’s do a bare bones example.

I created a simple PHP application with just an index.php file:

I add the parent folder to my GitHub Desktop app, I initialize a Git repo, and I push it to GitHub:

Screen Shot 2022-06-27 at 17.26.24.jpg

Now go on digitalocean.com .

If you don’t have an account yet, use my referral code to sign up get $100 free credits over the next 60 days and you can work on your PHP app for free.

I connect to my DigitalOcean account and I go to Apps → Create App.

I connect my GitHub Account and select the repo of my app.

Make sure “Autodeploy” is checked, so the app will automatically redeploy on changes:

Screen Shot 2022-06-27 at 17.31.54.jpg

Click “Next” then Edit Plan:

Screen Shot 2022-06-27 at 17.32.24.jpg

By default the Pro plan is selected.

Use Basic and pick the $5/month plan.

Note that you pay $5 per month, but billing is per hour – so you can stop the app any time you want.

Screen Shot 2022-06-27 at 17.32.28.jpg

Then go back and press “Next” until the “Create Resources” button appears to create the app. You don’t need any database, otherwise that would be another $7/month on top.

Screen Shot 2022-06-27 at 17.33.46.jpg

Now wait until the deployment is ready:

Screen Shot 2022-06-27 at 17.35.00.jpg

The app is now up and running!

Screen Shot 2022-06-27 at 17.35.31.jpg

You’ve reached the end of the PHP Handbook!

Thank you for reading through this introduction to the wonderful world of PHP development. I hope it will help you get your web development job, become better at your craft, and empower you to work on your next big idea.

Note: you can get a PDF, ePub, or Mobi version of this handbook for easier reference, or for reading on your Kindle or tablet.

Read more posts .

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Academia.edu no longer supports Internet Explorer.

To browse Academia.edu and the wider internet faster and more securely, please take a few seconds to  upgrade your browser .

Enter the email address you signed up with and we'll email you a reset link.

  • We're Hiring!
  • Help Center

paper cover thumbnail

Advanced PHP programming

Profile image of Mohammed Musthafa

Related Papers

Proceedings of the 39th SIGCSE technical symposium on Computer science education

Bertrand Meyer

php assignment pdf

Handbook of Warnings

Michael S . Wogalter

This chapter introduces several major warning-related concepts. Topics include the plll'poses of warnings and their place in the hazard control hierarchy. The who, what, when and where of warnings are described, followed by a discussion of the concepts of hazard control hierarchy and warning systems. A table of generalized design guidelines derived from the warning literature is presented. Lastly, testing using participants from the target population is recommended to verify warning effectiveness.

International Review of Law and Economics

Sandra Rousseau

Antti Pirhonen

Usability of complex information system like enterprise resource planning (ERP) system is still a challenging area. This is why many usability problems have been found in the ERP system. In this article, we tried to highlight the 21 usability problems in ERP error messages by using Nielsen’s heuristics and inquiry questionnaire methods. Nielsen’s heuristics is a better for finding a large number of unique usability problems in different areas. The inquiry questionnaire method has some constraints, but it is useful for comprehending how the actual end-users perceive an application. Keywords-component; Usability; Nielsen’s heuristics method; Inquiry questionnaire method

Drug Safety

Jeffrey Aronson

… (ASE), 2011 26th …

Tung Nguyen

Brett A Becker

Computer programming is an essential skill that all computing students must master and is increasingly important in many diverse disciplines. It is also difficult to learn. One of the many challenges novice programmers face from the start are notoriously cryptic compiler error messages. These report details on errors made by students and are essential as the primary source of information used to rectify those errors. However these difficult to understand messages are often a barrier to progress and a source of discouragement. A high number of student errors, and in particular a high frequency of repeated errors – when a student makes the same error consecutively – have been shown to be indicators of students who are struggling with learning to program. This instrumental case study research investigates the student experience with, and the effects of, software that has been specifically written to help students overcome their challenges with compiler error messages. This software provides help by enhancing error messages, presenting them in a straightforward, informative manner. Two cohorts of first year computing students at an Irish higher education institution participated over two academic years; a control group in 2014-15 that did not experience enhanced error messages, and an intervention group in 2013-14 that did. This thesis lays out a comprehensive view of the student experience starting with a quantitative analysis of the student errors themselves. It then views the students as groups, revealing interesting differences in error profiles. Following this, some individual student profiles and behaviours are investigated. Finally, the student experience is discovered through their own words and opinions by means of a survey that incorporated closed and open-ended questions. In addition to reductions in errors overall, errors per student, and the key metric of repeated error frequency, the intervention group is shown to behave more cohesively with fewer indications of struggling students. A positive learning experience using the software is reported by the students and the lecturer. These results are of interest to educators who have witnessed students struggle with learning to program, and who are looking to help remove the barrier presented by compiler error messages. This work is important for two reasons. First, the effects of error message enhancement have been debated in the literature – this work provides evidence that there can be positive effects. Second, these results should be generalisable at least in part, to other languages, students and institutions.

Masahiro Goshima

MUSTAPHA NASIR USMAN

Loading Preview

Sorry, preview is currently unavailable. You can download the paper by clicking the button above.

RELATED PAPERS

Andrei Alexandrescu

Proceedings of the 6th USENIX Symposium on File and Storage Technologies (FAST���08)

Cindy Gonzalez

Hubert Haider

Joaquim Vinte

James M Carpenter

Brad A Myers

Biological Psychology

thierry hasbroucq

Interacting with Computers

Klaus Opwis

paula kahuho-mwarari

Psychology & Marketing

Donna Riley

  •   We're Hiring!
  •   Help Center
  • Find new research papers in:
  • Health Sciences
  • Earth Sciences
  • Cognitive Science
  • Mathematics
  • Computer Science
  • Academia ©2024

Menu

  • In The News

Fill Out a PDF Form Using PHP – Tutorial

Looking for help on a project please feel free to contact me for a free consultation.

I recently took on a task where I had to use an HTML web form, whose back-end is PHP, to fill out a PDF form. The entire process is extremely annoying, and I was really hoping to use some kind of self-contained library that I could drop into a shared webhost for a client and be done with it. Unfortunately, at the tail end of 2022, there doesn’t seem to be any such library that handles everything. Below is my research as well as the methodology I ended up going with.

Table of Contents

Download links, the alternatives, the winner – pdftk, create a pdf form, create a corresponding html form, examine fdf file format, process html form data and output an fdf file, use pdftk to combine the fdf file and the pdf file.

If you’d like, you can skip right to the good stuff and download a set of files here – just note that you’ll need to install PDFtk on your server to use it (spoilers?)

I tried a few different options, and unfortunately the following didn’t really work for me. Maybe this list will prevent others from going down the same rabbit holes.

  • They even have a page dedicated to describing how to fill out a PDF form
  • Despite the old-style website, it works with PHP 8.1
  • I found out early on that it wouldn’t fill in checkboxes, but they mention that on the page above, and link to someone’s forked library, confusingly named FPDM
  • Unfortunately neither the original nor the fork handle radio buttons, which my PDF had, so I had to abandon the whole thing
  • But I’m not using Zend, and even if I was, I’m not so comfortable with unofficial patches…
  • In fact, under “Known limitations”, it specifically says that it “cannot save a completed form”, which means it’s kind of useless to me

As you can see, the landscape is a little bleak. Lots of projects that deal with PDFs in one way or another, some with forms in mind, but none that do exactly what I want.

My only solution was to use a system library, PDFtk , which would do the job for me. Basically, the goal is to dump the form data into a file format called FDF, and then to use the PDFtk library to combine the data from the FDF with the PDF form. The main caveat is that PDFtk needs to be installed on the server you’re running the code on. If you have sudo access to your system, this is easy, but if you don’t, your shared host might actually have it installed already (my client’s BlueHost server did). Just check with tech support.

So, the goal is as follows:

  • Create a PDF form
  • Generate an HTML form with a submit button
  • Send the data from that form over to a PHP file
  • Process the data and dump it into an FDF file
  • Call PDFtk and use it to combine the FDF data and the PDF form

You can download and run the sample project from here . Note that you’ll need to install PDFtk – you can find more information about it here , or you can Google “PDFtk install” + your operating system of choice.

I created a sample PDF using Adobe Acrobat Pro. It’s a very simple file that contains each of the types of inputs a form can have in a PDF: a textbox, checkboxes, radio buttons, and a dropdown (called a list box within Acrobat).

php assignment pdf

Of important note is the names of these fields – this is how they will be identified later on. It’s easiest not to use spaces in the names.

php assignment pdf

Next, I need to make a corresponding HTML file file that matches the naming scheme of the PDF file. Easy enough, check out index.html in the sample project . It’s a boilerplate HTML5 document, with a bunch of input fields. See the snippet below:

Of note here is that each field’s name ends in _fieldtype , whether that’s _textbox , _checkbox , _radio , or _dropdown . This makes it easier to process in the next step.

At this point, if we were to dump the contents of $_POST in pdfFiller.php, it would look like this:

So, what we want to do is loop through these and dump their data into an FDF file. But what format is the FDF file in? The easiest way to determine that is actually to fill out the PDF yourself, hit save, and run the following command, replacing the data where necesary:

That line was written for Windows (hence pdftk.exe ), but otherwise should work on all platforms supported by PDFtk. The output, once cleaned up a bit, is as follows:

We can ignore the first 2 lines and the final 3 lines, because they are just boilerplate FDF information. We’ll be sure to include them in our code, though. The real thing to focus on are the individual fields. The format appears to be, in most cases:

Exceptions are checkboxes and radio buttons, which use the format /Value instead of (Value) . Also note that checking a checkbox requires /Yes whereas unchecking it requires just / .

With that in mind, we can quickly create a basic PHP file that will output an FDF file.

What we need to do now is loop through the different key/value pairs passed ot us in $_POST, and depending on the type of field, add a string to FDF data in the correct format. Below is an example regarding a textbox, but the code files I provide cover all of the field types.

Once we have our FDF data stored safely in $fdf , we’ll need to output it to a file. I created a folder named output – you may need to change the permissions or ownership of this folder in order to allow PHP to write to it. In addition to the text in $fdf , we’ll also need the boilerplate information that I mentioned above. I hid those away in functions to make things a bit cleaner. Finally, we’ll need a filename – because I don’t want the file to overwrite itself every time the script is ran, I used a timestamp in the name of the file. You may want to add other unique elements to the file (like data from the form), or some extra checks to make sure that no such file exists already.

Finally, we get to the good part – using PDFtk to combine this FDF form data with the original PDF and outputting a new PDF. If you haven’t yet installed PDFtk, now’s the time – you can find more information about it here , or you can Google “PDFtk install” + your operating system of choice.

The shell command for PDFtk is as follows:

Roughly translated, this means: with the PDFtk program, use the file originalForm.pdf. We want to fill that form, and specifically we want to fill it using the FDF data in formData.fdf. Once the form is filled, save its output in filledFormWithData.pdf

In PHP, we can execute this shell command by way of the exec() function. Finally, to make debugging a bit easier, I output not only where the PDF is on the server, but also a link back home (to easily fill the form out again), and I embed the new PDF as an iframe so it’s easy to see. Any of this can be easily customized.

You should be very careful any time you use the exec() function, as it is executing a shell script on the webserver itself. This may also require additional permissions from your webhost’s tech support if they have configured PHP to not allow the exec() function for security reasons.

Although it’s unfortunate that there’s no pure PHP, drop-in solution, I found PDFtk to be very easy to work with. Check out the sample project here and let me know what you think. I rearranged the code a bit to make it read nicely, and over-commented so it’s very obvious what I’m doing.

This tutorial is magnificent

I wish FPDM was updated to work with PHP 8.2, as all I am trying to do is fill out existing fields in a PDF and flatten it.

I spent awhile trying different solutions, and what I found that fits my needs is a php library based around the PDF Toolkit (pdftk) used in this tutorial.

https://github.com/mikehaertl/php-pdftk

If you don’t want to execute commands from PHP like myself, give this library a shot. There may be better solutions as more libraries are updated to work with PHP 8.2, but I found this the best for now. The only issue it has, and this may be a deal breaker for some people, is if you need UTF-8 encoding for non-ASCII characters, it may not be able to flatten PDFs correctly.

I asked my support guys (hosting company) to install PDFtk, got confirmation from them, then uploaded your Sample Project AS IS ( https://core.fragolan.com/pdf ), updated permissions to the output/ folder to 777… for some reason I just get the FDF file but not the PDF file… ideas?

I see the PDF file at that link just fine!

Do you know how you can replace an image form field in a PDF using this application?

I can replace text easy enough but can’t get an image form field to accept an image from my scripts.

Leave a Comment Cancel Comment

Your email address will not be published. Required fields are marked *

SEND A MESSAGE

Most scores from the August 24th SAT are now available. View your scores.

School and District Resource Center

We've put together this collection of resources to help you and your staff as you prepare for and communicate with students, parents, and caregivers about the value of each test in the digital SAT Suite of Assessments and what they need to know to get ready for them.

For Students

Use these resources to help students know what to expect from the digital SAT Suite and what's in it for them. Find directions on how to translate closed captions for the videos into any language. Closed Captions Instructions (.pdf)

What to expect with the digital SAT School Day

If you're planning to take the digital SAT on a school day, here's what you can expect.

Understanding Your Score Report For The Digital SAT On A School Day

Your digital SAT score report provides a lot of feedback as you prepare for your future after high school--college, career, or wherever your path leads you.

What to expect with the digital PSAT/NMSQT

If you're planning to take the digital PSAT/NMSQT, here's what you can expect.

Understanding Your Digital PSAT/NMSQT Scores

Your digital PSAT/NMSQT score report provides a lot of feedback as you prepare for the SAT and for your future after high school—college, career, or wherever your path leads you.

What to expect with the digital PSAT 10

If you're planning to take the digital PSAT 10, here's what you can expect.

Understanding Your Digital PSAT 10 Scores

Your digital PSAT 10 score report provides a lot of feedback as you prepare for the PSAT/NMSQT, the SAT and for your future after high school—college, career, or wherever your path leads you.

What to expect with the digital PSAT 8/9

If you're planning to take the digital PSAT 8/9, here's what you can expect.

Understanding Your Digital PSAT 8/9 Scores

Your digital PSAT 8/9 score report provides a lot of feedback so you, your family, and your teachers can see your strengths and areas that you need to focus on so you can continue to improve and plan for high school and beyond.

What to Expect from the Digital SAT

If you're planning to take the digital SAT on a weekend, here's what you can expect.

Understanding Your Digital SAT Score Report

Your digital SAT score report provides a lot of feedback as you prepare for your future after high school, college, career, or wherever your path leads you.

Customizable Student Flyers

Help students understand the value of the digital SAT, PSAT/NMSQT, and PSAT 10 and customize with your school's administration details.

Digital SAT Student Flyer

Digital psat/nmsqt student flyer, digital psat 10 student flyer, printable student posters.

Download, customize, print, and hang these posters in your school to help your students understand the benefits of each assessment in the digital SAT Suite.

Digital SAT Student Poster

Psat/nmsqt student poster, digital psat 10 student poster, psat 8/9 student poster, for parents and caregivers.

Use these resources at back-to-school night or anytime you want to communicate with families about the benefits the tests in the digital SAT Suite provide for their children.

Principal to Parent Email Templates

Use these customizable email templates as you communicate with parents and caregivers about your fall and/or spring administrations of the digital SAT Suite of Assessments.

SAT Weekend Principal to Parent Email Template

K–12 educators should use this customizable email template to let parents know about an upcoming SAT Weekend administration, the benefits for students, and what parents should know about the transition to digital.

SAT School Day Principal to Parent Email Template

K–12 educators should use this customizable email template to let parents know about an upcoming SAT School Day administration, the benefits for students, and what parents should know about the transition to digital.

PSAT/NMSQT Principal to Parent Email Template

K–12 educators should use this customizable email template to let parents know about an upcoming PSAT/NMSQT administration, the benefits for students, and what parents should know about the transition to digital.

PSAT 10 Principal to Parent Email Template

K–12 educators should use this customizable email template to let parents know about an upcoming PSAT 10 administration, the benefits for students, and what parents should know about the transition to digital.

PSAT 8/9 Principal to Parent Email Template

K–12 educators should use this customizable email template to let parents know about an upcoming PSAT 8/9 administration, the benefits for students, and what parents should know about the transition to digital.

Website Copy Templates

Leverage these website copy templates to inform students and families of the benefits of the digital SAT Suite of Assessments and customize with your school's specific administration details.

SAT Website Copy Template

K–12 educators should use this customizable website copy template to inform students and families about an upcoming SAT administration, the benefits for students, and information about the transition to digital.

PSAT/NMSQT Website Copy Template

K–12 educators should use this customizable website copy template to inform students and families about an upcoming PSAT/NMSQT administration, the benefits for students, and information about the transition to digital.

PSAT 10 Website Copy Template

K–12 educators should use this customizable website copy template to inform students and families about an upcoming PSAT 10 administration, the benefits for students, and information about the transition to digital.

PSAT 8/9 Website Copy Template

K–12 educators should use this customizable website copy template to inform students and families about an upcoming PSAT 8/9 administration, the benefits for students, and information about the transition to digital.

Digital SAT Suite Flyers

Share these flyers (available in English and Spanish) with parents and caregivers to help them understand the benefits of the digital PSAT 8/9, PSAT 10, PSAT/NMSQT, and SAT. Remember to download and customize the form fields before saving and sending.

Parent's Guide to the Digital SAT

Parent's guide to the digital sat (spanish), parent's guide to the digital psat/nmsqt, parent's guide to the digital psat/nmsqt (spanish), parent's guide to the digital psat 10, parent's guide to the digital psat 10 (spanish), parent's guide to the digital psat 8/9, parent's guide to the digital psat 8/9 (spanish), principal to parent powerpoint.

Leverage this PowerPoint slide template to communicate with parents and caregivers about the benefits of each assessment in the SAT Suite and the transition to digital testing.

  • Presentation

Use these resources to educate your school staff about the value of the digital SAT Suite.

Share these flyers with school and district staff to help them understand the benefits of the digital PSAT 8/9, PSAT 10, PSAT/NMSQT, and SAT.

Educator's Guide to the Digital SAT

Educator's guide to the digital psat/nmsqt, educator's guide to the digital psat 10, educator's guide to the digital psat 8/9, social media templates.

Spread the word about SAT School Day, and the importance of practice, to students and parents with these social media copy templates and images.

  • Compressed File

Additional Tools and Resources

Counselor resources.

Explore this collection of counselor resources and information to advise your students about the SAT Suite of Assessments.

  • Go to Counselors

SAT Suite of Assessments–Educator Guide

Explore detailed information about each assessment in the SAT Suite.

In-School Educator Experience

Explore information about purchasing, preparing for, and administering the digital Suite.

Student Guides

These guides provide helpful information for students taking the SAT Suite of Assessments. Download and learn what to expect ahead of test day.

SAT Student Guide

This guide provides helpful information for students taking the SAT during a weekend administration in Fall 2024.

SAT School Day Student Guide

Find information about the SAT School Day, with advice about preparing for and taking the test. The guide also includes the testing rules.

PSAT/NMSQT Student Guide

Find information about the PSAT/NMSQT, with advice about preparing for and taking the test. The guide also includes the testing rules and information about the National Merit Scholarship Program.

PSAT 10 Student Guide

Information for students about the PSAT 10, with test-taking advice, practice information, and testing rules.

PSAT 8/9 Student Guide

Find information about the PSAT 8/9, with advice about preparing for and taking the test. The guide also includes the testing rules.

BigFuture Toolkit for Counselors

Introduce students to the Career Insights feature of their SAT Suite score report and other BigFuture tools that help students plan for life after high school.

BigFuture School and Connections

Learn how the BigFuture School mobile app and Connections program, available exclusively to certain school day test takers, spark students' interest in planning for the future.

PHP Tutorial

Php advanced, mysql database, php examples, php reference, php introduction.

PHP code is executed on the server.

What You Should Already Know

Before you continue you should have a basic understanding of the following:

If you want to study these subjects first, find the tutorials on our Home page .

What is PHP?

  • PHP is an acronym for "PHP: Hypertext Preprocessor"
  • PHP is a widely-used, open source scripting language
  • PHP scripts are executed on the server
  • PHP is free to download and use

PHP is an amazing and popular language!

It is powerful enough to be at the core of the biggest blogging system on the web (WordPress)! It is deep enough to run large social networks! It is also easy enough to be a beginner's first server side language!

What is a PHP File?

  • PHP files can contain text, HTML, CSS, JavaScript, and PHP code
  • PHP code is executed on the server, and the result is returned to the browser as plain HTML
  • PHP files have extension " .php "

What Can PHP Do?

  • PHP can generate dynamic page content
  • PHP can create, open, read, write, delete, and close files on the server
  • PHP can collect form data
  • PHP can send and receive cookies
  • PHP can add, delete, modify data in your database
  • PHP can be used to control user-access
  • PHP can encrypt data

With PHP you are not limited to output HTML. You can output images or PDF files. You can also output any text, such as XHTML and XML.

Advertisement

  • PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP supports a wide range of databases
  • PHP is free. Download it from the official PHP resource: www.php.net
  • PHP is easy to learn and runs efficiently on the server side

What's new in PHP 7

  • PHP 7 is much faster than the previous popular stable release (PHP 5.6)
  • PHP 7 has improved Error Handling
  • PHP 7 supports stricter Type Declarations for function arguments
  • PHP 7 supports new operators (like the spaceship operator: <=> )

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

COMMENTS

  1. PDF PHP Programming Cookbook

    PHP Programming Cookbook

  2. PHP All Exercises & Assignments

    Tutorials Class provides you exercises on PHP basics, variables, operators, loops, forms, and database. Once you learn PHP, it is important to practice to understand PHP concepts. This will also help you with preparing for PHP Interview Questions. Here, you will find a list of PHP programs, along with problem description and solution.

  3. PDF Unit 1: Introduction to PHP

    PHP is a server-side scripting language, usually used to create web applications in combination with a web server, such as Apache. PHP can also be used to create command-line scripts akin to Perl or shell scripts, but such use is much less common than PHP's use as a web language. MySQL is an open source, SQL relational database management ...

  4. PHP: Assignment

    PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world. Downloads; ... An exception to the usual assignment by value behaviour within PHP occurs with object s, which are assigned by reference. Objects may be explicitly copied via the clone keyword.

  5. PHP Exercises, Practice, Solution

    Weekly Trends and Language Statistics. PHP Exercises, Practice, Solution: PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

  6. PDF PHP Tutorial From beginner to master

    PHP Tutorial From beginner to master. PHP is a powerfulbeginner to mastertool for maki. g dynamic and interactive Web pages.PHP is the widely-used, free, and efficient alternative to. In our PHP tutorial you will learn about PHP, and how to execute scripts on your server.

  7. PDF Introduction to PHP

    The following is a quick introduction and summary of many aspects of the PHP language for those who have some programming experience. Although this overview is not intended to be an exhaustive examination of PHP, it is comprehensive enough for you to get started building non-trivial web applications with PHP.

  8. PDF Advanced PHP Programming: A practical guide to developing large-scale

    The PHP Request Life Cycle 492 The SAPI Layer 494 The PHP Core 496 The PHP Extension API 497 The Zend Extension API 498 How All the Pieces Fit Together 500 Further Reading 502 21 Extending PHP: Part I 503 Extension Basics 504 Creating an Extension Stub 504 Building and Enabling Extensions 507 Using Functions 508 Managing Types and Memory 511

  9. PDF Sathyabama Institute of Science and Technolgoy Department of

    •PHP is an acronym for "PHP: Hypertext Preprocessor" • PHP is a widely-used, open source scripting language • PHP scripts are executed on the server • PHP is free to download and use What is a PHP File? • PHP files can contain text, HTML, CSS, JavaScript, and PHP code • PHP code are executed on the server, and the result is returned to the browser ...

  10. Handwritten PHP notes pdf free download lecture notes bca

    We have provided complete PHP handwritten notes pdf for any university student of BCA, MCA, B.Sc, B.Tech CSE, M.Tech branch to enhance more knowledge about the subject and to score better marks in their PHP exam. Free PHP notes pdf are very useful for PHP students in enhancing their preparation and improving their chances of success in PHP exam.

  11. PDF About the Tutorial

    About the Tutorial. The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web-based software applications. This tutorial will help you understand the basics of PHP and how to put it in practice.

  12. PHP Cheat Sheet (.PDF Version Included)

    PHP Cheat Sheet. Our PHP cheat sheet aims to help anyone trying to get proficient in or improve their knowledge of PHP. The programming language is among the most popular in web development. It's in the heart of WordPress, the world's most popular CMS, and also forms the base of other platforms like Joomla and Drupal.

  13. php-assignment/pdf.php at master · MicoDan/php-assignment

    this is the updated assignment of php. Contribute to MicoDan/php-assignment development by creating an account on GitHub.

  14. The PHP Handbook

    The PHP Handbook - Learn PHP for Beginners

  15. (PDF) Advanced PHP programming

    Download Free PDF. Advanced PHP programming. Advanced PHP programming. Mohammed Musthafa. 2004. ... pages in Web development. We propose PhpSync, a novel automatic locating/fixing tool for HTML validation errors in PHP-based Web applications. Download Free PDF ... An example might be using a variable in a non-assignment expression before it has ...

  16. PHP Operators

    PHP Operators. Operators are used to perform operations on variables and values. PHP divides the operators in the following groups: Arithmetic operators. Assignment operators. Comparison operators. Increment/Decrement operators. Logical operators. String operators.

  17. PHP Assignment

    php_assignment.docx - Free download as Word Doc (.doc / .docx), PDF File (.pdf), Text File (.txt) or read online for free. The document contains PHP code to validate email addresses. It defines a HTML form to accept an email address from the user. When submitted, the PHP code uses the checkdnsrr() function to check if the domain portion of the email exists in the DNS records, and returns ...

  18. Fill Out a PDF Form Using PHP

    Once the form is filled, save its output in filledFormWithData.pdf. In PHP, we can execute this shell command by way of the exec() function. Finally, to make debugging a bit easier, I output not only where the PDF is on the server, but also a link back home (to easily fill the form out again), and I embed the new PDF as an iframe so it's easy ...

  19. PDF lab debug : Disastrous Debugging Stack or Heap? lifetimes. The stack

    Copying Correctly When copying variables, we need to think about two things - what we want to copy (value or address) and what is the type of the variable we

  20. PDF Ambassadorial Assignments Overseas 9/5/2024 Office of Presidential

    Ambassadorial Assignments Overseas Office of Presidential Appointments (GTM/PAS) 9/5/2024. Country/Organization Name. Additional Countries. Name; State. Career Status Oath of Office. ASEAN - Representative of the United States of America to the Association of Southeast Asian Nations, with the rank

  21. School and District Resource Center

    PDF; 1.38 MB; Download. PSAT 10 Student Guide Information for students about the PSAT 10, with test-taking advice, practice information, and testing rules. PDF; 897.55 KB; Download. PSAT 8/9 Student Guide Find information about the PSAT 8/9, with advice about preparing for and taking the test. The guide also includes the testing rules.

  22. PHP Introduction

    PHP is an acronym for "PHP: Hypertext Preprocessor". PHP is a widely-used, open source scripting language. PHP scripts are executed on the server. PHP is free to download and use. PHP is an amazing and popular language! It is powerful enough to be at the core of the biggest blogging system on the web (WordPress)!

  23. PDF CSO # Assignment Description # of firms required

    needed based on current information and funding availability. Individual assignment information is subject to change prior to issuing a solicitation. In most cases, the solicitation will be issued within 3 months of appearing on this list. All inquiries regarding the information contained herein must go through the Consultant Selection Office ...

  24. PDF P What's Story?

    •',animallength. •ˆ,organismaldensity. •˙,maximumappliedforceperunitareaoftissue. •b,maximummetabolicrateperunitmass(b hasthedimensionsofpowerper