0% found this document useful (0 votes)
68 views13 pages

Unit 4 PHP Question Bank

Unit 4_PHP Question Bank -#PHP #phpnotes #phpquestionbank #bharathidasanuniversity #bharathidasan #BharathidasanUniversity #syllabusphp #phpsyllabus #phpsyllabusbharathidasanuniversity

Uploaded by

Nandhu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views13 pages

Unit 4 PHP Question Bank

Unit 4_PHP Question Bank -#PHP #phpnotes #phpquestionbank #bharathidasanuniversity #bharathidasan #BharathidasanUniversity #syllabusphp #phpsyllabus #phpsyllabusbharathidasanuniversity

Uploaded by

Nandhu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit IV Programming in PHP ACAS

Unit-IV
1. File Handling
a. Opening File
b. Reading Text from File
c. Reading Text from a File Using fgets
d. Closing file
e. Reading from a file Character by character
f. Reading a whole file at once with file_get_contents
g. Getting file size
h. Coping Files
i. Deleting files
j. Reading files
k. Writing Files
l. Appending files
m. Closing a File
2. Working with Data Bases
a. What is database
b. Essential SQL queries
c. Creating MYSQL Database
d. Creating Table
e. Putting Data into Database
f. Reading the Table
g. Displaying Table
h. Updating Database
i. Deleting Records

3. SESSIONS
a. What is a PHP Session?
b. Start a PHP Session
c. Get PHP Session Variable Values
d. Modify a PHP Session
e. Destroy a PHP Session
4. Cookies
a. Setting cookies
b. Reading Cookies
c. Deleting Cookies
5. FTP
a. Working with FTP
b. Downloading Files with FTP
c. Uploading Files with FTP
d. Deleting Files with FTP

1
Unit IV Programming in PHP ACAS

1.File Handling
a. Opening File:

 Definition: Opening a file is the process of creating a connection between your PHP
script and the file on the filesystem, allowing you to read or write data to it.
 Example Program:
$file = fopen("example.txt", "r");
 Explanation: In this program, the fopen() function is used to open a file named
"example.txt" in read mode ("r"). This returns a file handle that can be used to interact
with the file.

b. Reading Text from File:

 Definition: Reading text from a file involves fetching the contents of the file and
displaying it.
 Example Program:
$file = fopen("example.txt", "r");
echo fread($file, filesize("example.txt"));
fclose($file);

 Explanation: Here, the fread() function reads the contents of the file using the file
handle returned by fopen(). The filesize() function is used to determine the size of the
file.

c. Reading Text from a File Using fgets:

 Definition: The fgets() function reads a line from an open file.


 Example Program:
$file = fopen("example.txt", "r");
while (!feof($file)) {
echo fgets($file) . "<br>";
}
fclose($file);
 Explanation: The fgets() function reads lines from the file in a loop until the end of
the file is reached (feof() function). Each line is then echoed.

d. Closing File:

 Definition: After you're done working with a file, it's important to close it using the
fclose() function to free up system resources.
 Example Program:
$file = fopen("example.txt", "r");
// Perform file operations

2
Unit IV Programming in PHP ACAS

fclose($file);
 Explanation: The fclose() function is used to close the file handle after all necessary
file operations have been performed.

e. Reading from a File Character by Character:

 Definition: You can read characters from a file one by one using the fgetc() function.
 Example Program:
$file = fopen("example.txt", "r");
while (!feof($file)) {
echo fgetc($file);
}
fclose($file);
 Explanation: The fgetc() function reads characters from the file in a loop until the
end of the file is reached.

f. Reading a Whole File at Once with file_get_contents():

 Definition: The file_get_contents() function reads the entire contents of a file into a
string.
 Example Program:
$content = file_get_contents("example.txt");
echo $content;
 Explanation: The file_get_contents() function reads the content of the file
"example.txt" and assigns it to the variable $content, which is then echoed.

g. Getting File Size:


 Definition: The filesize() function returns the size of a file in bytes.
 Example Program:
$size = filesize("example.txt");
echo "File size: $size bytes";
 Explanation: The filesize() function returns the size of the file "example.txt" in bytes,
which is then echoed.

h. Copying Files:
 Definition: The copy() function is used to copy a file from one location to another.
 Example Program:
