PHP (Hypertext Preprocessor) is a popular server-side scripting language designed for web development but also used as a general-purpose programming language.
It is especially suited for creating dynamic web pages and applications.
<h1> Hello from HTML </h1>
<?php
// This is a simple PHP script that outputs "Hello, World!"
echo "Hello, World!";
?>
<p> This is more HTML content. </p>
Hello from HTML
Hello, World!
This is more HTML content.
๐ Concept: Output from PHP is substituted into the HTML at the location of the PHP code.
๐ Concept: It runs on the server, and the client only sees the resulting HTML.
Start MAMP on your machine.
_ Click on โStartโ to start the Apache server.
http://localhost:8888 or http://localhost:8888/MAMP/?language=English in your web browser to verify that the server is running.Edit the file php.ini to configure PHP settings.
On my Mac OS X, the file is located at:
/Applications/MAMP/bin/php/php8.3.28/conf/php.ini
The contents of php.ini look like this:
; PHP's initialization file, generally called php.ini, is responsible for
; configuring many of the aspects of PHP's behavior.
;
; This file is divided into sections, each section having directives that
; configure various aspects of PHP's behavior. Each directive is explained
; via comments in this file.
;
; For more information about setting up PHP, please refer to the
; documentation at https://www.php.net/manual/en/configuration.file.php
Start writing PHP code in your web serverโs document root directory (e.g., htdocs for MAMP).
On my Mac OS X, the document root directory is located at:
/Applications/MAMP/htdocs
In this directory, create a new folder named my_php_site.
In this folder, create a file with a .php extension (e.g., index.php) to start writing your PHP code.
Open your favorite code editor (e.g., VS Code, vi, Sublime Text, or any text editor) to write PHP code.
Write the PHP code in the .php file you created.
<?php
// Your PHP code goes here
echo "Hello World!";
?>
http://localhost:8888/my_php_site/index.php in your web browser to see the output of your PHP code.A PHP script is typically enclosed within <?php and ?> tags.
A PHP file usually has a .php extension.
A PHP script can generate HTML content dynamically.
PHP is loosely typed, meaning you do not need to declare variable types explicitly.
Static typing can be found in C++ or Java, where you must declare the type of a variable before using it.
Dynamic typing means that the type is determined at runtime based on the value assigned to the variable.
For example:
<?php
$age = 25; // $age is an integer
$name = "Alice"; // $name is a string
$price = 19.99; // $price is a float
?>
Example code snippets:
<?php
// Example 1: Variables and Output
$name = "John";
echo "Hello, " . $name . "!"; // Outputs: Hello, John!
?>
<?php
// Example 2: Conditional Statements
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>
<?php
// Example 3: Looping
for ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . "<br>";
}
?>
<?php
// Example 4: Functions
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("Alice"); // Outputs: Hello, Alice!
?>
<?php
// Example 5: Arrays
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
?>
<?php
$number = "10"; // string
$sum = $number + 5; // PHP converts $number to an integer
echo $sum; // Outputs: 15
?>
<?php
$a = 10;
$b = 5;
$sum = $a + $b; // Addition
$difference = $a - $b; // Subtraction
$product = $a * $b; // Multiplication
$quotient = $a / $b; // Division
$isEqual = ($a == $b); // Comparison
$isGreater = ($a > $b); // Comparison
$andCondition = ($a > 5 && $b < 10); // Logical AND
$orCondition = ($a < 5 || $b < 10); // Logical OR
?>
++) and decrement (--) operators to increase or decrease the value of a variable by one.
<?php
$x = 5;
$x++; // Increment: $x is now 6
$y = 10;
$y--; // Decrement: $y is now 9
?>
<?php
$a = 3;
$b = ++$a; // Prefix: $a is incremented to 4, then assigned to $b
$c = $a++; // Postfix: $c is assigned the value 4, then $a is incremented to 5
?>
<?php
$x = 12;
$y = 15 + $x++;
echo "x is $x and y is $y";
$z = 20 + ++$x;
echo "x is $x and y is $y and z is $z";
?>
The . (dot) operator is used for string concatenation
๐ค Remember: The + (plus) operator will try to aggeressively type convert and add
Example code below:
<?php
$a = "Hello " . "World";
echo $a . "\n";
?>
โ ๏ธ NOTE This is not a good practice
Use them sparingly but I show them for the sake of completeness
Try the following code in the online PHP compiler
<?php
$x = 10;
$x += 2;
echo $x;
?>
PHP does aggressive type casting
Floating point
<?php
$x = 56;
$y = 12;
echo $x / $y;
?>
<?php
$z = "100" + 36.25 + TRUE;
echo $z;
?>
Explicit type casting
๐ ๏ธ What will be the output of this code?
<?php
echo "100" + (string) 10;
?>
<?php
echo "100" . string(10)
?>
<?php
echo (int) 9.9 - 1.9;
?>
<?php
echo "Soumya" . 25;
?>
<?php
echo "Soumya" + 25;
?>
Concept ๐ โ ๏ธ There are no errors! Only silent type conversion. Beware!
Concept ๐ โ ๏ธ FALSE and NULL become 0 and TRUE becomes 1.
Concept ๐ โ ๏ธ echo does not show FALSE (since it becomes 0)
== and ===<?php
if (123 == "123") print ("Equal \n");
if (123 === "123") print ("Equal \n");
?>
More fun examples in the video by Dr. Chuck Severance on equality
== Aggressively convert/cast its operands
If a function fails, it can return FALSE!
e.g. strpos() return FALSE if it did not find anything. FALSE can get converted to 0!
๐ โ ๏ธ Concept Hence use === to check if strpos() found the value or not
<?php
/* comment .... */
# comment
?>
Use array keyword
<?php
$str_array = array("Hello", "World");
echo $str_array[1];
?>
array functions ?? (exists), count, sort (sort by values in place), ksort (sort by keys), asort (sort by values)
print_r (print array), explode (split array by delimiter)
๐ก $_GET (all constituents of end of URL)
call by value (default)
call by reference (use &)
global variables
include
<?php
include "header.php";
?>
PHP can be used to submit data from forms
If using GET, variables saved in $_GET
If using POST, variables saved in $_POST
Video comparing GET vs POST and how variables transferred from client to server
GET is used when you are reading or searching
POST is used when data is being created or modified
๐งฉ ๐ Concept: GET URLs should be idempotent. If you hit refresh, you should get same result. For example, you are searching for a part number URL?partid=890
Search engines also follow URLs (so if your URL has a GET request and it is modifying data, then โฆ.. :-)
GET has an upper limit on the number of bytes you can send
Video outlining different PHP form elements (radio boxes, etc)
<p> Forms in PHP</p>
<form method="post">
<label>Input guess</label>
<input type="text" name="guess" id="guess"/>
<input type="submit">
</form>
$_POST
<?php
print_r($_POST)
?>
๐ Concept: $_POST has all the information in an array. guess (from the name tag in input field) will have the value.
๐ Concept: If you use POST the information will not show up in the URL.
Save the following in form1.php.
On My Mac OS X, this is saved in the folder ` /Applications/MAMP/htdocs/my_php_site`
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "PHP";
echo "I love $txt!";
?>
<p> Forms in PHP</p>
<form method="post">
<label>Input guess</label>
<input type="text" name="guess" id="guess"/>
<input type="submit">
</form>
<pre>
<?php
print_r($_POST)
?>
</pre>
</body>
</html>
MAMP and go to the following http://localhost:8888/my_php_site/form1.phpRadio buttons
Check boxes
Dropdown