0% found this document useful (0 votes)
40 views16 pages

php

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

Set – 02(Basic PHP)

1. Define PHP. What are the advantages of PHP over other programming languages?
Answer: PHP, which stands for Hypertext Preprocessor, is a widely-used server-side scripting
language designed for web development. It is embedded within HTML code and is used to
manage dynamic content, handle form data, and interact with databases. PHP is an open-source
language, and it is particularly well-suited for web development.
Advantages of PHP over other programming languages include:
• PHP is a server-side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
• It is integrated with a number of popular databases, including MySQL, Oracle, Sybase,
Informix, and Microsoft SQL Server.
• PHP is pleasingly fast in its execution, especially when compiled as an Apache module
on the Unix side.
• PHP is scalable, allowing developers to build both small, simple websites and large,
complex web applications. Its versatility makes it suitable for a wide range of projects.
• PHP is a very efficient language that can handle a large amount of traffic. This makes
it a good choice for high-traffic websites.
• PHP has a number of popular frameworks, such as Laravel and Symfony, that can make
development faster and easier.
• PHP has a very large and active community of developers. This means that there are a
wealth of resources available to help you learn the language and solve problems.
• PHP is relatively easy to learn, even for beginners. This is because it has a simple syntax
and a large number of pre-written libraries and functions that can be used to common
tasks.

2. What are the features/ characteristics of PHP? Briefly explain any three of them.
Answer: There are many features given by PHP. All Features discussed below one by one.
Familiarity
Simplicity
Efficiency
Security
Flexibility
Open source
Object Oriented

Familiarity: If you are in programming background then you can easily understand the PHP
syntax. And you can write PHP script because of most of PHP syntax inherited from other
languages like C or Pascal.
Simplicity: PHP provides a lot of pre-define functions to secure your data. It is also
compatible with many third-party applications, and PHP can easily integrate with other.
In PHP script there is no need to include libraries like c, special compilation directives like
Java, PHP engine starts execution from (<?) escape sequence and end with a closing escape
sequence (?>). In PHP script,
there is no need to write main function. And also you can work with PHP without creating a
class.
Efficiency: PHP 4.0 introduced resource allocation mechanisms and more pronounced
support for object-oriented programming, in addition to session management features.
Eliminating unnecessary memory allocation.
Security: Several trusted data encryption options are supported in PHP’s predefined
function set. You can use a lot of third-party applications to secure our data, allowing for
securing our application.
Flexibility: You can say that PHP is a very flexible language because of PHP is an embedded
language you can embed PHP scripts with HTML, JAVA SCRIPT, WML, XML, and many
others. You can run your PHP script any device like mobile Phone, tabs, laptops, PC.
Open Source/ Free: PHP is an open-source programming language so you can download
freely there is no need to buy a licence or anything.
Object Oriented: PHP has added some object-oriented programming features, and Object
Oriented programming became possible with PHP 4.0.

3. Write down the application of PHP.


Answer:

PHP (Hypertext Preprocessor) is a server-side scripting language widely used for web
development. Some key applications of PHP include:

1. Web Development: PHP is primarily used to create dynamic and interactive web pages.
It can be embedded within HTML code and executed on the server, generating dynamic
content before it is sent to the user's browser.
2. Content Management Systems (CMS): Many popular CMS platforms, such as
WordPress, Joomla, and Drupal, are built using PHP. It enables the creation and
management of dynamic website content with ease.
3. E-Commerce Solutions: PHP is commonly used for developing e-commerce websites
and online shopping carts. It facilitates the integration of payment gateways, order
processing, and inventory management.
4. Server-Side Scripting: PHP is a powerful server-side scripting language, allowing
developers to write scripts that run on the server, interacting with databases, handling
forms, and performing various server-side tasks.
5. Data Processing: PHP is often utilized for data processing tasks, such as collecting form
data, processing user input, and interacting with databases to store or retrieve
information.
6. Web Services: PHP can be used to develop and consume web services, making it
possible for different applications to communicate with each other over the web.
7. Command-Line Scripting: PHP can be executed from the command line, enabling
developers to perform various tasks and automate processes outside of a web server
context.
8. Social Media Integration: PHP is commonly employed to integrate websites with social
media platforms, allowing users to log in with their social media credentials and share
content on social networks.
9. XML and JSON Parsing: PHP supports parsing and generating XML and JSON,
making it suitable for handling data interchange between web applications and external
services.
10. User Authentication and Authorization: PHP provides mechanisms for user
authentication and authorization, ensuring secure access to web applications by
implementing user login systems and controlling user permissions.

