0% found this document useful (0 votes)
23 views14 pages

PHP Notes

The document provides comprehensive notes on PHP, covering topics from basic syntax and variables to advanced concepts like object-oriented programming and database interactions. It includes sections on control structures, functions, arrays, web page handling, and sessions, along with practical code examples. The notes aim to equip readers with the foundational and advanced skills needed for PHP development.

Uploaded by

sakhataj3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views14 pages

PHP Notes

The document provides comprehensive notes on PHP, covering topics from basic syntax and variables to advanced concepts like object-oriented programming and database interactions. It includes sections on control structures, functions, arrays, web page handling, and sessions, along with practical code examples. The notes aim to equip readers with the foundational and advanced skills needed for PHP development.

Uploaded by

sakhataj3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Comprehensive PHP Notes: From Basic

to Advanced
Part 1: The Basics
1.1 Introduction to PHP
●​ What is PHP? PHP stands for "PHP: Hypertext Preprocessor". It's a widely-used,
open-source scripting language especially suited for web development and can be
embedded into HTML.
●​ What can PHP do?
○​ Generate dynamic page content.
○​ Create, open, read, write, delete, and close files on the server.
○​ Collect form data.
○​ Send and receive cookies.
○​ Add, delete, modify data in your database.
○​ Control user-access.
○​ Encrypt data.
●​ Why PHP?
○​ Runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.).
○​ Compatible with almost all servers used today (Apache, IIS, etc.).
○​ Supports a wide range of databases.
○​ It's free and easy to learn.

1.2 Environment Setup


To start developing with PHP, you need a web server with PHP support. The most common
setup is a LAMP (Linux, Apache, MySQL, PHP), WAMP (Windows, Apache, MySQL, PHP), or
MAMP (Mac, Apache, MySQL, PHP) stack. You can install these stacks using software like
XAMPP or WampServer.

1.3 Basic Syntax


●​ A PHP script is executed on the server.
●​ PHP scripts start with <?php and end with ?>.
●​ PHP statements end with a semicolon ;.
<?php​
// This is a single-line comment​
# This is also a single-line comment​

/*​
This is a multi-line comment​
block.​
*/​

echo "Hello, World!";​
?>​

1.4 Variables
●​ Variables are containers for storing information.
●​ In PHP, a variable starts with the $ sign, followed by the name of the variable.
●​ Variable names are case-sensitive ($age and $AGE are two different variables).
<?php​
$greeting = "Hello";​
$name = "PHP Developer";​
$age = 25;​
$pi = 3.14;​

echo $greeting . ", " . $name . "!"; // Output: Hello, PHP Developer!​
echo "You are " . $age . " years old."; // Output: You are 25 years
old.​
?>​

1.5 Data Types


PHP supports the following data types:
●​ String: A sequence of characters.
●​ Integer: Non-decimal numbers.
●​ Float (Double): Numbers with a decimal point.
●​ Boolean: Represents two possible states: TRUE or FALSE.
●​ Array: Stores multiple values in one single variable.
●​ Object: An instance of a class.
●​ NULL: A special data type which can have only one value: NULL.
●​ Resource: A special variable, holding a reference to an external resource (like a
database connection).
<?php​
$string_var = "This is a string";​
$int_var = 123;​
$float_var = 10.5;​
$bool_var = true;​
$array_var = array("Apple", "Banana", "Cherry");​
$null_var = null;​

var_dump($string_var); // Dumps information about a variable​
echo "<br>";​
var_dump($int_var);​
?>​
1.6 Constants
Constants are like variables, except that once they are defined, they cannot be changed.
●​ Use the define() function to create a constant.
●​ By convention, constant names are in uppercase.
<?php​
define("SITE_URL", "https://www.example.com");​
define("DATABASE_NAME", "my_db");​

echo "Thank you for visiting " . SITE_URL;​
?>​

Part 2: Control Structures


2.1 Conditional Statements
●​ if, else, elseif: Execute code based on conditions.
<?php​
$hour = date("H");​

