Unit 2 of 3 · BCA Sem 3

Unit 2: Arrays, strings and file handling

Web Programming-I notes · PTU syllabus (UGDSE301)

3 min read4 topics8 exam questions
On this page
  1. Unit summary
  2. Arrays
  3. String functions
  4. File handling and uploads
  5. Cookies and sessions
  6. Key terms
  7. Quick revision
  8. Important questions

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
1

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.

ComparisonTypes of arrays
Example
Access

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

FunctionPurpose
count($a)Number of elements
sort / rsortSort values ascending / descending
asort / ksortSort 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_popAdd / 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.

2

Topic 2

String functions

PHP has built-in functions for the common jobs done on text: measuring, changing case, searching, replacing and splitting.

FunctionPurpose
strlen($s)Length
strtoupper / strtolowerChange 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_formatFormat 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.

3

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".

4

Topic 4

Cookies and sessions

GraphCookies vs sessions
CookieSessionStored in the browserStored on the server (ID in a cookie)Small, user can editSafer for sensitive data

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.

ComparisonCookies vs sessions
Cookie
Session

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

  1. Q1.Differentiate between indexed and associative arrays.
  2. Q2.What does explode() do?
  3. Q3.Which enctype is needed for file uploads?
  4. Q4.Differentiate between cookies and sessions.
  5. Q5.How do you destroy a session?

Long-answer questions

  1. Q1.Explain arrays in PHP and their important functions with examples.
  2. Q2.Write a PHP program to upload a file and validate its type and size.
  3. 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.

WhatsApp us