PHP

PHP is a server-side scripting language used to build dynamic web pages and web applications. PHP code runs on the server and outputs HTML sent to the browser. In this chapter we will learn PHP basics: embedding PHP in HTML, printing, variables, types, operators, control flow, functions, arrays, superglobals, file handling, error handling, security tips, and a final Collatz example shown as encoded PHP in code blocks.
Introduction to PHP
PHP files usually use the .php extension. PHP code is written inside <?php ?> tags. A web server with PHP installed processes the PHP code and returns the resulting HTML to the client.
Embedding PHP in HTML
PHP can be mixed with HTML. Use short examples to print values and insert dynamic content into pages.
<!DOCTYPE html><br />
<html><br />
<body><br />
<h1>Welcome</h1><br />
<?php echo "Hello, world!"; ?><br />
</body><br />
</html>
Printing and output
Output text with echo or print. Use concatenation with the dot . operator to join strings and variables into output.
<?php br /><br />
echo "Hello PHP"; <br />
print "Hello again"; <br />
$name = "Riya"; echo "Name: ".$name; <br />
Variables and types
Variables start with $. PHP supports strings, integers, floats, booleans, arrays, objects and null. Types are flexible and can be cast when needed.
<?php
$age = 14; <br />
$price = 99.99; <br />
$isActive = true; <br />
$names = array("Riya","Amit","Priya"); <br />
$user = ["name"=>"Riya","age"=>14]; <br />
Operators
Arithmetic, assignment, comparison, logical and string operators are used to perform calculations and make decisions.
<?php
$sum = $a + $b; <br />
$eq = ($a == $b); <br />
$same = ($a === $b); <br />
$concat = $s1 . $s2; <br />
$x = $x ?? 'default'; <br />
Control structures
Use if, else if, else, switch, for, while and foreach to control flow.
<?php
if ($age >= 18) { echo "Adult"; } else { echo "Minor"; }<br />
for ($i=0;$i<5;$i++) { echo $i; }<br />
$arr = [1,2,3]; foreach ($arr as $v) { echo $v; }<br />
Functions
Define reusable code with function. Functions may have parameters, default values, and return values.
<?php
function add($a, $b) { return $a + $b; }<br />
function greet($name = "Guest") { echo "Hello ".$name; }<br />
$sum = add(2,3); greet("Riya"); <br />
Arrays
Arrays store lists and associative key-value pairs. Use array functions to manipulate arrays: array_push, array_pop, array_merge, array_slice, and more.
<?php
$list = [10,20,30]; array_push($list,40); <br />
$assoc = ["name"=>"Riya","age"=>14]; echo $assoc["name"]; <br />
$mapped = array_map(fn($x) => $x*2, $list); <br />
Superglobals
PHP provides superglobal arrays: $_GET, $_POST, $_SERVER, $_SESSION, $_COOKIE. These provide request, server, and session data.
<?php
// Read GET parameter: ?name=Riya<br />
$name = $_GET['name'] ?? 'Guest'; <br />
// Start session and store value<br />
session_start(); $_SESSION['user'] = $name; <br />
File handling
Use fopen, fread, fwrite, and fclose for file I/O. For quick operations, use file_get_contents and file_put_contents.
<?php
file_put_contents('data.txt', 'Hello'); <br />
$s = file_get_contents('data.txt'); echo $s; <br />
$list = scandir('.'); print_r($list); <br />
Error handling
Use try/catch to handle exceptions. During development enable error reporting; in production log errors rather than displaying them to users.
<?php
try { $db = new PDO('sqlite::memory:'); } catch (Exception $e) { error_log($e->getMessage()); } <br />
Security tips
Always validate and sanitize user input. Use prepared statements to avoid SQL injection. Escape output for HTML contexts to prevent XSS. Hash passwords using password_hash and verify with password_verify.
Final example — Collatz sequence
Below is a small Collatz example presented as encoded PHP inside a code box. Save as collatz.php and run on a server or via CLI.
collatz.php
<?php
// Generate Collatz sequence for start values 1..$n
$n = 5; // change as needed
function collatz_for($start) {
$seq = [];
$x = $start;
while ($x != 1) {
$seq[] = $x;
if ($x % 2 == 0) {
$x = $x / 2;
} else {
$x = 3*$x + 1;
}
}
$seq[] = 1;
return $seq;
}
for ($i = 1; $i <= $n; $i++) {
$s = collatz_for($i);
echo "Start = ".$i." : ".implode(" - ",$s)."\n";
}
?>
MCQs
1. Which tag starts PHP code?
(a) <php>
(b) <?php
(c) <script>
(d) <?>
► (b) <?php
2. Which function outputs text in PHP?
(a) write()
(b) echo
(c) printline()
(d) println()
► (b) echo
3. Which symbol begins a variable name?
(a) @
(b) $
(c) %
(d) &
► (b) $
4. Which operator concatenates strings?
(a) +
(b) <<
(c) .
(d) &
► (c) .
5. How do you create an array in PHP?
(a) $a = [1,2,3];
(b) $a = (1,2,3);
(c) $a = {1,2,3};
(d) $a = <1,2,3>;
► (a) $a = [1,2,3];
6. Which superglobal holds GET parameters?
(a) $_POST
(b) $_GET
(c) $_REQUEST
(d) $_SERVER
► (b) $_GET
7. Which function reads the entire file into a string?
(a) fopen()
(b) file_get_contents()
(c) fread()
(d) readfile()
► (b) file_get_contents()
8. Which statement handles exceptions?
(a) try/catch
(b) if/else
(c) switch
(d) error()
► (a) try/catch
9. Which function hashes passwords securely?
(a) md5()
(b) sha1()
(c) password_hash()
(d) crypt()
► (c) password_hash()
10. Which operator checks type and value equality?
(a) ==
(b) =
(c) ===
(d) !=
► (c) ===
11. Which function starts a session?
(a) session()
(b) start_session()
(c) session_start()
(d) begin_session()
► (c) session_start()
12. Which method is used to combine arrays?
(a) array_join()
(b) array_merge()
(c) combine()
(d) merge_array()
► (b) array_merge()
13. Which function converts a PHP value to JSON?
(a) to_json()
(b) serialize()
(c) json_encode()
(d) encode_json()
► (c) json_encode()
14. How do you include a file once?
(a) include()
(b) require()
(c) include_once()
(d) load()
► (c) include_once()
15. Which built-in function gets current timestamp?
(a) now()
(b) current_time()
(c) time()
(d) timestamp()
► (c) time()
16. Which function removes HTML tags from a string?
(a) strip_tags()
(b) remove_html()
(c) htmlspecialchars()
(d) sanitize()
► (a) strip_tags()
17. Which function splits a string into an array by delimiter?
(a) explode()
(b) split()
(c) str_split()
(d) join()
► (a) explode()
18. Which is the correct file name for the final example?(Given in the chapter)
(a) collatz.html
(b) collatz.php
(c) collatz.txt
(d) collatz.js
► (b) collatz.php