0% found this document useful (0 votes)
4 views8 pages

php assignment

The document provides an overview of PHP programming concepts, including client-server architecture, setting up a web development environment, the difference between interpreters and compilers, and the use of sessions. It includes examples of PHP scripts for user authentication, database connection, and file handling, as well as explanations of functions, object-oriented programming, and error handling. Additionally, it discusses encoding and decoding data in PHP.

Uploaded by

ibrahim
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views8 pages

php assignment

The document provides an overview of PHP programming concepts, including client-server architecture, setting up a web development environment, the difference between interpreters and compilers, and the use of sessions. It includes examples of PHP scripts for user authentication, database connection, and file handling, as well as explanations of functions, object-oriented programming, and error handling. Additionally, it discusses encoding and decoding data in PHP.

Uploaded by

ibrahim
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 8

PHP

Q1. A. Explain with aid of diagram, a client -server architecture


A client-server architecture is a network model where a central server handles requests from multiple client
computers. Clients send requests to the server, and the server processes them and sends back responses.
B. Give a detailed explanation of the procedure for setting -up a development environment for
web development, Highlight the requirements and necessary tools needed.
Requirements:
1. Text editor (Notepad ++, visual studio code, sublime text, eclipse)
2. Web browser (chrome, opera, firefox)
3. Local server (Apache, Ngink)

Setup Procedure:
1. Download notepad++ and install it
2. Get a browser ready (chrome)
3. Download XAMPP from apache.org and install it
4. Open XAMPP control panel
5. Click on start apache and MySQL
6. Navigate to pc  c: drive  xampp folder  htdocs  create your folder

C. Differentiate between an interpreter and a compiler, then state with reason which category
PHP programming language belongs
An interpreter translates high-level programming code into machine code line-by-line at runtime, executing
each command immediately. In contrast, a compiler translates the entire code into machine code before
execution, creating an executable file that can be run independently.
PHP is categorized as an interpreter language because it executes scripts on the server side using a PHP
interpreter, processing the code at runtime rather than compiling it beforehand. This allows for dynamic web
content generation and easier debugging during development.

Q2. Consider to have a HTML form containing some codes for input fields and a submit button. This
code creates a modal login form with two input fields for the username and password. The form will
send data to the “login.php” file using post method when the user clicks the login button.
A. Create the “login.php” script
<?php
If ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$username = $_POST[“username”];
$password = $_POST[“password”];
If (validate_credentials($username, $password)) {
Session_start();
$_SESSION[“username”] = $username;
Header(“Location: dashboard.php”);
} else {
Echo “Invalid username or password.”;
}
}
?>
B. Open a connection with a database use test_db.sql as your database
<?php
$servername = “localhost”;
$username = “your_username”;
$password = “your_password”;
$dbname = “test_db”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
If ($conn->connect_error) {
Die(“Connection failed: “ . $conn->connect_error);
}
?>
C. Describe the procedure of creating the database (test_db.sql)in PhpmyAdmin
* Log in to phpMyAdmin.
* Click the “Databases” tab.
* Click the “Create database” button.
* Enter the database name (e.g., “test_db”).
* Click the “Create” button.

Q3
A. What is PHP Session? Explain its Importance.
A PHP session is a mechanism for storing user data across multiple pages during a user's visit to a website.
Unlike cookies, which store data on the client-side, session data is stored on the server and is associated with
a unique session ID. This allows the server to maintain state and track user activity, making it essential for
functionalities like user authentication, shopping carts, and personalized experiences.
Importance of PHP Sessions
State Management: Sessions help maintain user state in stateless HTTP protocol.
Security: Sensitive information is stored on the server rather than on the client side.
Data Persistence: Users can navigate through different pages without losing their data.
B. Create a PHP Script for the Start of a Session

<?php
// Start the session
session_start();
// Set session variables
$_SESSION["username"] = "JohnDoe";
$_SESSION["role"] = "admin";

echo "Session started. Welcome, " . $_SESSION["username"] . "!";


?>

C. Create a Script to Destroy a PHP Session