if (copy("source.txt", "destination.txt")) {
echo "File copied successfully.";
} else {
echo "Copy failed.";
}
 Explanation: The copy() function attempts to copy the content of "source.txt" to
"destination.txt" and echoes a success or failure message accordingly.

i. Deleting Files:

3
Unit IV Programming in PHP ACAS

 Definition: The unlink() function is used to delete a file.


 Example Program:
if (unlink("file_to_delete.txt")) {
echo "File deleted successfully.";
} else {
echo "Deletion failed.";
}
 Explanation: The unlink() function attempts to delete the file "file_to_delete.txt" and
echoes a success or failure message accordingly.

j. Reading Files:
 Definition: Reading files is the process of retrieving data from a file and displaying it.
 Example Program: (Refer to the examples under headings "b. Reading Text from
File" and "c. Reading Text from a File Using fgets" above)
k. Writing Files:
 Definition: Writing files involves creating or modifying the content of a file.
 Example Program:
$file = fopen("output.txt", "w");
fwrite($file, "Hello, World!");
fclose($file);
 Explanation: In this program, the fopen() function is used to open "output.txt" in
write mode ("w"). The fwrite() function writes the string "Hello, World!" to the file.

l. Appending Files:
 Definition: Appending involves adding content to the end of an existing file.
 Example Program:
$file = fopen("log.txt", "a");
fwrite($file, "New log entry\n");
fclose($file);
 Explanation: In this program, the fopen() function opens the file "log.txt" in append
mode ("a"). The fwrite() function adds the new log entry to the end of the file without
removing the existing content.

m. Closing a File:
 Definition: Closing a file involves releasing the resources associated with the file
handle, allowing other processes to access the file.
 Example Program:
$file = fopen("example.txt", "r");
// Perform file operations
fclose($file);
Explanation: In this program, the fclose() function is used to close the file handle after the
necessary file operations have been performed.

2. Working with Data Bases


a. What is Database:

4
Unit IV Programming in PHP ACAS

 Definition: A database is an organized collection of data, typically stored and


managed using a database management system (DBMS). It allows you to store,
retrieve, update, and manage data efficiently.

b. Essential SQL Queries:


 Definition: SQL (Structured Query Language) is used to interact with databases.
Essential SQL queries include SELECT, INSERT, UPDATE, and DELETE.
 Example Program:
-- SELECT Query
SELECT column1, column2 FROM table_name WHERE condition;

-- INSERT Query
INSERT INTO table_name (column1, column2) VALUES (value1, value2);

-- UPDATE Query
UPDATE table_name SET column1 = value1 WHERE condition;

-- DELETE Query
DELETE FROM table_name WHERE condition;

 Explanation: SQL queries are used to perform various operations on databases.


SELECT retrieves data, INSERT adds new records, UPDATE modifies records, and
DELETE removes records.

c. Creating MySQL Database:


 Definition: Creating a database involves setting up a space to store data using a
database management system like MySQL.
Here's a step-by-step explanation of how to create a MySQL database:

Access MySQL Server: Before you create a database, make sure you have access to a
MySQL server. You might have MySQL installed locally or be using a remote MySQL
server.

Use a Database Client: You can use various tools like phpMyAdmin, MySQL Workbench,
or command-line tools to interact with MySQL. Let's use the command-line approach in this
example.

Log into MySQL: Open a terminal or command prompt and log into MySQL using a user
account that has the necessary privileges to create databases. Replace username with your
MySQL username and password with your password:

mysql -u username -p

You'll be prompted to enter your password.

5
Unit IV Programming in PHP ACAS

Create a Database: Once logged in, you can create a new database using the CREATE
DATABASE statement. Replace yourdb with the desired name of your database:

CREATE DATABASE yourdb;


Press Enter to execute the command.

Confirm Creation: You should see a message indicating that the database has been created:
Query OK, 1 row affected

Select the Database: After creating the database, select it to start working within that
database:
USE yourdb;

You'll see a message indicating that the database has been changed:
Database changed

d. Creating Table:
 Definition: A table is a structured collection of data stored in rows and columns
within a database. It defines the structure of the data to be stored.
 Example Program:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
);
 Explanation: This SQL query creates a table named "users" with columns for "id",
"username", and "email". The "id" column is set as the primary key with auto-
incrementing values.

