Unit 2: Arrays, strings and file handling
Web Programming-I notes · PTU syllabus (UGDSE301)
On this page
Unit summary
Real applications deal with lists of data, text and files, and need to remember users between pages. This unit covers PHP arrays and array functions, string manipulation, file handling and uploads, and maintaining state with cookies and sessions.
After this unit you can
- Create indexed, associative and multidimensional arrays and use array functions
- Manipulate and format strings
- Read, write, append and delete files and handle file uploads
- Use cookies and sessions to maintain state
PTU syllabus topics
- Indexed
- associative and multidimensional arrays
- array functions (sorting, merging, searching)
- string manipulation and formatting functions
- file handling (open, read, write, append, delete)
- file uploads
- cookies and sessions
Topic 1
Arrays
An array stores many values under one name. PHP has three kinds: indexed arrays use numbers as keys, associative arrays use names as keys, and multidimensional arrays hold arrays inside arrays.
Indexed
$c = ["BCA", "BBA", "MBA"];
$c[0]
Associative
$s = ["name" => "Ana", "roll" => 12];
$s["name"]
Multidimensional
$m = [[1,2],[3,4]];
$m[1][0] gives 3
| Function | Purpose |
|---|---|
| count($a) | Number of elements |
| sort / rsort | Sort values ascending / descending |
| asort / ksort | Sort associative arrays by value / key |
| array_merge($a, $b) | Join arrays |
| in_array($x, $a) | Check if a value exists |
| array_search($x, $a) | Return the key of a value |
| array_push / array_pop | Add / remove at the end |
Example
Looping through an associative array: $marks = ["Ana" => 82, "Raj" => 74]; then foreach ($marks as $name => $m) { echo "$name: $m <br>"; } prints Ana: 82 and Raj: 74. count($marks) returns 2.
Topic 2
String functions
PHP has built-in functions for the common jobs done on text: measuring, changing case, searching, replacing and splitting.
| Function | Purpose |
|---|---|
| strlen($s) | Length |
| strtoupper / strtolower | Change case |
| str_replace($a, $b, $s) | Replace text |
| strpos($s, $x) | Position of a substring |
| substr($s, $start, $len) | Extract part of a string |
| trim($s) | Remove surrounding spaces |
| explode(",", $s) / implode(",", $a) | Split into an array / join an array |
| sprintf / number_format | Format strings and numbers |
Example
Cleaning form input: for $name = " ravi kumar ";, trim($name) gives "ravi kumar", ucwords(trim($name)) gives "Ravi Kumar", strlen(trim($name)) gives 10 and explode(" ", trim($name)) gives the array ["ravi", "kumar"].
Exam tip
explode() splits a string into an array; implode() joins an array into a string.
Topic 3
File handling and uploads
php<?php
$f = fopen("notes.txt", "a"); // r, w, a, r+
fwrite($f, "New line\n");
fclose($f);
echo file_get_contents("notes.txt"); // read whole file
if (file_exists("old.txt")) unlink("old.txt"); // delete
?>File upload: the form needs method="post" and enctype="multipart/form-data"; PHP reads the file from $_FILES["file"] and saves it with move_uploaded_file(). Check the file type and size before saving.
Example
File modes: "r" reads an existing file. "w" writes and erases what was there. "a" adds to the end. An uploaded file arrives in $_FILES["photo"]["tmp_name"] and is saved with move_uploaded_file(); the form must have enctype="multipart/form-data".
Topic 4
Cookies and sessions
Use sessions for login state and cookies for preferences such as theme or language
HTTP is stateless — each request is independent — so websites use cookies and sessions to remember users.
Stored on
The user's browser
The server
Security
Less secure (user can see and edit)
More secure
Size
Small (about 4 KB)
Larger
Lifetime
Until its expiry time
Until logout or timeout
PHP
setcookie(), $_COOKIE
session_start(), $_SESSION
php<?php
session_start();
$_SESSION["user"] = "ana"; // store
echo $_SESSION["user"]; // read on any page after session_start()
session_destroy(); // logout
?>Example
A login session: after checking the password, session_start(); $_SESSION["user"] = $name; stores the name on the server. Other pages call session_start() and read it. session_destroy() logs the user out. A cookie, set with setcookie("theme", "dark", time() + 86400), is stored in the browser for one day.
Exam tip
Sessions are stored on the server and are safer. Cookies are stored in the browser and limited to about 4 KB.
Key terms
- Associative array
- An array with named keys
- explode
- Splits a string into an array
- enctype
- Form attribute needed for file uploads
- Cookie
- Small data stored in the browser
- Session
- User data stored on the server across pages
Quick revision
- Indexed, associative and multidimensional arrays.
- explode splits, implode joins.
- fopen modes: r, w, a, r+; uploads need multipart/form-data.
- Sessions are server-side and more secure than cookies.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.Differentiate between indexed and associative arrays.
- Q2.What does explode() do?
- Q3.Which enctype is needed for file uploads?
- Q4.Differentiate between cookies and sessions.
- Q5.How do you destroy a session?
Long-answer questions
- Q1.Explain arrays in PHP and their important functions with examples.
- Q2.Write a PHP program to upload a file and validate its type and size.
- Q3.Explain cookies and sessions with programs, and compare them.
Stuck on this unit?
Message SBS on WhatsApp for help with Web Programming-I, or to ask about studying BCA at Synetic.
