Unit 5
Unit 5
PHP
Introduction to PHP
• PHP (Hypertext Preprocessor) ia a open-source server-
side scripting language designed specifically for web
development.
• It is embedded within HTML
• It is used to manage dynamic content, databases,
session tracking, and even build entire e-commerce
websites.
• Rasmus Lerdorf in 1994, maintained by The PHP Group.
• PHP files typically have a .php extension and can
contain text, HTML, CSS, JavaScript, and PHP code.
Role of PHP
$x = 5;
$y = 4;
echo $x + $y;
• PHP echo and print Statements are used to output data to the screen. Echo
does not return any value print returns 1, so it can be used in the expressions.
Data Types
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
PHP is a loosely typed language.
Getting data type:
$x = 5;
var_dump($x);
Strings
familyName("Hege", "1975");
familyName("Stale", "1978");
Arrays
• Php runs on the server side it receives the data(request) from client
and return it in simple html format.
• HTML forms send data to PHP using:
• GET – Appends data to the URL.
• POST – Sends data in the request body.
• GET vs POST Methods
• Feature GET
POST
• Visibility Appends data to URL Sends data in
request body
• Use Case Bookmarkable/search forms Login, registration,
payments
• Data Limit Limited (~2000 characters) No size limit
• Security Less secure More secure
S u p e rg lo b a ls in P H P
• PHP allows you to create, read, write, and close files using
built-in functions.
• Common File Functions
• Function Purpose
• fopen() Opens a file
• fread() Reads a file
• fwrite() Writes to a file
• fclose() Closes a file
• file_get_contents() Reads file content as a string
• file_put_contents() Writes data to a file
• Writing to a File
$file = fopen("data.txt", "w"); // 'w' = write (overwrite)
fwrite($file, "Hello, world!\n");
fclose($file);
• If data.txt doesn't exist, it will be created.
• "w" mode overwrites content if the file exists.
• Appending to a File
$file = fopen("data.txt", "a"); // 'a' = append
fwrite($file, "Another line\n");
fclose($file);
• Reading from a File
$file = fopen("data.txt", "r"); // 'r' = read
$content = fread($file, filesize("data.txt"));
fclose($file);
• echo $content;
• Quick Read & Write (Simple Way)
• // Read
• $content = file_get_contents("data.txt");
• // Write (overwrites)
• file_put_contents("data.txt", "New content");
• // Append
• file_put_contents("data.txt", "Extra line", FILE_APPEND);