Overall, PHP's versatility and ease of use make it a popular choice for a wide range of web
development projects.

4. Why is PHP referred to as a loosely typed language with examples?


Answer: PHP is often referred to as a loosely typed or dynamically typed language because it
allows variables to change their data types during runtime. In a loosely typed language, the
data type of a variable is not explicitly defined when the variable is declared, and it can be
dynamically changed as the program runs.
Here are some examples illustrating the loose typing nature of PHP:
• Variable Assignment:
• $x = 10; // $x is an integer
• $x = "Hello"; // $x is now a string
• $x = 3.14; // $x is now a float
In this example, the variable ‘$x’ starts as an integer, becomes a string, and then becomes
a float. PHP allows such dynamic changes in data types.
• Type Juggling:
• $a = "5";
• $b = 10;

• $result = $a + $b; // PHP automatically converts $a to an integer and performs
the addition
• echo $result; // Output: 15
In this case, PHP performs type juggling by automatically converting the string "5" to an
integer during the addition operation.

• Comparison of Different Types:


$num = 5;
$str = "5";
if ($num == $str) {
echo "Equal"; // This will be true, as PHP performs type coercion for equality
comparison
}
PHP uses type coercion in loose comparisons, so in this example, the numeric value of $str
is compared with $num, and the condition evaluates to true.
• Function Parameters:
function add($a, $b) {
return $a + $b;
}
$result = add(5, "10"); // PHP performs type coercion, converting the string "10" to an
integer
echo $result; // Output: 15
PHP will automatically convert the string "10" to an integer when the add function is called,
allowing for flexibility in function parameter types.

5. What is super global variable in PHP? Mention some name of super global variables.
Answer: In PHP, super global variables are predefined variables that are always accessible,
regardless of the scope or location within a script. These variables are called "super global"
because they are automatically available in every part of the script, and they provide
information about the server, the client, and the environment.
Here are some commonly used super global variables in PHP:
• $_GET: Contains variables sent to the script via URL parameters (HTTP GET method).
• $_POST: Holds variables sent to the script via HTTP POST method (commonly used with
HTML forms).
• $_REQUEST: A combined array containing data from $_GET, $_POST, and $_COOKIE.
It is not recommended to use $_REQUEST due to security considerations.
• $_SESSION: Stores session variables that can be used across multiple pages of a website
for a specific user.
• $_COOKIE: Contains variables sent to the script via HTTP cookies.
• $_FILES: An associative array containing information about file uploads via HTTP POST.
• $_SERVER: Contains information about the server and the execution environment. It
includes details like server name, request method, script filename, and more.
• $_ENV: Holds variables from the environment, which are often set by the server
administrator.
• $_GLOBALS: A global variable holding references to all variables in the global scope. It's
not as commonly used as other super global.

6. Write down a PHP program to show information about headers, paths, and script
locations of a webpage using a super global variable.
Answer: Certainly! In PHP, information about headers, paths, and script locations can be
accessed using various superglobal variables. Below is a simple PHP program that demonstrates
how to retrieve and display information about headers, paths, and script locations using
superglobal variables:
<?php
// Display information about headers
echo "<h2>HTTP Headers:</h2>";
echo "<pre>";
print_r($_SERVER);

// Display information about the server path


echo "<h2>Server Path:</h2>";
echo "<p>Document Root: {$_SERVER['DOCUMENT_ROOT']}</p>";
echo "<p>Server Software: {$_SERVER['SERVER_SOFTWARE']}</p>";
// Display information about the script location
echo "<h2>Script Location:</h2>";
echo "<p>Script Name: {$_SERVER['SCRIPT_NAME']}</p>";
echo "<p>Current Page: {$_SERVER['PHP_SELF']}</p>";
echo "</pre>";
?>

