Introducing PHP (Features & Basics) Features & Advantages Open Source: Free to use and modify. Cross-platform: Runs on various operating systems (Windows, Linux, macOS). Server-side Scripting: Executes on the server, generating HTML sent to the client. Database Connectivity: Excellent support for various databases (MySQL, PostgreSQL, Oracle). Ease of Learning: Relatively simple syntax, especially for C/Java developers. Performance: With PHP 7+ and JIT, performance is significantly improved. Large Community: Extensive documentation and community support. Comparison: PHP vs. ASP, JSP, PERL Feature PHP ASP JSP PERL Language PHP VBScript/JScript Java PERL Platform Cross-platform Windows (IIS) Cross-platform Cross-platform Open Source Yes No (Microsoft) Yes Yes Database Support Excellent Good Excellent Good Primary Use Web Development Web Development Enterprise Web Text processing, Web Structure of a PHP Program PHP code is embedded within HTML. It starts with <?php and ends with ?> . <!DOCTYPE html> <html> <head> <title>My First PHP Page</title> </head> <body> <h1>Welcome!</h1> <?php // This is a single-line comment echo "<p>Hello from PHP!</p>"; /* This is a multi-line comment */ $name = "World"; echo "<p>Hello, " . $name . "!</p>"; ?> </body> </html> Key PHP Features Server-side Scripting: Handles dynamic content, database interactions, session management. Command Line Scripting: Can be used for shell scripting tasks. Desktop Application Development: Less common, but possible with frameworks like PHP-GTK. Object-Oriented Programming (OOP): Supports classes, objects, inheritance, polymorphism. Strong Community & Libraries: Vast ecosystem of frameworks (Laravel, Symfony), CMS (WordPress, Drupal). Error Reporting: Flexible error handling mechanisms. Variables, Data Types & Constants Data Types Scalar Types: Boolean: true or false . Integer: Whole numbers (e.g., 10 , -5 ). Float (Double): Numbers with decimal points (e.g., 3.14 , 2.5e3 ). String: Sequence of characters (e.g., "Hello" , 'PHP' ). Compound Types: Array: Stores multiple values in a single variable. Object: Instances of user-defined classes. Special Types: Resource: Special variables holding references to external resources (e.g., database connection). NULL: A variable with no value. Variable Destruction Variables are automatically destroyed when their scope ends (e.g., function execution completes, script finishes). You can explicitly destroy a variable using unset() . <?php $myVar = "some value"; echo $myVar; // Outputs: some value unset($myVar); // echo $myVar; // This would cause an error as $myVar no longer exists ?> Controlling Program Flow Conditional Statements if statement: Executes code if a condition is true. <?php $a = 10; if ($a > 5) { echo "a is greater than 5"; } ?> if...else statement: Executes one block if true, another if false. <?php $b = 3; if ($b % 2 == 0) { echo "b is even"; } else { echo "b is odd"; } ?> if...elseif...else statement: Multiple conditions. <?php $grade = 85; if ($grade >= 90) { echo "A"; } elseif ($grade >= 80) { echo "B"; } else { echo "C"; } ?> switch statement: Tests a variable against multiple values. <?php $day = "Mon"; switch ($day) { case "Mon": echo "Monday"; break; case "Tue": echo "Tuesday"; break; default: echo "Other day"; } ?> Looping do-while loop: Executes at least once, then checks condition. <?php $i = 0; do { echo $i . " "; $i++; } while ($i foreach loop: Iterates over arrays. <?php $colors = array("red", "green", "blue"); foreach ($colors as $color) { echo $color . "<br>"; } ?> while loop: Checks condition, then executes. <?php $count = 0; while ($count Practical Logic Display today's date and check for leap year: <?php $currentYear = date("Y"); echo "Today's Date: " . date("Y-m-d") . "<br>"; if (($currentYear % 4 == 0 && $currentYear % 100 != 0) || ($currentYear % 400 == 0)) { echo $currentYear . " is a leap year."; } else { echo $currentYear . " is not a leap year."; } ?> Check if a number is a palindrome: <?php function isPalindrome($number) { $originalNumber = $number; $reverseNumber = 0; while ($number > 0) { $remainder = $number % 10; $reverseNumber = $reverseNumber * 10 + $remainder; $number = (int)($number / 10); } return $originalNumber == $reverseNumber; } $num = 121; if (isPalindrome($num)) { echo $num . " is a palindrome."; } else { echo $num . " is not a palindrome."; } ?> Functions, Arrays & Files Functions Fibonacci series using functions: <?php function fibonacci($n) { $a = 0; $b = 1; $series = []; if ($n >= 1) $series[] = $a; if ($n >= 2) $series[] = $b; for ($i = 2; $i < $n; $i++) { $next = $a + $b; $series[] = $next; $a = $b; $b = $next; } return $series; } $numTerms = 8; echo "Fibonacci Series up to " . $numTerms . " terms: " . implode(", ", fibonacci($numTerms)); ?> Factorial and sum of array numbers: <?php function factorial($n) { $result = 1; for ($i = 1; $i <= $n; $i++) { $result *= $i; } return $result; } function sumArray(array $arr) { $sum = 0; foreach ($arr as $value) { $sum += $value; } return $sum; } $number = 5; echo "Factorial of " . $number . ": " . factorial($number) . "<br>"; $myArray = [10, 20, 30, 40]; echo "Sum of array elements: " . sumArray($myArray); ?> Arrays Three types of arrays: Numeric (Indexed) Array: Stores elements with a numeric index (starts from 0). <?php $fruits = array("Apple", "Banana", "Cherry"); echo $fruits[0]; // Output: Apple ?> Associative Array: Stores elements with named keys. <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo $age['Peter']; // Output: 35 ?> Multidimensional Array: An array containing one or more arrays. <?php $cars = array( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), ); echo $cars[0][0]; // Output: Volvo ?> Compare Numeric and Associative Arrays & display with foreach: <?php // Numeric Array $numericArray = ["Red", "Green", "Blue"]; echo "<h4>Numeric Array:</h4><ul>"; foreach ($numericArray as $index => $value) { echo "<li>Index " . $index . ": " . $value . "</li>"; } echo "</ul>"; // Associative Array $associativeArray = ["color1" => "Red", "color2" => "Green", "color3" => "Blue"]; echo "<h4>Associative Array:</h4><ul>"; foreach ($associativeArray as $key => $value) { echo "<li>Key '" . $key . "': " . $value . "</li>"; } echo "</ul>"; ?> Reverse a string: <?php $str = "Hello World"; echo "Original String: " . $str . "<br>"; echo "Reversed String: " . strrev($str); // Output: dlroW olleH ?> Files Four functions to read a file: fread($handle, $length) : Reads up to $length bytes from an open file. <?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fread($myfile, filesize("webdictionary.txt")); fclose($myfile); ?> fgets($handle) : Reads a single line from an open file. <?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fgets($myfile); // Reads the first line fclose($myfile); ?> fgetc($handle) : Reads a single character from an open file. <?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fgetc($myfile); // Reads the first character fclose($myfile); ?> file_get_contents($filename) : Reads the entire file into a string. Simpler for small files. <?php echo file_get_contents("webdictionary.txt"); ?> Forms & Databases (MySQL) Form Handling PHP form to compute addition: <!-- index.html --> <form action="process.php" method="post"> Number 1: <input type="text" name="num1"><br> Number 2: <input type="text" name="num2"><br> <input type="submit" value="Add"> </form> <!-- process.php --> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $num1 = $_POST["num1"]; $num2 = $_POST["num2"]; if (is_numeric($num1) && is_numeric($num2)) { $sum = $num1 + $num2; echo "The sum is: " . $sum; } else { echo "Please enter valid numbers."; } } ?> Form with validation and database save: <!-- register.html --> <form action="register_process.php" method="post"> Name: <input type="text" name="name" required><br> Email: <input type="email" name="email" required><br> <input type="submit" value="Register"> </form> <!-- register_process.php --> <?php $servername = "localhost"; $username = "root"; $password = "your_password"; $dbname = "mydb"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $conn->real_escape_string($_POST['name']); $email = $conn->real_escape_string($_POST['email']); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Invalid email format"; } else { $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } } } $conn->close(); ?> Database Integration (MySQL) Connect to a MySQL database: <?php $servername = "localhost"; $username = "root"; $password = "your_password"; $dbname = "mydb"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; $conn->close(); ?> Create a database using MySQL: This is typically done via MySQL command line or a tool like phpMyAdmin, not usually within a running PHP application. However, PHP can execute SQL commands. <?php $servername = "localhost"; $username = "root"; $password = "your_password"; $conn = new mysqli($servername, $username, $password); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "CREATE DATABASE mynewdb"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; } $conn->close(); ?> Create a table 'user' or 'STUDENT': <?php $servername = "localhost"; $username = "root"; $password = "your_password"; $dbname = "mydb"; // Assuming 'mydb' already exists $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "CREATE TABLE users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; if ($conn->query($sql) === TRUE) { echo "Table Users created successfully"; } else { echo "Error creating table: " . $conn->error; } $conn->close(); ?> Methods: $_GET and $_POST Feature $_GET $_POST Data Visibility Visible in URL (query string) Not visible in URL Data Limit Limited (URL length) No practical limit Security Less secure (data exposed) More secure (data hidden) Bookmarks Can be bookmarked Cannot be bookmarked Use Cases Retrieving data, search queries Submitting sensitive data, file uploads Sessions in PHP Working with Sessions Sessions allow you to store user information across multiple pages. This is crucial for user authentication, shopping carts, etc. PHP sessions work by assigning a unique session ID to each visitor, typically stored in a cookie. This ID is then used to retrieve session data stored on the server. Start a session: session_start(); (must be called before any HTML output). Store data: Use the superglobal array $_SESSION . Access data: Retrieve values from $_SESSION . Session Management with Code <!-- page1.php --> <?php session_start(); // Start the session $_SESSION["username"] = "JohnDoe"; // Store session data $_SESSION["favcolor"] = "green"; echo "Session variables are set."; echo '<br><a href="page2.php">Go to Page 2</a>'; ?> <!-- page2.php --> <?php session_start(); // Resume the session if (isset($_SESSION["username"])) { echo "Welcome, " . $_SESSION["username"] . "!<br>"; echo "Your favorite color is: " . $_SESSION["favcolor"]; } else { echo "No session data found."; } echo '<br><a href="logout.php">Logout</a>'; ?> Functions: session_start() and session_destroy() session_start() : Initializes a session or resumes an existing one. Creates a new session ID if none exists, or uses the one provided by the client (usually via cookie). Must be called at the very beginning of the script, before any output to the browser. session_destroy() : Destroys all data registered to a session. It does not unset the session cookie itself, but the session data on the server is removed. To completely clear the session, you often combine it with session_unset() and setting the session cookie to expire. <!-- logout.php --> <?php session_start(); // Start the session session_unset(); // Unset all session variables session_destroy(); // Destroy the session // Optionally, delete the session cookie if (ini_get("session.use_cookies")) { $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"] ); } echo "You have been logged out."; ?>