if ($hour < "12") {​
echo "Good morning!";​
} elseif ($hour < "18") {​
echo "Good afternoon!";​
} else {​
echo "Good evening!";​
}​
?>​

●​ switch: Selects one of many blocks of code to be executed.


<?php​
$fav_color = "red";​

switch ($fav_color) {​
case "red":​
echo "Your favorite color is red!";​
break;​
case "blue":​
echo "Your favorite color is blue!";​
break;​
case "green":​
echo "Your favorite color is green!";​
break;​
default:​
echo "Your favorite color is neither red, blue, nor green!";​
}​
?>​

2.2 Loops
●​ while: Loops through a block of code as long as the specified condition is true.
<?php​
$i = 1;​
while ($i <= 5) {​
echo "The number is " . $i . "<br>";​
$i++;​
}​
?>​

●​ do...while: Loops through a block of code once, and then repeats the loop as long as the
specified condition is true.
<?php​
$i = 1;​
do {​
echo "The number is " . $i . "<br>";​
$i++;​
} while ($i <= 5);​
?>​

●​ for: Loops through a block of code a specified number of times.


<?php​
for ($i = 0; $i < 5; $i++) {​
echo "The number is " . $i . "<br>";​
}​
?>​

●​ foreach: Loops through a block of code for each element in an array.


<?php​
$colors = array("red", "green", "blue", "yellow");​

foreach ($colors as $value) {​
echo $value . "<br>";​
}​
?>​

Part 3: Functions
3.1 User-Defined Functions
A function is a block of statements that can be used repeatedly in a program.
<?php​
function sayHello() {​
echo "Hello there!<br>";​
}​

sayHello(); // Call the function​

// Function with arguments​
function greetUser($name) {​
echo "Hello, " . $name . "!<br>";​
}​

greetUser("John"); // Output: Hello, John!​

// Function with a return value​
function add($x, $y) {​
return $x + $y;​
}​

$sum = add(5, 10);​
echo "Sum: " . $sum; // Output: Sum: 15​
?>​

3.2 Variable Scope


●​ Local Scope: A variable declared within a function has a LOCAL SCOPE and can only
be accessed within that function.
●​ Global Scope: 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.
●​ Static Scope: When a function is completed, all of its variables are normally deleted.
However, sometimes you want a local variable NOT to be deleted. Use the static
keyword.
<?php​
$x = 5; // global scope​

function myTest() {​
global $x; // use global keyword​
$y = 10; // local scope​
echo "Variable x inside function is: $x <br>";​
echo "Variable y inside function is: $y <br>";​
}​

myTest();​

echo "Variable x outside function is: $x <br>";​
// echo "Variable y outside function is: $y"; // This will cause an
error​
?>​

Part 4: Arrays
4.1 Array Types
●​ Indexed arrays: Arrays with a numeric index.
●​ Associative arrays: Arrays with named keys.
●​ Multidimensional arrays: Arrays containing one or more arrays.
<?php​
// Indexed array​
$cars = array("Volvo", "BMW", "Toyota");​
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] .
".<br>";​

// Associative array​
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");​
echo "Peter is " . $age['Peter'] . " years old.<br>";​

// Multidimensional array​
$students = array(​
"Peter" => array("Math"=>85, "Science"=>92),​
"Ben" => array("Math"=>78, "Science"=>88)​
);​
echo "Peter's Math score: " . $students['Peter']['Math'];​
?>​

4.2 Useful Array Functions


●​ count(): Get the length of an array.
●​ sort(): Sort arrays in ascending order.
●​ rsort(): Sort arrays in descending order.
●​ asort(): Sort associative arrays in ascending order, according to the value.
●​ ksort(): Sort associative arrays in ascending order, according to the key.

Part 5: Working with Web Pages


5.1 Superglobals
Superglobals are built-in variables that are always available in all scopes.
●​ $GLOBALS
●​ $_SERVER
●​ $_REQUEST
●​ $_POST
●​ $_GET
●​ $_FILES
●​ $_ENV
●​ $_COOKIE
●​ $_SESSION

5.2 Handling Forms ($_GET & $_POST)


