PHP QB
PHP QB
i)Get method:
It processes the client request which is sent by the client, using the HTTP get method.
Browser uses get method to send request.
ii)Post method
It handles requests in a servlet which is sent by the client. If a client is entering registration data in
an html form, the data can be sent using post method.
Serialize() :
It is a technique used by programmers to preserve their working data in a format that can later be
restored to its previous form.
Serializing an object means converting it to a byte stream representation that can be stored in a file. It
converts a storable representation of a value.
Syntax : serialize(value);
Example : <?php
$a = array(‘Joey’, 'Chandler', 'Ross’);
$s = serialize($a);
print_r($s);
?>
Output :
a:3:{i:0;s:5:"Joey";i:1;s:5:"Chandler";i:2;s:5:"Ross";}
Unserialize() :
The unserialize() function converts serialized data back into actual data.
Syntax: unserialize(string, options);
Example:
<?php
$a = array(‘Joey’, 'Chandler', 'Ross’);
$s = serialize($a);
print_r($s);
$s1 = unserialize($s);
echo "<br>";
print_r($s1);
?>
Output:
Array ( [0] => Joey [1] => Chandler [2] => Ross )
4. Define Introspection
Introspection in PHP offers the useful ability to examine an object's characteristics, such as its name,
parent class (if any) properties, classes, interfaces and methods.
PHP offers a large number functions that can be used to accomplish the above task.
Cookie : PHP cookie is a small piece of information which is stored at the client browser. It is used to
recognize the user.
Cookies are created at the server side and saved to the client browser. Each time when a client sends a
request to the server, a cookie is embedded with the request. Such way, cookie can be received at the
server side.In short, cookie can be created, sent and received at server end.
Session : Session cookies expire at the end of the session.
This means, when you close your browser window, the session cookie is deleted.
A session cookie may be created when you visit a site or portion of a site.
The cookie exists for the duration of your visit. This website only uses session cookies.
Session cookies are temporary means they are stored temporarily in memory and are automatically
removed when the browser closes or the session ends.
For example, a session cookie is created when you use the Personal Login to access secured
pages.Depending on the settings in your browser, you may have the option to deny the session cookie;
however, if you deny the cookie you may have trouble using the site which relies on that cookie.
8. Differentiate Session and Cookie
9. What is Inheritance
Syntax:
class Parent
{
//code
}
class Child extends Parent
{ //child can use parent class code here
}
10. What are the different types of inheritance
Single Inheritance:
● Single inheritance refers to the concept where a class can inherit properties and methods from
only one parent class. PHP supports single inheritance, meaning a class can extend only one
other class.
Hierarchical Inheritance:
● Hierarchical inheritance occurs when multiple classes extend the same parent class. In other
words, it forms a hierarchy of classes where multiple child classes inherit from a single parent
class.
Multiple Inheritance (Through Interfaces):
● While PHP does not support multiple inheritance in terms of classes (a class cannot extend more
than one class at a time), it does support multiple inheritance through interfaces.
● Interfaces in PHP allow a class to implement multiple interfaces, effectively inheriting the
method signatures defined in those interfaces. This allows a form of multiple inheritance, where
a class can inherit method signatures from multiple interfaces.
INSERT INTO table_name (column1, column2, column3,etc) VALUES (value1, value2, value3, etc);
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
ASSIGNMENT 5
Introspection is the ability of a program to examine an object's characteristics such as its name,parent
class,properties and method.
Introspection allow us to:
1.Obtain the name of the class to which an object belongs as well as its member properties and method
2.write generic debuggers,serializers,profilers
Introspection in PHP offers the useful ability to examine classes, interfaces, properties and method with
introspection we can write code that operates on any class or object
Example:
<?php
class Test
{
function testing_one()
{
return(true);
}
function testing_two()
{
return(true);
}
function testing_three()
{
return(true);
}
//Class "Test" exist or not
if (class_exists('Test'))
{
$t = new Test();
echo "The class is exist. <br>";
}
else
{
echo "Class does not exist. <br>";
}
//Access name of the class
$p= new Test();
echo "Its class name is " ,get_class($p) , "<br>";
//Aceess name of the methods/functions
$method = get_class_methods(new Test());
echo "<b>List of Methods:</b><br>";
foreach ($method as $method_name)
{
echo "$method_name<br>";
}
?>
Output :
The class is exist.
Its class name is Test
List of Methods:
testing_one
testing_two
testing_three
2. Explain
1. class_exist() :
This function is used to determine whether a class exists.It takes a string and return a boolean value.
Syntax- $yes_no=class_exists(classname);
This function returns TRUE if classname is a defined class, or FALSE
2. is_subclass_of():
● This function checks whether a given object belongs to a subclass of a specified class. It takes
two parameters: the object instance and the class name to compare against. It returns true if the
object is an instance of a subclass of the specified class, and false otherwise.
3. get_parent_class():
● This function returns the name of the parent class of an object or class. If the object or class does
not have a parent class, it returns false.
4. get_object_vars():
● This function returns an associative array containing all the properties of an object. It takes one
parameter, the object whose properties you want to retrieve, and returns an array where the keys
are the property names and the values are the property values.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Management</title>
</head>
<body>
<form method="post">
<label for="cookie_value">Enter cookie value:</label>
<input type="text" id="cookie_value" name="cookie_value">
<button type="submit" name="create_cookie">Create Cookie</button>
<button type="submit" name="modify_cookie">Modify Cookie</button>
<button type="submit" name="delete_cookie">Delete Cookie</button>
</form>
<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Handling create cookie
if (isset($_POST["create_cookie"])) {
$cookie_name = "user";
$cookie_value = $_POST["cookie_value"];
$expiry_time = time() + (86400 * 30); // 30 days
setcookie($cookie_name, $cookie_value, $expiry_time, "/");
echo "Cookie '$cookie_name' with value '$cookie_value' has been created.<br>";
}
// Handling modify cookie
if (isset($_POST["modify_cookie"])) {
$cookie_name = "user";
$cookie_value = $_POST["cookie_value"];
$expiry_time = time() + (86400 * 30); // 30 days
setcookie($cookie_name, $cookie_value, $expiry_time, "/");
echo "Cookie '$cookie_name' has been modified with new value '$cookie_value'.<br>";
}
// Handling delete cookie
if (isset($_POST["delete_cookie"])) {
$cookie_name = "user";
setcookie($cookie_name, "", time() - 3600, "/");
echo "Cookie '$cookie_name' has been deleted.<br>";
}
}
?>
</body>
</html>
Output
Enter Cookie value : Mohit Create Modify Delete (BUTTONS)
Cookie “user” has been created.
Cookie “user” has been modified.
Cookie “user” has been deleted.
4. Answer the following
i)Use of Cookie.
Internet Explorer usually stores them in Temporal Internet Files folder.
Personalizing the user experience – this is achieved by allowing users to select their preferences.
The page requested that follow are personalized based on the set preferences in the cookies.
Tracking the pages visited by a user
ii)How to set Cookie.
Syntax : setcookie($name, $value, $expiry, $path, $domain, $secure, $httponly);
● $name: (string) The name of the cookie.
● $value: (string) The value of the cookie.
● $expiry: (int) The expiration time of the cookie. If set to 0, the cookie will expire when the
browser session ends. If set to a positive integer, it specifies the number of seconds until the
cookie expires.
● $path: (string) Optional. The path on the server in which the cookie will be available.
● $domain: (string) Optional. The domain that the cookie is available to. If not set, it will default
to the domain of the current webpage.
● $secure: (bool) Optional. Indicates whether the cookie should only be transmitted over a secure
HTTPS connection.
● $httponly: (bool) Optional. Indicates whether the cookie should be accessible only through
HTTP protocol. It cannot be accessed by JavaScript.
Example :
<?php
// Set a cookie named "username" with value "john_doe"
setcookie("username", "john_doe", time() + 3600, "/");
To modify a cookie in PHP, you can simply set a new cookie with the same name, but with the updated
value or properties. Here's how you can modify a cookie:
<?php
// Modify cookie named "username" with a new value
$new_value = "jane_doe";
setcookie("username", $new_value, time() + 3600, "/");
Invalid user input can make errors in processing. Therefore, validating inputs is a must.
1. Required field will check whether the field is filled or not in the proper way. Most of cases we will
use the * symbol for required field.
2. Validation means checking the input submitted by the user.
There are two types of validation available in PHP.
Client-Side Validation − Validation is performed on the client machine web browsers.
Server Side Validation − After submitted by data, The data is sent to a server and performs
validation checks in the server machine.
Some of Validation rules for field
1. Field Validation Rules
Name Should required letters and white-spaces
Email Should be required @ and .
Website Should required a valid URL
Radio Must be selectable at least once
Check Box Must be checkable at least once
Drop Down menu Must be selectable at least once
2. The preg_match() function searches a string for pattern, returning true if the pattern exists, and
false otherwise.
To check whether an email address is well-formed is to use PHP's filter_var() function.
empty() function will ensure that text field is not blank it is with some data, function accepts a variable
as an argument and returns TRUE when the text field is submitted with empty string, zero, NULL or
FALSE value.
3. Is_numeric() function will ensure that data entered in a text field is a numeric value, the
function accepts a variable as an argument and returns TRUE when the text field is submitted
with numeric value.
Example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
</head>
<body>
<h2>Registration Form</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<button type="submit" name="submit">Submit</button>
</form>
<?php
// Form validation logic
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
Program :
<?php
// Database connection parameters
$servername = "localhost"; // Change this if your MySQL server is hosted elsewhere
$username = "your_username"; // Your MySQL username
$password = "your_password"; // Your MySQL password
$dbname = "your_database"; // Your MySQL database name
// Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
Output :
Connected Successfully
Program :
<?php
// Database connection parameters
$servername = "localhost"; // Change this if your MySQL server is hosted elsewhere
$username = "your_username"; // Your MySQL username
$password = "your_password"; // Your MySQL password
$dbname = "your_database"; // Your MySQL database name
// Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// SQL query to create employee table
$sql_create_table = "CREATE TABLE IF NOT EXISTS employees (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";
// Execute query to create table
if (mysqli_query($conn, $sql_create_table)) {
echo "Employee table created successfully<br>";
} else {
echo "Error creating table: " . mysqli_error($conn) . "<br>";
}
// Inserting data into the table
$sql_insert = "INSERT INTO employees (firstname, lastname, email) VALUES ('John', 'Doe',
'[email protected]')";
if (mysqli_query($conn, $sql_insert)) {
echo "Record inserted successfully<br>";
} else {
echo "Error inserting record: " . mysqli_error($conn) . "<br>";
}
// Deleting a record from the table
$sql_delete = "DELETE FROM employees WHERE id = 1";
if (mysqli_query($conn, $sql_delete)) {
echo "Record deleted successfully<br>";
} else {
echo "Error deleting record: " . mysqli_error($conn) . "<br>";
}
// Updating a record in the table
$sql_update = "UPDATE employees SET lastname='Smith' WHERE id = 2";
if (mysqli_query($conn, $sql_update)) {
echo "Record updated successfully<br>";
} else {
echo "Error updating record: " . mysqli_error($conn) . "<br>";
}
// Close connection
mysqli_close($conn);
?>
Output :
Employee table created successfully
Record inserted successfully
Record deleted successfully
Record updated successfully