PHP Tutorial Remarks
- Internal Links:
- External Links:
My Notes on using the w3schools PHP Tutorial
- Easy Learning with "PHP Tryit"
- PHP Tutorial - Learn PHP
- PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
- PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
- familiarize yourself with the "PHP Tryit" Editor
- Scroll down a bit to see the editor, and click the green "Try it Yourself" button.
- This added an additional tab to my browser with the "W3 PHP Tryit Editor v1.2" page displaying two panes.
- You can edit the php code in the left pane
- and click the green "Run" button to see the response displayed in the right pane.
- A PHP script starts with < ? p h p and and ends with ? >
- Without the spaces! The browser gave me an issue when I originally typed that in without the forced spaces.
- This lesson uses the echo sttm | php.net
using the example of echo "My first PHP script!";
- Make sure there is a semi-colon ; at end of each sttm.
- Except for the tags that represent the start and end of php scripts.
- PHP Introduction | w3schools
- PHP code is executed on the server.
- What You Should Already Know: HTML, CSS, JavaScript
- 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
- 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, PDF files, and even Flash movies. You can also output any text, such as XHTML and XML.
- Why PHP?
- 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: <=>)
- What does the spaceship operator do ?
- PHP Installation | w3schools
- What Do I Need ? - Find a web host with PHP and MySQL support, Or install a web server on your own PC, and then install PHP and MySQL
- What version is GoDaddy using ?
- I kept track in prupis.info/classphp/php2022/php2022.html#phpMyAdminPage: phpMyAdmin page in GoDaddy
- PHP Online Compiler / Editor - example: a simple variable named and assigned: $txt = "PHP"
- PHP Syntax | w3schools | Go to Top
- < ? p h p and ? >
- semi-colon ; at end of each sttm
- keywords (e.g. if, else, while, echo, etc.), classes, functions, user-defined functions are not case-sensitive
- However, all variable names are case-sensitive!
- PHP Comments | w3schools | Go to Top
- Why use comments - to document what is coded, or to block some php code from running.
- single-lined comments use // or #
- multi-lined comments use /* to the */
- can also be used to leave out parts of a code line
- PHP Variables
| w3schools
| php.net
| Go to Top
- PHP Variables
- PHP Variable names starts with the $ sign, followed by the name
- When you assign a text value to a PHP variable, put quotes around the value.
- A PHP variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- PHP Variable names are case-sensitive ($age and $AGE are two different variables)
- PHP Variable names cannot start with a number
- Unlike other programming languages, PHP has no command for declaring a variable.
- It is created the moment you first assign a value to it.
- Output Variables
- The PHP echo statement is often used to output data to the screen.
- The PHP echo statement will output the sum of two variables, ie: echo $x + $y;
- PHP is a Loosely Typed Language
- PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.
- In PHP 7, type declarations were added. This gives an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.
- You will learn more about strict and non-strict requirements, and data type declarations in the w3schools PHP Functions chapter.
- PHP Variables Scope
| w3schools
| php.net
| Go to Top
- PHP variables can be declared anywhere in the script.
- The scope of a variable is the part of the script where the variable can be referenced/used.
- 3 different variable scopes
- A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function
- You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
- A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function
- The global keyword is used to access a global variable from within a function
- To do this, use the global keyword before the variables (inside the function)
- PHP also stores all global variables in an array called $GLOBALS[index].
- The index holds the name of the variable.
- This array is also accessible from within functions and can be used to update global variables directly.
- The static variable
- Normally, when a function is completed/executed, all of its variables are deleted.
- However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
- To do this, use the static keyword when you first declare the variable.
- Example: static $x = 0;
- PHP echo and print
| w3schools
| php.net: echo and
print
| Go to Top
- echo and print are more or less the same. They are both used to output data to the screen.
- The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions.
- echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.
- The echo statement can be used with or without parentheses: echo or echo().
- The print statement can be used with or without parentheses: print or print().
- PHP Data Types
| w3schools
| php.net
| Go to Top
- String, Integer, Float aka Double, Boolean, Array, Object, NULL, Resource
- also introduced var_dump which displays the data type and value.
- String - A string can be any text inside quotes. You can use single or double quotes
- Integer - An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
- Rules for Integers
- An integer must have at least one digit
- An integer must not have a decimal point
- An integer can be either positive or negative
- Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation
- Float aka Double - A float (floating point number) is a number with a decimal point or a number in exponential form.
- Boolean - A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional testing.
- Array - An array stores multiple values in one single variable.
- Object - A class is a template for objects, and an object is an instance of a class.
- Classes and objects are the two main aspects of object-oriented programming.
- A class is a template for objects, and an object is an instance of a class.
- When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.
- Let's assume we have a class named Car. A Car can have properties like model, color, etc. We can define variables like $model, $color, and so on, to hold the values of these properties.
- When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.
- If you create a __construct() function, PHP will automatically call this function when you create an object from a class.
- NULL - Null is a special data type which can have only one value: NULL.
- A variable of data type NULL is a variable that has no value assigned to it.
- Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
- Variables can also be emptied by setting the value to NULL:
- Resource - The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP.
- A common example of using the resource data type is a database call.
- PHP Strings
| w3schools
| php.net
| Go to Top
- A string is a sequence of characters, like "Hello world!".
- PHP String Functions
- strlen() - Return the Length of a String
- str_word_count() - Count Words in a String
- strrev() - Reverse a String
- strpos() - Search For a Text Within a String
- The PHP strpos() function searches for a specific text within a string.
- If a match is found, the function returns the character position of the first match.
- If no match is found, it will return FALSE.
- str_replace() - SReplace Text Within a String
- "Complete List" PHP String Functions
- PHP Numbers
| w3schools
| Go to Top
- Integers, Floats, and Number Strings
- PHP Numbers
- One thing to notice about PHP is that it provides automatic data type conversion.
- So, if you assign an integer value to a variable, the type of that variable will automatically be an integer. Then, if you assign a string to the same variable, the type will change to a string.
- This automatic conversion can sometimes break your code.
- PHP Integers
| php.net
| Go to Top
- 2, 256, -256, 10358, -179567 are all integers.
- An integer is a number without any decimal part.
- An integer data type is a non-decimal number between -2147483648 and 2147483647 in 32 bit systems, and between -9223372036854775808 and 9223372036854775807 in 64 bit systems. A value greater (or lower) than this, will be stored as float, because it exceeds the limit of an integer.
- Note: Another important thing to know is that even if 4 * 2.5 is 10, the result is stored as float, because one of the operands is a float (2.5).
- Here are some rules for integers:
- An integer must have at least one digit
- An integer must NOT have a decimal point
- An integer can be either positive or negative
- Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
- PHP has the following predefined constants for integers:
- PHP_INT_MAX - The largest integer supported
- PHP_INT_MIN - The smallest integer supported
- PHP_INT_SIZE - The size of an integer in bytes
- PHP has the following functions to check if the type of a variable is integer:
- is_int()
- is_integer() - alias of is_int()
- is_long() - alias of is_int()
- PHP Floats
| php.net
| Go to Top
- A float is a number with a decimal point or a number in exponential form.
- The float data type can commonly store a value up to 1.7976931348623E+308 (platform dependent), and have a maximum precision of 14 digits.
- PHP has the following predefined constants for floats (from PHP 7.2):
- PHP_FLOAT_MAX - The largest representable floating point number
- PHP_FLOAT_MIN - The smallest representable positive floating point number
- - PHP_FLOAT_MAX - The smallest representable negative floating point number
- PHP_FLOAT_DIG - The number of decimal digits that can be rounded into a float and back without precision loss
- PHP_FLOAT_EPSILON - The smallest representable positive number x, so that x + 1.0 != 1.0
- PHP has the following functions to check if the type of a variable is float:
- is_float()
- is_double() - alias of is_float()
- PHP Infinity | Go to Top
- A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.
- PHP has the following functions to check if a numeric value is finite or infinite:
- However, the PHP var_dump() function returns the data type and value:
- PHP NaN | Go to Top
- NaN stands for Not a Number.
- NaN is used for impossible mathematical operations.
- PHP has the following functions to check if a value is not a number:
- However, the PHP var_dump() function returns the data type and value:
- example: Invalid calculation will return a NaN value
- PHP Numerical Strings | Go to Top
- The PHP is_numeric() function can be used to find whether a variable is numeric.
- The function returns true if the variable is a number or a numeric string, false otherwise.
- Note: From PHP 7.0: The is_numeric() (php.net) function will return FALSE for numeric strings in hexadecimal form (e.g. 0xf4c3b00c), as they are no longer considered as numeric strings.
- PHP Casting Strings and Floats to Integers | Go to Top
- Sometimes you need to cast a numerical value into another data type.
- The (int), (integer), or intval() function are often used to convert a value to an integer.
- (int), (integer), or intval() (php.net) function
- PHP Math | w3schools | Go to Top
- PHP has a set of math functions that allows you to perform mathematical tasks on numbers.
- Complete list of PHP Math Functions
w3schools
| php.net
- The following functions are displayed as examples:
- PHP pi() - The pi() function returns the value of PI
- PHP min() and max() - The min() and max() functions can be used to find the lowest or highest value in a list of arguments
- PHP abs() - The abs() function returns the absolute (positive) value of a number
- PHP sqrt() - The sqrt() function returns the square root of a number
- PHP round() - The round() function rounds a floating-point number to its nearest integer
- PHP rand() - The rand() function generates a random number
- reserve
My Notes on using the w3schools PHP Tutorial for - PHP Form Handling
PHP - A Simple HTML Form that uses the POST Method
- From the documentation: The example below displays a simple HTML form with two input fields and a submit button:
- Note: I had to replace angle brackets with parentheses.
(html)
(body)
(form action="welcome.php" method="post")
Name: (input type="text" name="name")(br)
E-mail: (input type="text" name="email")(br)
(input type="submit")
(/form)
(/body)
(/html)
About "welcome.php"
- Go to Top
- When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php".
- The form data is sent with the HTTP POST method.
- To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
(html)
(body)
Welcome (?php echo $_POST["name"]; ?)(br)
Your email address is: (?php echo $_POST("email"); ?)
(/body)
(/html)
welcome.php's output
- The output could be something like this:
Welcome John
Your email address is john.doe@example.com
PHP - A Simple HTML Form that uses the GET Method
- The same result could also be achieved using the HTTP GET method:
(html)
(body)
(form action="welcome_get.php" method="get")
Name: (input type="text" name="name")(br)
E-mail: (input type="text" name="email")(br)
(input type="submit")
(/form)
(/body)
(/html)
About "welcome_get.php"
- Go to Top
- and "welcome_get.php" looks like this:
(html)
(body)
Welcome (?php echo $_GET["name"]; ?)(br)
Your email address is: (?php echo $_GET("email"); ?)
(/body)
(/html)
These examples Lacked Security Safe-Guards
- Go to Top
- The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code.
Think SECURITY when processing PHP forms!
- This page does not contain any form validation, it just shows how you can send and retrieve form data.
- However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important to protect your form from hackers and spammers!
PHP Form Handling - GET vs. POST
GET vs. POST
- Go to Top | PHP Form Handling
- Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
- Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
- $_GET is an array of variables passed to the current script via the URL parameters.
- $_POST is an array of variables passed to the current script via the HTTP POST method.
When to use GET?
- Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL).
- GET also has limits on the amount of information to send. The limitation is about 2000 characters.
- However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
- GET may be used for sending non-sensitive data.
- Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?
- Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
- Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
- However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
- Go to Top
- Developers prefer POST for sending form data.
- Next, lets see how we can process PHP forms the secure way!
- PHP Exercises
PHP Form Validation
PHP Form Validation
- Think SECURITY when processing PHP forms!
- These pages will show how to process PHP forms with security in mind. Proper validation of form data is important to protect your form from hackers and spammers!
- The HTML form we will be working at in these chapters, contains various input fields: required and optional text fields, radio buttons, and a submit button:
- The validation rules for the form above are as follows:
- First we will look at the plain HTML code for the form:
Text Fields
- The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks like this:
Radio Buttons
- The gender fields are radio buttons and the HTML code looks like this:
The Form Element
- The HTML code of the form looks like this:
- When the form is submitted, the form data is sent with method="post".
What is the $_SERVER["PHP_SELF"] variable?
- The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script.
- So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error messages on the same page as the form.
What is the htmlspecialchars() function?
- The htmlspecialchars() function converts special characters to HTML entities.
- This means that it will replace HTML characters like < and > with (& l t ;) and (& g t ;).
- This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
Big Note on PHP Form Security
- The $_SERVER["PHP_SELF"] variable can be used by hackers!
- If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.
- Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users.
- then there are examples
How To Avoid $_SERVER["PHP_SELF"] Exploits?
- $_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function.
- then there are examples
Validate Form Data With PHP
- The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.
- When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field:
- (script)location.href('http://www.hacked.com')(/script) - script angle brackets had to be parentheses
- - this would not be executed, because it would be saved as HTML escaped code, like this:
- & l t ; script & g t ; location.href('http://www.hacked.com') & l t; /script & g t ;
- The code is now safe to be displayed on a page or inside an e-mail.
- We will also do two more things when the user submits the form:
- Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
- Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
- The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again).
- We will name the function test_input().
- Now, we can check each $_POST variable with the test_input() function, and the script looks like this:
- here's the example
- Notice that at the start of the script, we check whether the form has been submitted using $_SERVER["REQUEST_METHOD"].
- If the REQUEST_METHOD is POST, then the form has been submitted - and it should be validated. If it has not been submitted, skip the validation and display a blank form.
- However, in the example above, all input fields are optional. The script works fine even if the user does not enter any data.
- The next step is to make input fields required and create error messages if needed.
PHP Form Required
PHP - Required Fields
- From the validation rules table on the previous page, we see that the "Name", "E-mail", and "Gender" fields are required. These fields cannot be empty and must be filled out in the HTML form.
- In the previous chapter, all input fields were optional.
- In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr.
- These error variables will hold error messages for the required fields. We have also added an if else statement for each $_POST variable.
- This checks if the $_POST variable is empty (with the PHP empty() function).
- If it is empty, an error message is stored in the different error variables, and if it is not empty, it sends the user input data through the test_input() function:
PHP - Display The Error Messages
- Then in the HTML form, we add a little script after each required field, which generates the correct error message if needed
- (that is if the user tries to submit the form without filling out the required fields):
- The next step is to validate the input data, that is "Does the Name field contain only letters and whitespace?",
- and "Does the E-mail field contain a valid e-mail address syntax?", and if filled out, "Does the Website field contain a valid URL?".
PHP Form URL/E-mail
PHP - Validate Name
- The code below shows a simple way to check if the name field only contains letters, dashes, apostrophes and whitespaces. If the value of the name field is not valid, then store an error message:
- The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.
PHP - Validate E-mail
- The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.
- In the code below, if the e-mail address is not well-formed, then store an error message:
PHP - Validate URL
- The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL).
- If the URL address syntax is not valid, then store an error message:
PHP - Validate Name, E-mail, and URL
- Now, the script looks like this:
- The next step is to show how to prevent the form from emptying all the input fields when the user submits the form.
PHP Form Complete
PHP - Keep The Values in The Form
- To show the values in the input fields after the user hits the submit button, we add a little PHP script inside the value attribute of the following input fields: name, email, and website.
- In the comment textarea field, we put the script between the <textarea> and </textarea> tags.
- The little script outputs the value of the $name, $email, $website, and $comment variables.
- Then, we also need to show which radio button that was checked. For this, we must manipulate the checked attribute (not the value attribute for radio buttons):
PHP - Complete Form Example
- Here is the complete code for the PHP Form Validation Example:
- First we display the form
Fini
Reserve