✅PHP EXAM MOST IMP QUETION FOR SEM 5❇️TY BCA PHP MATERIAL❓BCA SUBJECT MATERIAL PDF✅
Q..Php Variables
Variables in a program are used to store some values or data that can be used later in a program. PHP has its own way of declaring and storing variables.
There are few rules, that needs to be followed and facts that need to be kept in mind while dealing with variables in PHP:
1)Local variables:
<?php
$num = 60;
function local_var()
{
// This $num is local to this function
// the variable $num outside this function
// is a completely different variable
$num = 50;
echo "local num = $num \n";
}
local_var();
// $num outside function local_var() is a
// completely different Variable than that of
// inside local_var()
echo "Variable num outside local_var() is $num \n";
?>
2)Global variables:
The variables declared outside a function are called global variables.
These variables can be accessed directly outside a function.
<?php
$num = 20;
// function to demonstrate use of global variable
function global_var()
{
// we have to use global keyword before
// the variable $num to access within
// the function
global $num;
echo "Variable num inside function : $num \n";
}
global_var();
echo "Variable num outside function : $num \n";
?>
3.Static variable:
It is the characteristic of PHP to delete the variable, ones it completes its execution and the memory is freed.
But sometimes we need to store the variables even after the completion of function execution.
To do this we use static keyword and the variables are then called as static variables.
Example:
-Filter_none -edit -play_arrow -brightness_4
<?php
// function to demonstrate static variables
function static_var()
{
// static variable
static $num = 5;
$sum = 2;
$sum++;
$num++;
echo $num, "\n";
echo $sum, "\n";
}
// first function call
static_var();
// second function call
static_var();
?>
static_var();
// second function call
static_var();
?>
Q2. Login Page
Login page should be as follows and works based on session. If the user close the session, it will erase the session data.
<?php
ob_start();
session_start();
?>
<?
// error_reporting(E_ALL);
// ini_set("display_errors", 1);
?>
<html lang = "en">
<head>
<title>Tutorialspoint.com</title>
<link href = "css/bootstrap.min.css" rel = "stylesheet">
<style>
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #ADABAB;
}
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
color: #017572;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
border-color:#017572;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
border-color:#017572;
}
h2{
text-align: center;
color: #017572;
}
</style>
</head>
<body>
<h2>Enter Username and Password</h2>
<div class = "container form-signin">
<?php
$msg = '';
if (isset($_POST['login']) && !empty($_POST['username'])
&& !empty($_POST['password'])) {
if ($_POST['username'] == 'tutorialspoint' &&
$_POST['password'] == '1234') {
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
$_SESSION['username'] = 'tutorialspoint';
echo 'You have entered valid use name and password';
}else {
$msg = 'Wrong username or password';
}
}
?>
</div> <!-- /container -->
<div class = "container">
<form class = "form-signin" role = "form"
action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);
?>" method = "post">
<h4 class = "form-signin-heading"><?php echo $msg; ?></h4>
<input type = "text" class = "form-control"
name = "username" placeholder = "username = tutorialspoint"
required autofocus></br>
<input type = "password" class = "form-control"
name = "password" placeholder = "password = 1234" required>
<button class = "btn btn-lg btn-primary btn-block" type = "submit"
name = "login">Login</button>
</form>
Click here to clean <a href = "logout.php" tite = "Logout">Session.
</div>
</body>
</html>
Logout.php
It will erase the session data.
<?php
session_start();
unset($_SESSION["username"]);
unset($_SESSION["password"]);
echo 'You have cleaned session';
header('Refresh: 2; URL = login.php');
?>
Q3.PHP - Operator Types
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.
1.Arithmetic Operators
Comparison Operators
Logical Operators
Assignment Operators
Conditional Operator
There is one more operator called conditional operator.
This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation.
The conditional operator has this syntax −
Precedence of PHP Operators
Q4 PHP Sessions
What is a PHP Session?
when you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are.
It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state
Start a PHP Session
A session is started with the session_start() function. Session variables are set with the PHP global variable: $_SESSION. Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Note: The session_start() function must be the very first thing in your document.
Before any HTML tags.
Get PHP Session Variable Values
Next, we create another page called "demo_session2.php". From this page, we will access the session information we set on the first page ("demo_session1.php"). Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()). Also notice that all session variable values are stored in the global $_SESSION variable:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
<html>
Modify a PHP Session Variable
To change a session variable, just overwrite it: Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
<body>
<Html>
Destroy a PHP Session
To remove all global session variables and destroy the session, use session_unset() and session_destroy():
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables session_unset();
session_unset();
// destroy the session session_destroy();
session_destroy();
?>
</body>
</html>
QUETION5 PHP Cookies
Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies.
The Anatomy of a Cookie Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this − HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.
Setting Cookies with PHP PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before tag. For each cookie this function has to be called separately.
Here is the detail of all the arguments −
Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value − This sets the value of the named variable and is the content that you actually want to store.
Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
Accessing Cookies with PHP
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "
"; /* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "
"; echo $_COOKIE["age"] . " ";
/* is equivalent to */ echo $HTTP_COOKIE_VARS["age"] . " ";
?>
</body>
</html>
Deleting Cookie with PHP
Officially, to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on. It is safest to set the cookie with a date that has already expired –
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<? Php eco “deleted cookie” ?>
</body>
</html>
QUETION6 PHP DATA TYPES
1PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
2.PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Example
<?php
$x = 5985;
var_dump($x);
?>
3.PHP Float
A float (floating point number) is a number with a decimal
point or a number in exponential form.
In the following example $x is a float. The PHP var_dump()
function returns the data type and value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
4.PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
5.PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump()
function returns the data type and value:
ExEXample
<?php $cars = array("Volvo","BMW","Toyota"); var_dump($cars); ?>
PHP Object
Classes and objects are the two main aspects of object-oriented programming.
A class is a template for objects, and an object is an instance of a class.
Example
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
$myCar = new Car("black", "Volvo");
echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP.
A common example of using the resource data type is a database call.
We will not talk about the resource type here, since it is an advanced topic.
QU7 PHP User-defined functions
PHP has a large number of built-in functions such as mathematical, string, date, array functions etc. It is also possible to define a function as per specific requirement. Such function is called user defined function.
Syntax
//define a function
function myfunction($arg1, $arg2, ... $argn)
{
statement1;
statement2;
..
..
return $val;
}
//call function
$ret=myfunction($arg1, $arg2, ... $argn);
Example
<?php
//function definition
function sayHello(){
echo "Hello World!";
}
//function call
sayHello();
?>
function with arguments
<?php
function add($arg1, $arg2){
echo $arg1+$arg2 . "\n";
}
add(10,20);
add("Hello", "World");
?>
function return
<?php
function add($arg1, $arg2){
return $arg1+$arg2;
}
$val=add(10,20);
echo "addition:". $val. "\n";
$val=add("10","20");
echo "addition: $val";
?>
function with default argument value
<?php
function welcome($user="Guest"){
echo "Hello $user\n";
}
//overrides default
welcome("admin");
//uses default
welcome();?>
Recursive function
<?php
function factorial($n){
if ($n < 2) {
return 1;
} else {
return ($n * factorial($n-1));
}
}
echo "factorial(5) = ". factorial(5);
?>
QUETION 8ARRAY SHORTING
Array Sorting Function we will go through the following PHP array sort functions:
sort() - sort arrays in ascending order rsort() - sort arrays in descending order asort() - sort associative arrays in ascending order, according to the value ksort() - sort associative arrays in ascending order, according to the key arsort() - sort associative arrays in descending order, according to the value krsort() - sort associative arrays in descending order, according to the key
(1)Sort Array in Ascending Order -
(2)Sort Array in Descending Order - rsort()
(3)Sort Array (Ascending Order), According to Value - asort()
(4)Sort Array (Ascending Order), According to Value - arsort()
(5)Sort Array (Ascending Order), According to Key - ksort()
(6)Sort Array (Ascending Order), According to Key - krsort()
(7)PHP count() Function
(8)PHP current() Function
(9)PHP prev() Function
(10) PHP next() Function
(11) PHP list() Function
(12) PHP in_array() Function
(13) PHP end() Function
(14) PHP each() Function
(15) PHP array_chunk() Function
Q9/Date & Time Function
(1) PHP date() function (2) PHP getdate() Function The getdate() function returns date/time information of a timestamp or the current local date/time. (3) PHP checkdate() Function The checkdate() function is used to validate a Gregorian date. (4) PHP date_create() Function The date_create() function returns a new DateTime object. (5) PHP date_format() Function The date_format() function returns a date formatted according to the specified format. (6) PHP date_add() Function(7) PHP date_diff() Function(8) PHP date_default_timezone_get() Function(9) PHP date_default_timezone_set() Function(10) PHP time() Function
Q10PHP STRING FUCTION
1) PHP strtolower() function
The strtolower() function returns string in lowercase letter.
Syntax
1string strtolower ( string $string )
Example
<?php
$str="My name is KHAN";
$str=strtolower($str);
echo $str;
?>
2) PHP strtoupper() function
The strtoupper() function returns string in uppercase letter.
Syntax
string strtoupper ( string $string )
Example
<?php
$str="My name is KHAN";
$str=strtoupper($str);
echo $str;
?>
3) PHP ucfirst() function
The ucfirst() function returns string converting first character into uppercase.
It doesn't change the case of other characters.
Syntax
string ucfirst ( string $str )
Example
<?php
$str="my name is KHAN";
$str=ucfirst($str);
echo $str;
?>
4) PHP lcfirst() function
The lcfirst() function returns string converting first character into lowercase.
It doesn't change the case of other characters.
Syntax
string lcfirst ( string $str )
Example
<?php
$str="MY name IS KHAN";
$str=lcfirst($str);
echo $str;
?>
5) PHP ucwords() function
The ucwords() function returns string converting first character of each word into uppercase.
Syntax
string ucwords ( string $str )
Example
<?php
$str="my name is Sonoo jaiswal";
$str=ucwords($str);
echo $str;
?>
6) PHP strrev() function
The strrev() function returns reversed string.
Syntax
string strrev ( string $string )
Example
<?php
$str="my name is Sonoo jaiswal";
$str=strrev($str);
echo $str;
?>
7) PHP strlen() function
The strlen() function returns length of the string.
Syntax.
0 Comments
If You Any Query Please Tell Me..?