In this program:

• The $_SERVER superglobal variable is used to access information about the server,
including headers.
• Information about the server path is displayed, including the document root and server
software.
• Information about the script location is displayed, including the script name, script
filename, and current page.

Please note that the output of $_SERVER may contain a large amount of information, so it's often
a good idea to use it for debugging purposes or to extract specific pieces of information needed
for your application. Additionally, be cautious about displaying such information on a production
website for security reasons.

7. Write down a PHP program with a super global variable which is used to collect data
after submitting an HTML form.
Answer:
$_POST: Holds variables sent to the script via HTTP POST method is a PHP super global
variable which is used to collect data after submitting an HTML form.
Example:
<html>
<body>
<form method="post" action="" >
Name: <input type="text" name="fname">
<input type="Submit" name="submit" value="Submit">
</form>
<?php
if (isset($_POST[‘submit’]) {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";}
else { echo$name; } } ?>
</body>
</html>
8. Let consider a text “Information and Communication Engineering” What are the output
of the following string functions (i) strrev() (ii) str_word_count() (iii) strpos() for
“Communication” (iv) str_replace() replace “Engineering” by “Technology”.
Answer: Let's analyze the given text "Information and Communication Engineering" using the
mentioned string functions:
• strrev(): This function reverses a string.
$text = "Information and Communication Engineering";
$reversed_text = strrev($text);
echo $reversed_text;

Output:
.gninireehtnE noitacinummoC dna noitanrofmI

• str_word_count(): This function counts the number of words in a string.


$text = "Information and Communication Engineering";
$word_count = str_word_count($text);
echo $word_count;

Output:
4

• strpos(): This function finds the position of the first occurrence of a substring in a
string.
$text = "Information and Communication Engineering";
$position = strpos($text, "Communication");
echo $position;

Output:
16

• str_replace(): This function replaces occurrences of a specified substring with another


string.
$text = "Information and Communication Engineering";
$modified_text = str_replace("Engineering", "Technology", $text);
echo $modified_text;

Output:
Information and Communication Technology

In summary:
The reversed string is "gninireehtnE noitacinummoC dna noitanrofmI."
The number of words in the string is 4.
The position of the substring "Communication" is 16.
The modified string with "Engineering" replaced by "Technology" is "Information and
Communication Technology."

9. Write PHP program to get the hour of server and show the following message: (i) if the
hour less than 10 then show "Have a good morning!" (ii) else if the hour less than 20 then
show " Have a good day!" otherwise show “Have a good night!”.
Answer: Certainly! Below is a simple PHP program that gets the current hour of the server
and displays a message based on the specified conditions:
<?php
// Get the current hour
$currentHour = date("G");

// Display a message based on the hour


if ($currentHour < 10) {
$message = "Have a good morning!";
} elseif ($currentHour < 20) {
$message = "Have a good day!";
} else {
$message = "Have a good night!";
}

// Output the message


echo $message;
?>
This program uses the date("G") function to get the current hour in 24-hour format. Then, it
uses a series of if and elseif statements to determine the appropriate message based on the time
of day. Finally, the chosen message is echoed to the screen.
Set-04 (Advanced PHP and MYSQL)

1. What do you mean by cookies? Explain the process to set cookies using the setcookie()
function in PHP.
Answer: In web development, a "cookie" refers to a small piece of data stored on the client's
computer by the web browser while browsing a website. Cookies are commonly used to store
information about the user's session, preferences, and other data that can be retrieved later to
enhance the browsing experience or track user behavior.

In PHP, the setcookie() function is used to set a cookie. Here's an overview of how you can
use it:
setcookie(name, value, expire, path, domain);
• name: The name of the cookie.
• value: The value to be stored in the cookie.
• expire: The expiration time of the cookie. It is a Unix timestamp representing the
number of seconds since January 1, 1970, 00:00:00 UTC. If you want the cookie to
expire at the end of the session, you can set it to 0. If you want the cookie to be stored
for a specific number of seconds, you can set it accordingly.
• path (optional): The path on the server in which the cookie will be available. If set to
"/", the cookie will be available across the entire domain. If set to "/example/", the
cookie will only be available in the "/example/" directory and its subdirectories.
• domain (optional): The domain for which the cookie is accessible. By default, the
cookie is available for the domain of the web page that set the cookie.
Here's an example:

<?php
// Set a cookie named "user" with the value "John Doe" that expires in one hour
setcookie("user", "John Doe", time() + 3600, "/");

// Retrieve the value of the cookie (if it exists)


if (isset($_COOKIE["user"])) {
echo "Welcome " . $_COOKIE["user"] . "!";
} else {
echo "Cookie not set!";
}
?>
In this example, a cookie named "user" is set with the value "John Doe," and it will expire in one
hour. Later, the script checks if the cookie is set and echoes a welcome message if it is, or a
message indicating that the cookie is not set if it's not.
2. Illustrate the HTTP request and response using cookies.
Answer:

The image shows the following:

• The client is sending a request to the server for a web page. The request includes the
Cookie header, which contains the cookies that the client has for the server domain.
• The server is checking to see if the client has any cookies for the server domain. The
server is using the isset() function to check if the $_COOKIE variable contains a value
for the name cookie.
• The server is also checking to see if the name parameter was passed in the request. The
server is using the isset() function to check if the $_GET variable contains a value for
the name parameter.
• If the client does not have any cookies for the server domain, or if the name parameter
was not passed in the request, the server will respond with an HTML form. The form will
ask the user to enter their name.
• If the client does have cookies for the server domain, and the name parameter was passed
in the request, the server will set a cookie on the client's computer. The cookie will
contain the name that the user entered in the form. The server will also respond with a
welcome message that is personalized to the user.

Cookies can be a very useful tool for web developers. However, it is important to use cookies
responsibly and to protect the privacy of your users.
3. Write down a PHP code for the following cases (i) Case 1: the cookies already set (ii)
Case 2 & 3: first and second visits.
Answer: Certainly! Let's create a simple PHP code that covers three cases: when the cookie is
already set, during the first visit, and during the second visit.
<?php
// Case 1: The cookies already set
if (isset($_COOKIE["user"])) {
$username = $_COOKIE["user"];
echo "Welcome back, $username!";
}
// Case 2: Upon submission of form
else if (isset($_GET["name"])) {
$username = $_GET["user "];
setcookie("user", $username, time() + 3600, "/");

echo "Welcome $ username! This is your second visit.";


}
// Case 3: First visit - Show form
else {
?>
<form action="" method="get">
Enter your name here: <input type="text" name="name" />
<br /><input type="submit" />
</form>
<?php
}
?>
Explanation:

1. Case 1 (The cookies already set):


o If the "user" cookie is already set, the script retrieves the username from the
cookie.
o It then echoes a welcome message addressing the user by their username,
indicating a return visit.
2. Case 2 (Upon submission of form):
o If the "user" cookie is not set (indicating the first visit), the script checks if the
"name" parameter is set in the GET request (form submission).
o If the "name" parameter is set, it retrieves the username from the "user" field in
the form.
o It sets a new cookie named "user" with the provided username, and it is set to
expire in one hour (time() + 3600).
o The script then echoes a welcome message indicating the second visit.
3. Case 3 (First visit - Show form):
o If neither the "user" cookie is set nor the form is submitted (no "name"
parameter), it displays an HTML form.
o The form has an input field for the user to enter their name, and it uses the GET
method to submit the form data to the same script.

4. Define sessions. What are the main disadvantages of cookies?


Answer: A session in web development is a way to store information about a user across
multiple pages or visits. Unlike cookies, which are stored on the client-side, session data is
typically stored on the server. A session is initiated when a user visits a website for the first
time, and a unique session identifier is assigned to the user. This identifier is then used to
associate the user with stored data on the server, such as user preferences, authentication status,
or other relevant information.
In PHP, sessions are often managed using the $_SESSION superglobal. Here's a simplified
Disadvantages of Cookies: While cookies are widely used for storing small amounts of data
on the client side, they have some disadvantages:
• Cookies have size limitations (usually 4 KB). If you need to store a significant amount
of data, cookies may not be the most efficient option.
• Cookies are not the best choice for storing sensitive information such as passwords or
credit card details due to the potential for interception or unauthorized access.
• Cookies are susceptible to various security threats, such as cross-site scripting (XSS)
attacks. If a malicious script is injected into a web page, it can potentially access and
manipulate cookie data.
• Since cookies are stored on the client side, users have control over them. Users can
choose to disable cookies in their browsers, impacting the functionality of websites that
rely heavily on cookies for session management or user customization.

5. Demonstrate the process to set and unset sessions in PHP.


Answer: In PHP, sessions are commonly used to store and retrieve data across multiple pages.
Here's a simple example demonstrating how to set and unset sessions:
• Setting Sessions:
<?php
session_start();
// Set session variables
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';
// Display a message
echo "Session variables are set.";
session_write_close();
?>
In this example:
▪ session_start() initializes a new session or resumes an existing one.
▪ $_SESSION['user_id'] and $_SESSION['username'] are used to set session
variables.
▪ session_write_close() is optional but recommended after setting session variables.
It writes session data and closes the session, freeing up resources.
• Unsetting Sessions (Destroying Sessions): In this example,
<?php
session_start();
// Unset specific session variables (if needed)
unset($_SESSION['user_id']);
unset($_SESSION['username']);
session_destroy();
// Display a message
echo "Session is destroyed.";
?>
▪ unset($_SESSION['user_id']) and unset($_SESSION['username']) are optional and
used to unset specific session variables if you only want to remove certain data from
the session.
▪ session_destroy() is used to destroy the entire session, including all session data.
echo "Session is destroyed."; is a message to indicate that the session has been
destroyed.
6. Write down the comparison between cookies and sessions.
Answer: Certainly! Here's a comparison between cookies and sessions in web development:
▪ Storage Location:
Cookies: Stored on the client-side (browser).
Sessions: Typically stored on the server-side.
▪ Security:
Cookies: Vulnerable to security threats such as cross-site scripting (XSS) attacks if not handled
properly. Limited security for sensitive data.
Sessions: Generally more secure because session data is stored on the server. However, session
hijacking is a potential risk if not managed correctly.
▪ Storage Capacity:
Cookies: Limited to a small amount of data (usually 4 KB per cookie).
Sessions: Can handle larger amounts of data, as they are stored on the server.
▪ Ease of Use:
Cookies: Easy to use and implement. Can be set and accessed directly in JavaScript.
Sessions: Require server-side processing and often involve more complex configuration,
especially for secure implementations.
▪ Control:
Cookies: Users have control over cookies and can disable them in their browsers.
Sessions: Controlled by the server, and users have limited direct control.
▪ Use Cases:
Cookies: Often used for storing small amounts of data on the client side, such as user
preferences or tracking information.
Sessions: Typically used for more sensitive data, user authentication, and maintaining state
across multiple pages.
▪ Implementation:
Cookies: Set and accessed using the setcookie() function in PHP or JavaScript.
Sessions: Managed using the $_SESSION super global in PHP.
7. What do you mean by SQL injection? Explain the SQL injection scenario with a suitable
example.
Answer: SQL injection is a type of cyber-attack that occurs when an attacker is able to
manipulate a SQL query by injecting malicious SQL code into user-input fields. The vulnerability
arises when user input is not properly sanitized or validated before being included in SQL
statements. If a web application does not handle input correctly, an attacker can insert malicious
SQL code into a query, potentially gaining unauthorized access to a database, modifying data, or
performing other malicious actions.

Example Scenario:

Suppose you have a simple login page on a website where users enter their username and
password. The PHP code handling the login might look like this:

<?php
// Retrieving user input from a form
$username = $_POST['username'];
$password = $_POST['password'];

$query = "SELECT * FROM users WHERE username='$username' AND


password='$password'";

In this example, the $username and $password variables directly take input from the user, and
their values are concatenated into the SQL query string. This approach is vulnerable to SQL
injection.

Now, consider an attacker who enters the following text into the username field:

' OR '1'='1' --

If this input is directly inserted into the SQL query, it modifies the query to become:

SELECT * FROM users WHERE username='' OR '1'='1' --' AND password=''

In this modified query:

• The single quote after the empty username closes the original string.
• The OR '1'='1' condition always evaluates to true, effectively bypassing the password
check.
• The double hyphen (--) denotes a comment in SQL, causing the rest of the original query
to be ignored.

As a result, the attacker might gain access to an account without providing a valid password.
To prevent SQL injection, it's crucial to use parameterized queries or prepared statements, which
allow user input to be safely handled without directly inserting it into the SQL string. Using
parameterized queries helps to separate user input from the SQL code, making it much more
difficult for attackers to inject malicious code.

8. Write a simple PHP program to retrieve user information from SQL database.

Answer: Below is a simple example of a PHP program that connects to a MySQL database and
retrieves user information.

<?php
$conn = mysqli_connect('localhost', 'root', ' ', 'example');
if ($conn) {
echo 'Conected';
}
// SQL query to retrieve user information
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql)
// Check if there are results
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_array($result)) {
echo "User ID: " . $row["user_id"] . "<br>";
echo "Username: " . $row["username"] . "<br>";
echo "Email: " . $row["email"] . "<br>";
echo "--------------------------<br>";
}
} else {
echo "No users found in the database.";
}
// Close the database connection
$conn->close();
?>

