php
php
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.
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.
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);
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
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
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");
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, "/");
• 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, "/");
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'];
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:
• 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 />";
}
}
$user and $pass retrieves the submitted username and password from the POST request.
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.
$_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'];