e. Putting Data into Database:


 Definition: Inserting data involves adding new records into a table.
 Example Program:
INSERT INTO users (username, email) VALUES ('john_doe', '[email protected]');
 Explanation: This SQL query inserts a new record with the specified values into the
"users" table.

f. Reading the Table:


 Definition: Reading data involves retrieving records from a table.
 Example Program:
SELECT id, username, email FROM users;
Explanation: This SQL query selects the "id", "username", and "email" columns
from the "users" table, retrieving all records.

g. Displaying Table:
 Definition: Displaying data involves presenting the retrieved records in a human-
readable format.

6
Unit IV Programming in PHP ACAS

 Example Program: N/A (This topic is more about displaying data using PHP and
HTML.)
h. Updating Database:
 Definition: Updating data involves modifying existing records in a table.
 Example Program
UPDATE users SET email = '[email protected]' WHERE username =
'john_doe';
 Explanation: This SQL query updates the "email" field of a record in the "users"
table where the "username" is "john_doe".

i. Deleting Records:
 Definition: Deleting data involves removing records from a table.
 Example Program:
DELETE FROM users WHERE username = 'john_doe';
Explanation: This SQL query deletes records from the "users" table where the
"username" is "john_doe".

3. SESSIONS
a. What is a PHP Session?:
 Definition: A PHP session is a way to preserve data across subsequent HTTP
requests. It allows you to store and retrieve data that can be used across different
pages or requests while a user navigates through your website.
b. Start a PHP Session:
 Definition: Starting a PHP session involves creating a unique session identifier and
enabling the server to track session-related data for a user.
 Example Program:
session_start();
 Explanation: The session_start() function is used to start a new or resume an existing
session. It must be called at the beginning of every script that will utilize session
variables.
c. Get PHP Session Variable Values:
 Definition: Once a session is started, you can access session variables that hold data
specific to the user's session.
 Example Program:
session_start();
$_SESSION['username'] = 'john_doe';

// Later in another script or request


session_start();

7
Unit IV Programming in PHP ACAS

echo $_SESSION['username']; // Output: john_doe


 Explanation: In this program, the $_SESSION superglobal is used to store and
retrieve session data. The value of $_SESSION['username'] persists across different
requests.
d. Modify a PHP Session:
 Definition: You can modify session variables by directly assigning new values to
them.
 Example Program:
session_start();
$_SESSION['count'] = isset($_SESSION['count']) ? $_SESSION['count'] + 1 : 1;
echo "Page views: " . $_SESSION['count'];
 Explanation: This program increments the value of the session variable count each
time the page is visited, displaying the number of page views.
e. Destroy a PHP Session:
 Definition: Destroying a session terminates the user's session, removing all session
data.
 Example Program:
session_start();
session_destroy();
Explanation: The session_destroy() function ends the current session and removes
all session data associated with the user. After calling this function, any session
variables are no longer accessible.
Program: Using PHP Sessions
<?php
// Start a new session or resume an existing session
session_start();

// Set session variables


$_SESSION['username'] = 'john_doe';
$_SESSION['user_id'] = 123;

// Display session variables


echo "Welcome, " . $_SESSION['username'];

8
Unit IV Programming in PHP ACAS

// Modify session data


$_SESSION['user_id'] = 456;

// Destroy the session


session_destroy();
?>
This program demonstrates the basic usage of PHP sessions, including starting a
session, setting session variables, displaying their values, modifying data, and
destroying the session.

4. Cookies
a. Setting Cookies:
 Definition: Cookies are small pieces of data that a web server can store on a user's
computer. They are often used to remember user preferences or track user activity.
 Example Program:
$cookie_name = "user";
$cookie_value = "john_doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
 Explanation: In this program, the setcookie() function is used to set a cookie named
"user" with the value "john_doe". The third argument specifies the expiration time,
which is set to 30 days from the current time. The fourth argument "/" indicates that
the cookie is available across the entire website.

b. Reading Cookies:
 Definition: Reading cookies involves retrieving the data stored in a cookie that was
previously set.
 Example Program:
if (isset($_COOKIE['user'])) {
echo "User: " . $_COOKIE['user'];
} else {
echo "User cookie not set.";
}

9
Unit IV Programming in PHP ACAS

 Explanation: This program checks if the "user" cookie is set using the isset()