<?php
// Start the session
session_start();

// Unset all session variables


$_SESSION = array();

// If it's desired to kill the session, also 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"]
);
}

// Finally, destroy the session


session_destroy();

echo "Session destroyed. You have been logged out.";


?>
Q4. A. What are Functions in PHP? Differentiate Between Built-in Functions and User-defined
Functions.
Functions in PHP are blocks of organized, reusable code designed to perform specific tasks. They help
improve modularity and maintainability of code by allowing the same code to be executed multiple times
without rewriting it. Functions can accept parameters and return values.

Built-in Functions: These are pre-defined functions provided by PHP that perform specific tasks. Examples
include:
- `strlen()` for string length.
- `array_push()` for adding elements to an array.
- `date()` for formatting dates.
User-defined Functions: These are functions created by the programmer to perform specific tasks that are
not covered by built-in functions. They allow customization based on the application’s requirements.

B. i. Create a Function Named "displayMsg()" That Outputs "Hello World!"

<?php
function displayMsg() {
echo "Hello World!";
}
?>
B. ii. Call the Function in (bi) Above
<?php
// Call the function
displayMsg();
?>

Q5A. Explain the concept of Object-Oriented Programming (OOP) and state (5) of its advantages
over procedural programming
OOP is a programming paradigm that models real-world entities as objects, which have properties
(attributes) and behaviors (methods).
Advantages:
1. Modularity: Encapsulates data and behavior within objects.
2. Reusability: Can reuse code by creating classes and objects.
3. Maintainability: Easier to maintain and modify code.
4. Extensibility: Can easily add new features by creating new classes.
5. Flexibility: Can create complex and dynamic applications.
B. Create a PHP script which declare a class named “Fruit” consisting of two properties ($name and
$color) and two methods set_name() and get_name() for setting and getting the $name property
class Fruit {
public $name;
public $color;

public function set_name($name) {


$this->name = $name;
}

Public function get_name() {


Return $this->name;
}
}
Q6.
Consider the following error and answer the questions that follow:
Fatal error: Uncaught Exception: devision by zero in C:\webfolder\test.php:4 Stack trace: #0 C:\
webfolder\test.php(9): divide(5,0) #1 {main} thrown in C:\webfolder\test.php on line 4
A. What is the name of this error?
Division by zero
B. Why is this error generated?
The error occurs because the code attempts to divide a number by zero, which is mathematically undefined.
C. How can you handle the errorm
function divide($a, $b) {
if ($b == 0) {
throw new Exception(“Division by zero”);
}
Return $a / $b;
}

Try {
$result = divide(5, 0);
Echo $result;
} catch (Exception $e) {
Echo “Error: “ . $e->getMessage();
}

Q7.
A. Show how PHP handles file by doing the following:

i. Create a File
<?php
$file = fopen(“example\.txt”, “w”);
?>

ii. Read File Line by Line


<?php
$file = fopen(“example.txt”, “r”);
While (!feof($file)) {
$line = fgets($file);
Echo $line;
}
Fclose($file);
?>

iii. Read File Character by Character


<?php
$file = fopen(“example.txt”, “r”);
While (!feof($file)) {
$char = fgetc($file);
Echo $char;
}
Fclose($file);
?>

iv. Write to a File


<?php
$file = fopen(“example.txt”, “w”);
Fwrite($file, “Hello, World!”);
Fclose($file);
?>

v. Append to a File
<?php
$file = fopen(“example\.txt”, “a”);
Fwrite($file, “Appending this text\.”);
Fclose($file);
?>
vi. Delete a File

To delete a file, you can use the unlink() function.


<?php
Unlink(“example.txt”);
?>
vii. Close a File
<?php
Fclose($file);
?>

B. Encoding and Decoding


Encoding is the process of converting data from one format to another, typically for the purpose of storage
or transmission. For example, converting text into binary data or transforming special characters into a
URL-friendly format.
Decoding is the reverse process, where the encoded data is converted back to its original format, making it
readable and usable again.

You might also like