●​ GET: Form data is sent as URL variables.
●​ POST: Form data is sent in the HTTP request body. POST is more secure.
HTML Form (index.html):
<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>​

PHP Script (welcome.php):


<?php​
// Always sanitize user input!​
$name = htmlspecialchars($_POST['name']);​
$email = htmlspecialchars($_POST['email']);​

echo "Welcome " . $name . "<br>";​
echo "Your email address is: " . $email;​
?>​

5.3 Cookies
A cookie is often used to identify a user. It's a small file that the server embeds on the user's
computer.
<?php​
$cookie_name = "user";​
$cookie_value = "John Doe";​
// setcookie(name, value, expire, path, domain, secure, httponly);​
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); //
86400 = 1 day​

if(!isset($_COOKIE[$cookie_name])) {​
echo "Cookie named '" . $cookie_name . "' is not set!";​
} else {​
echo "Cookie '" . $cookie_name . "' is set!<br>";​
echo "Value is: " . $_COOKIE[$cookie_name];​
}​
?>​
5.4 Sessions
A session is a way to store information (in variables) to be used across multiple pages. Unlike a
cookie, the information is not stored on the user's computer.
Start a session (page1.php):
<?php​
// Start the session​
session_start();​

// Set session variables​
$_SESSION["favcolor"] = "green";​
$_SESSION["favanimal"] = "cat";​
echo "Session variables are set.";​
?>​

Get session data (page2.php):


<?php​
session_start();​

// Echo session variables that were set on page1.php​
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";​
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";​
?>​

Part 6: Object-Oriented Programming (OOP) in PHP


6.1 Classes and Objects
●​ Class: A template for objects.
●​ Object: An instance of a class.
<?php​
class Car {​
// Properties​
public $color;​
public $model;​

// Constructor​
public function __construct($color, $model) {​
$this->color = $color;​
$this->model = $model;​
}​

// Method​
public function getMessage() {​
return "My car is a " . $this->color . " " . $this->model .
"!";​
}​
}​

// Create an object​
$myCar = new Car("black", "Volvo");​
echo $myCar->getMessage();​
?>​

6.2 Access Modifiers


●​ public: The property or method can be accessed from everywhere. This is the default.
●​ protected: The property or method can be accessed within the class and by classes
derived from that class.
●​ private: The property or method can ONLY be accessed within the class.

6.3 Inheritance
Inheritance is when a class derives from another class. The child class will inherit all the public
and protected properties and methods from the parent class.
<?php​
// Parent class​
class Vehicle {​
public $brand;​
public function __construct($brand) {​
$this->brand = $brand;​
}​
public function honk() {​
return "Tuut, tuut!";​
}​
}​

// Child class​
class Motorcycle extends Vehicle {​
public function getMessage() {​
return "My motorcycle is a " . $this->brand . ".";​
}​
}​

$myMotorcycle = new Motorcycle("Honda");​
echo $myMotorcycle->getMessage();​
echo "<br>";​
echo $myMotorcycle->honk();​
?>​

6.4 Static Methods & Properties


Static methods/properties can be called directly - without creating an instance of a class.
<?php​
class Greeting {​
public static function welcome() {​
echo "Hello World!";​
}​
}​

// Call static method​
Greeting::welcome();​
?>​

6.5 Abstract Classes and Methods


An abstract class is a class that contains at least one abstract method. An abstract method is a
method that is declared, but not implemented in the code.
<?php​
abstract class ParentClass {​
// Abstract method with an argument​
abstract protected function prefixName($name);​
}​

class ChildClass extends ParentClass {​
public function prefixName($name) {​
if ($name == "John Doe") {​
$prefix = "Mr.";​
} elseif ($name == "Jane Doe") {​
$prefix = "Mrs.";​
} else {​
$prefix = "";​
}​
return "{$prefix} {$name}";​
}​
}​

$class = new ChildClass;​
echo $class->prefixName("John Doe");​
?>​

6.6 Traits
Traits are used to declare methods that can be used in multiple classes.
<?php​
trait message1 {​
public function msg1() {​
echo "OOP is fun! ";​
}​
}​