function. If the cookie is set, it displays the user's name; otherwise, it informs that the
user cookie is not set.

c. Deleting Cookies:
 Definition: Deleting cookies involves removing a previously set cookie from the
user's computer.
 Example Program:
$cookie_name = "user";
setcookie($cookie_name, "", time() - 3600, "/");
 Explanation: This program uses the setcookie() function with an expiration time in
the past to effectively delete the "user" cookie. The empty value and negative
expiration time invalidate the cookie.
Note: Cookies are stored in the user's browser and are transmitted with each HTTP
request to the server. While cookies are convenient for storing small amounts of data,
they have limitations, such as data size and security concerns. Sensitive information
should not be stored in cookies without encryption.

Program: Using PHP Cookies

<?php
// Setting a cookie
$cookie_name = "user";
$cookie_value = "john_doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 30 days

// Reading a cookie
if (isset($_COOKIE[$cookie_name])) {
echo "User: " . $_COOKIE[$cookie_name];
} else {
echo "User cookie not set.";
}

// Deleting a cookie
if (isset($_COOKIE[$cookie_name])) {

10
Unit IV Programming in PHP ACAS

setcookie($cookie_name, "", time() - 3600, "/");


echo "<br>Cookie deleted.";
}
?>
Explanation:
1. The program starts by setting a cookie named "user" with the value "john_doe". It will
be valid for 30 days using the setcookie() function.
2. Next, it checks if the "user" cookie is set using the isset() function. If the cookie is set,
it displays the user's name; otherwise, it informs that the user cookie is not set.
3. Finally, the program checks if the "user" cookie is set again. If it is set, it uses the
setcookie() function with a negative expiration time to delete the cookie. The cookie's
value is emptied, and its expiration time is set to the past.
When you run this program, you'll see the output displaying the user's name if the
cookie is set, and then the cookie will be deleted, leading to the "Cookie deleted."
message.

5.FTP- File Transfer Protocol


g. Working with FTP
h. Downloading Files with FTP
i. Uploading Files with FTP
j. Deleting Files with FTP

a. Working with FTP:


Definition: FTP (File Transfer Protocol) is a standard network protocol used to
transfer files between a client and a server over a computer network.

b. Downloading Files with FTP:


Definition: Downloading files with FTP involves retrieving files from a remote
server to the local machine.
Example Program:
$server = "ftp.example.com";
$username = "ftp_username";
$password = "ftp_password";
$file = "remote_file.txt";
$local_file = "local_file.txt";

11
Unit IV Programming in PHP ACAS

$ftp = ftp_connect($server);
ftp_login($ftp, $username, $password);
ftp_get($ftp, $local_file, $file, FTP_BINARY);
ftp_close($ftp);
 Explanation: This program connects to an FTP server, logs in with the provided
credentials, and then uses ftp_get() to download the remote file "remote_file.txt" and
save it as "local_file.txt" on the local machine.

c. Uploading Files with FTP:


 Definition: Uploading files with FTP involves sending files from the local machine to
a remote server.
 Example Program:
$server = "ftp.example.com";
$username = "ftp_username";
$password = "ftp_password";
$local_file = "local_file.txt";
$remote_file = "remote_file.txt";

$ftp = ftp_connect($server);
ftp_login($ftp, $username, $password);
ftp_put($ftp, $remote_file, $local_file, FTP_BINARY);
ftp_close($ftp);
 Explanation: This program connects to an FTP server, logs in with the provided
credentials, and then uses ftp_put() to upload the local file "local_file.txt" to the
remote server as "remote_file.txt".

d. Deleting Files with FTP:


 Definition: Deleting files with FTP involves removing files from a remote server.
 Example Program
$server = "ftp.example.com";
$username = "ftp_username";

12
Unit IV Programming in PHP ACAS

$password = "ftp_password";
$file = "remote_file.txt";

$ftp = ftp_connect($server);
ftp_login($ftp, $username, $password);
ftp_delete($ftp, $file);
ftp_close($ftp);
 Explanation: This program connects to an FTP server, logs in with the provided
credentials, and then uses ftp_delete() to remove the remote file "remote_file.txt"
from the server.
Note: FTP functions in PHP require the FTP extension to be enabled in your PHP
configuration. Additionally, handling FTP operations often involves dealing with
authentication, connection errors, and data transfer modes

13

You might also like