This example assumes you have a table named "users" in your database with columns like
"user_id," "username," and "email." Modify the SQL query and output format based on your
specific database schema and requirements.

9. Write down the PHP program to handle login request from the client.
Answer:
<?php
if (isset($_POST["username"]) && isset($_POST["password"])) {
require("db.php"); // establish DB connection
$user = $_POST["username"];
$pass = $_POST["password"];
$query = "SELECT PASSWORD from users WHERE USERNAME=
'".mysql_real_escape_string($user)."' ";
$result = mysql_query($query, $db) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if ($pass == $row["PASSWORD"]) {
$_SESSION["username"] = $user;
}
else {
echo "Invalid username or password <br />";
}
}

After establishing connection

$user and $pass retrieves the submitted username and password from the POST request.

$result = mysql_query($query, $db) or die(mysql_error());

It constructs a SQL query to select the password from the "users" table based on the submitted
username. The mysql_real_escape_string function is used to escape characters and prevent
SQL injection. The query is executed, and any errors lead to script termination with an error
message.

If password match, it implies a successful login.

$_SESSION["username"] = $user;

If the password matches, it sets a session variable "username" with the submitted username,
indicating a successful login.

If the password does not match, it outputs an error message indicating an invalid username or
password.

It's important to note that the use of mysql_real_escape_string is deprecated, and the code
assumes plain text passwords in the database. Modern practices recommend using prepared
statements to prevent SQL injection and storing hashed passwords for security. Additionally, the
mysql_* functions are outdated, and using MySQLi or PDO is recommended for database
interactions.

10. Write a simple PHP code to store user information such as user name, user address and city
into SQL database.
Answer:
<?php
$conn = mysqli_connect('localhost', 'root', ' ', 'example');
if($conn){
echo "Connected!";
}
if(isset($_POST['submit'])) {
$firstname=$_POST['user'];
$add=$_POST['address'];
$city=$_POST['city'];

$insertquery = "insert into info values('$firstname','$add','$city')";


$res = mysqli_query($conn,$insertquery);
if($res) {
echo "Inserted!";
}
}
?>
<html> <body>
<form align="center" action="" method="POST">
First Name: <input type="text" name="user">
Address: <input type="text" name="address">
City: <input type="text" name="city">
<input type="submit" name="submit" value="Submit">
</form>
</body></html>

You might also like