class Welcome {​
use message1;​
}​

$obj = new Welcome();​
$obj->msg1();​
?>​

Part 7: Working with Databases (MySQLi & PDO)


PHP needs a way to connect to and interact with databases. The two most common ways are
MySQLi (i for improved) and PDO (PHP Data Objects). PDO is more versatile as it can work
with 12 different database systems, whereas MySQLi will only work with MySQL databases.
We'll focus on PDO.

7.1 Connecting to MySQL with PDO


<?php​
$servername = "localhost";​
$username = "username"; // Your database username​
$password = "password"; // Your database password​
$dbname = "myDB"; // Your database name​

try {​
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password);​
// set the PDO error mode to exception​
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);​
echo "Connected successfully";​
} catch(PDOException $e) {​
echo "Connection failed: " . $e->getMessage();​
}​
?>​

7.2 CRUD Operations with PDO


Create, Read, Update, Delete.
●​ Create (INSERT):
// Prepare statement to prevent SQL injection​
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname,
email) VALUES (:firstname, :lastname, :email)");​
$stmt->bindParam(':firstname', $firstname);​
$stmt->bindParam(':lastname', $lastname);​
$stmt->bindParam(':email', $email);​

// insert a row​
$firstname = "John";​
$lastname = "Doe";​
$email = "[email protected]";​
$stmt->execute();​

●​ Read (SELECT):
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM
MyGuests");​
$stmt->execute();​

// set the resulting array to associative​
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);​
foreach($stmt->fetchAll() as $k=>$v) {​
echo "Name: " . $v['firstname'] . " " . $v['lastname'] . "<br>";​
}​

●​ Update (UPDATE):
$sql = "UPDATE MyGuests SET lastname='Doe Jr.' WHERE id=2";​
// Prepare statement​
$stmt = $conn->prepare($sql);​
// execute the query​
$stmt->execute();​

●​ Delete (DELETE):
$sql = "DELETE FROM MyGuests WHERE id=3";​
// use exec() because no results are returned​
$conn->exec($sql);​

Part 8: Advanced Topics


8.1 Error Handling
A robust application needs proper error handling.
<?php​
function checkNum($number) {​
if($number>1) {​
throw new Exception("Value must be 1 or below");​
}​
return true;​
}​

try {​
checkNum(2);​
// If the exception is thrown, this text will not be shown​
echo 'If you see this, the number is 1 or below';​
} catch(Exception $e) {​
echo 'Message: ' .$e->getMessage();​
}​
?>​

8.2 File System Functions


PHP can interact with the server's file system.
●​ readfile(): Reads a file and writes it to the output buffer.
●​ fopen(), fread(), fclose(): Open, read, and close files.
●​ fwrite(): Write to a file.
●​ file_get_contents() / file_put_contents(): Simpler ways to read/write files.
<?php​
// Reading a file​
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");​
echo fread($myfile,filesize("webdictionary.txt"));​
fclose($myfile);​

// Writing to a file (this will overwrite the file)​
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");​
$txt = "John Doe\n";​
fwrite($myfile, $txt);​
fclose($myfile);​
?>​

8.3 Security Best Practices


●​ Sanitize Inputs: Never trust user input. Use functions like htmlspecialchars() to prevent
XSS attacks.
●​ Validate Data: Check if the data is in the proper format (e.g., is an email address valid?).
●​ Use Prepared Statements: To prevent SQL injection attacks.
●​ Prevent CSRF (Cross-Site Request Forgery): Use tokens in your forms.
●​ Store Passwords Securely: Use password_hash() to hash passwords and
password_verify() to check them. Do not store passwords in plain text.
<?php​
// Hashing a password​
$password = 'my-secret-password';​
$hashed_password = password_hash($password, PASSWORD_DEFAULT);​

// Verifying a password​
if (password_verify('my-secret-password', $hashed_password)) {​
echo 'Password is valid!';​
} else {​
echo 'Invalid password.';​
}​
?>​

You might also like