0% found this document useful (0 votes)
121 views26 pages

Short Answer Questions: 1. Write The Structure of PHP Script With An Example

This document contains a summary of key PHP concepts and examples: 1. PHP scripts use <?php ?> tags and can echo output. A basic script displays "Hello World!". 2. GET requests have limited data in the URL while POST sends larger data in the request body. GET is less secure and can be bookmarked. 3. Constants are defined with define() and have uppercase names. They cannot change value like variables. 4. Bitwise AND operates on bits while logical AND expects boolean values and returns a boolean. 5. Arrays store multiple values and can be numeric, associative, or multidimensional. Numeric arrays use numbers while associative arrays use strings as indexes

Uploaded by

Meeraj Medipalli
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)
121 views26 pages

Short Answer Questions: 1. Write The Structure of PHP Script With An Example

This document contains a summary of key PHP concepts and examples: 1. PHP scripts use <?php ?> tags and can echo output. A basic script displays "Hello World!". 2. GET requests have limited data in the URL while POST sends larger data in the request body. GET is less secure and can be bookmarked. 3. Constants are defined with define() and have uppercase names. They cannot change value like variables. 4. Bitwise AND operates on bits while logical AND expects boolean values and returns a boolean. 5. Arrays store multiple values and can be numeric, associative, or multidimensional. Numeric arrays use numbers while associative arrays use strings as indexes

Uploaded by

Meeraj Medipalli
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/ 26

Web technologies PHP

SHORT ANSWER QUESTIONS:

1. Write the structure of PHP script with an example


A PHP script starts with <?php and ends with ?>
Structure:
<?php
//phpcode
?>
Example:
<html>
<body>
<h1>MyfirstPHPpage</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
2. Write the differences between GET and POST methods

GET POST
1) In case of Get request, only limited In case of post request, large
amount of data can be sent because data is amount of data can be sent
sent in header. because data is sent in body.
2) Get request is not secured because data Post request is secured because
is exposed in URL bar. data is not exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be
bookmarked.
4) Get request is idempotent . It means Post request is non-idempotent.
second request will be ignored until
response of first request is delivered
3. How to define a constant variable in PHP? Give an example
A constant is a name or an identifier for a simple value. A constant value cannot
change during the execution of the script. By default, a constant is case-sensitive. By
convention, constant identifiers are always uppercase. A constant name starts with a
letter or underscore, followed by any number of letters, numbers, or underscores. If
you have defined a constant, it can never be changed or undefined.To define a
constant you have to use define() function and to retrieve the value of a constant, you
have to simply specifying its name. Unlike with variables, you do not need to have a
constant with a $. You can also use the function constant() to read a constant's value if
you wish to obtain the constant's name dynamically.

<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
4. Differentiate between the 'BITWISE AND' operator and the 'LOGICAL AND'
operator in PHP
& (Bitwise AND) : This is a binary operator i.e. it works on two operand. Bitwise
AND operator in PHP takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.
Dept of Cse,TKRCET 1
Web technologies PHP

'LOGICAL AND'
The logical and operator ‘&&’ expects its operands to be boolean expressions (either
1 or 0) and returns a boolean value.
5. Write a PHP program to print reverse of any number
<?php
$num = 23456;
$revnum = 0;
while ($num > 1)
{
$rem = $num % 10;
$revnum = ($revnum * 10) + $rem;
$num = ($num / 10);
}
echo "Reverse number of 23456 is: $revnum";
?>
Output:

Reverse number of 23456 is: 65432


6. What is the difference between PHP and JavaScript?

JAVASCRIPT PHP
Does job for Both Front-end and Back-end. Php is used mostly for Back-end
Purposes only.
Javascript is asynchronous, It doesn’t wait Php is synchronous, It waits for
for Input Output operations. IO operations to execute.
Can be run in browsers and after Node, we Php requires a Server to Run.
can also run it in Command line3. Cannot run without a server.
Js can be combined with HTMl, AJAX and Can be combined with HTML
XML. only.
It is a single threaded language that is It is multi-threaded which means
event-driven which means it never blocks it blocks I/O to carry out multiple
and everything runs concurrently. tasks concurrently.
7. Write about superglobals
In PHP super global is one the variable used to access global variables from
anywhere in the PHP script. PHP Super global variables is accessible inside the same
page that defines it, as well as outside the page. While local variable's scope is within
the page that defines it.
Different types of super global variables are:
• $_GLOBALS.
• $_SERVER.
• $_REQUEST.
• $_GET.
• $_POST.
• $_SESSION.
• $_COOKIE.
• $_FILES.
8. Write a php program to find the factorial of any given number
code:
Method 1: static way
<? php.
$num = 4;
$factorial = 1;
Dept of Cse,TKRCET 2
Web technologies PHP

for ($x=$num; $x>=1; $x--)


{
$factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";
?>
Method 2: Iterative way
<?php
function Factorial($number){
$factorial = 1;
for ($i = 1; $i <= $number; $i++){
$factorial = $factorial * $i;
}
return $factorial;
}
$number = 10;
$fact = Factorial($number);
echo "Factorial = $fact";
?>
Method 3: Use of recursion
<?php
function Factorial($number){
if($number <= 1){
return 1;
}
else{
return $number * Factorial($number - 1);
}
}
$number = 10;
$fact = Factorial($number);
echo "Factorial = $fact";
?>
9. Write a PHP code to generate star triangle
<?php
for($i=0;$i<5;$i++)
{
for($j=5;$j>$i;$j--)
{
echo"&nbsp ";
}
for($k=0;$k<=$i;$k++)
{
echo "* ";
}
echo "<br>";
}
?>
Output:
*
**
***
Dept of Cse,TKRCET 3
Web technologies PHP

****
*****

10. Write a PHP code to swap any two numbers.

<?php
$a = 45;
$b = 78;
echo "Before swapping:<br><br>";
echo "a =".$a." b=".$b."<br><br>";
// Swapping Logic
$third = $a;
$a = $b;
$b = $third;
echo "After swapping:<br><br>";
echo "a =".$a." b=".$b;
?>
Output:
Before Swapping
a=45 b=78
After Swapping
a=78 b=45

LONG ANSWER QUESTIONS:

11. Define an Array? Explain about the types of Arrays in PHP with an example
An array is a data structure that stores one or more similar type of values in a single
value. For example if you want to store 100 numbers then instead of defining 100
variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c
which is called array index.
• Numeric array − An array with a numeric index. Values are stored and accessed in
linear fashion.
• Associative array − An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
• Multidimensional array − An array containing one or more arrays and values are
accessed using multiple indices
Numeric arrays:These arrays can store numbers, strings and any object but their
index will be represented by numbers. By default array index starts from zero.
• Example
Following is the example showing how to create and access numeric arrays.Here we
have used array() function to create array. This function is explained in function
reference
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
Dept of Cse,TKRCET 4
Web technologies PHP

$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>

</body>
</html>
Output:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but
they are different in terms of their index. Associative array will have their index as
string so that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not
be the best choice. Instead, we could use the employees names as the keys in our
associative array, and the value would be their respective salary.

<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("Hari" => 2000, "raghu" => 1000, "zara" => 500);
echo "Salary of Hari is ". $salaries[' Hari '] . "<br />";
echo "Salary of raghu is ". $salaries[' raghu ']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
/* Second method to create array. */
$salaries[' Hari '] = "high";
$salaries['raghu '] = "medium";
$salaries['zara'] = "low";
echo "Salary of Hari is ". $salaries['Ha.ri'] . "<br />";
echo "Salary of raghu is ". $salaries[' raghu ']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body>
</html>
Output:
Salary of Hari is 2000
Salary of Raghu is 1000
Salary of zara is 500
Salary of Hari is high
Salary of raghu is medium
Salary of zara is low

Dept of Cse,TKRCET 5
Web technologies PHP

Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And
each element in the sub-array can be an array, and so on. Values in the multi-dimensional
array are accessed using multiple index.
Example

In this example we create a two dimensional array to store marks of three students in three
subjects

<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body></html>
Output:
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

12. Write a Program to read the form data of user registration using php and display
the retrieved data.
<!DOCTYPE HTML>
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
Dept of Cse,TKRCET 6
Web technologies PHP

</form>
</body>
</html>
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>

OUTPUT:

13. Write Php code to read two values from form and find Area of Triangle and display
the result
<html>
<body>
<form method = "post">
Base: <input type="number" name="base">
<br><br>
Height: <input type="number" name="height"><br>
<input type = "submit" name = "submit" value="Calculate">
</form>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
$base = $_POST['base'];
$height = $_POST['height'];
$area = ($base*$height) / 2;
echo "The area of a triangle with base as $base and height as $height is $area";
}
?>

Dept of Cse,TKRCET 7
Web technologies PHP

OUTPUT:

14. Explain variables and operators with example in PHP

Variables:
The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.

• All variables in PHP are denoted with a leading dollar sign ($).
• The value of a variable is the value of its most recent assignment.
• Variables are assigned with the = operator, with the variable on the left-hand side and
the expression to be evaluated on the right.
• Variables can, but do not need, to be declared before assignment.
• Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
• Variables used before they are assigned have default values.
• PHP does a good job of automatically converting types from one to another when
necessary.

Operator:Collection of operator and operand is called an 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.

• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators

There are following arithmetic operators supported by PHP language −Assume variable A
holds 10 and variable B holds 20 then −

Operator Description Example


+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give
200
/ Divide numerator by de-numerator B / A will give 2
Dept of Cse,TKRCET 8
Web technologies PHP

% Modulus Operator and remainder of after an integer B % A will give 0


division
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9
Comparison Operators
There are following comparison operators supported by PHP language,Assume variable A
holds 10 and variable B holds 20 then −
Operator Description Example
== Checks if the value of two operands are equal or not, if yes (A == B) is
then condition becomes true. not true.
!= Checks if the value of two operands are equal or not, if values (A != B) is
are not equal then condition becomes true. true.
> Checks if the value of left operand is greater than the value of (A > B) is not
right operand, if yes then condition becomes true. true.
< Checks if the value of left operand is less than the value of (A < B) is
right operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is
the value of right operand, if yes then condition becomes true. not true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand, if yes then condition becomes true. true.

Logical Operators
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then
Operator Description Example
And Called Logical AND operator. If both the operands are true (A and B) is
then condition becomes true. true.
Or Called Logical OR Operator. If any of the two operands are (A or B) is
non zero then condition becomes true. true.
&& Called Logical AND operator. If both the operands are non (A && B) is
zero then condition becomes true. true.
|| Called Logical OR Operator. If any of the two operands are (A || B) is
non zero then condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical state !(A && B)
of its operand. If a condition is true then Logical NOT operator is false.
will make false.

Assignment Operators

There are following assignment operators supported by PHP language −

Operator Description Example


= Simple assignment operator, Assigns values from C = A + B will assign
right side operands to left side operand value of A + B into C
+= Add AND assignment operator, It adds right operand C += A is equivalent
to the left operand and assign the result to left to C = C + A
operand
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to
operand from the left operand and assign the result to C=C-A
left operand
*= Multiply AND assignment operator, It multiplies C *= A is equivalent to
right operand with the left operand and assign the C=C*A
result to left operand
Dept of Cse,TKRCET 9
Web technologies PHP

/= Divide AND assignment operator, It divides left C /= A is equivalent to


operand with the right operand and assign the result C=C/A
to left operand
%= Modulus AND assignment operator, It takes modulus C %= A is equivalent
using two operands and assign the result to left to C = C % A
operand

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 −

Operator Description Example


?: Conditional If Condition is true ? Then value X : Otherwise value
Expression Y

Operators Categories

All the operators we have discussed above can be categorised into following categories −

• Unary prefix operators, which precede a single operand.


• Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
• The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of the
first expression.
• Assignment operators, which assign a value to a variable.

Precedence of PHP Operators

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity


Unary ! ++ -- Right to left
Multiplicative */% Left to right
Additive +- Left to right
Relational < <= > Left to right
>=
Equality == != Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= Right to left

Dept of Cse,TKRCET 10
Web technologies PHP

*= /= %=

15. Explain the predefined and user defined functions in PHP with an example
A function is a block of code written in a program to perform some specific task. We can
relate functions in programs to employees in a office in real life for a better
understanding of how functions work. Suppose the boss wants his employee to calculate
the annual budget. So how will this process complete? The employee will take
information about the statics from the boss, performs calculations and calculate the
budget and shows the result to his boss. Functions works in a similar manner. They take
informations as parameter, executes a block of statements or perform operations on this
parameters and returns the result.
Syntax:

function function_name(){
executable code;
}
PHP provides us with two major types of functions:

• Built-in functions : PHP provides us with huge collection of built-in library


functions. These functions are already coded and stored in form of functions. To use
those we just need to call them as per our requirement like, var_dump, fopen(),
print_r(), gettype() and so on.

<?php
if(is_numeric("guru"))
{
echo "true";
}
else
{
echo "false";
}
?>
• User Defined Functions : Apart from the built-in functions, PHP allows us to create
our own customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by
simply calling it.
<?php
function funcex()
{
echo "This is example";
}
// Calling the function
funcex();
?>
16. What is PHP session, how session is created and destroyed.
An alternative way to make data accessible across the various pages of an entire
website is to use a PHP Session.A session creates a file in a temporary directory on
the server where registered session variables and their values are stored. This data will
be available to all pages on the site during that visit. A session ends when the user
loses the browser or after leaving the site, the server will terminate the session after a
predetermined period of time, commonly 30 minutes duration.
Dept of Cse,TKRCET 11
Web technologies PHP

• Starting a PHP Session


A PHP session is easily started by making a call to the session_start() function.This
function first checks if a session is already started and if none is started then it starts
one. It is recommended to put the call to session_start() at the beginning of the
page.Session variables are stored in associative array called $_SESSION[]. These
variables can be accessed during lifetime of a session.
The following example starts a session then register a variable called counter that is
incremented each time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not

<?php
session_start();
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>
Output: You have visited this page 1in this session.

A PHP session can be destroyed by session_destroy() function. This function does not need
any argument and a single call can destroy all the session variables. If you want to destroy a
single session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable −

<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables −

<?php
session_destroy();
?>
17. Write a PHP script to open, close, read and write into a file.

The following functions related to files −

• Opening a file
• Reading a file
• Writing a file
• Closing a file

Opening and Closing Files


Dept of Cse,TKRCET 12
Web technologies PHP

The PHP fopen() function is used to open a file. It requires two arguments stating first the file
name and then mode in which to operate.

Files modes can be specified as one of the six options in this table.

r:Opens the file for reading only.Places the file pointer at the beginning of the file

r+:Opens the file for reading and writing.Places the file pointer at the beginning of the file.

w:Opens the file for writing only.Places the file pointer at the beginning of the file. and
truncates the file to zero length. If files does notexist then it attempts to create a file.

w+:Opens the file for reading and writing only.Places the file pointer at the beginning of the
file.and truncates the file to zero length. If files does notexist then it attempts to create a file.

a:Opens the file for writing only.Places the file pointer at the end of the file.If files does not
exist then it attempts to create a file.

a+:Opens the file for reading and writing only.Places the file pointer at the end of the file.If
files does not exist then it attempts to create a file

If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file
pointer which is used for further reading or writing to that file.

After making a changes to the opened file it is important to close it with the fclose() function.
The fclose() function requires a file pointer as its argument and then returns true when the
closure succeeds or false if it fails.

Reading a fileOnce a file is opened using fopen() function it can be read with a function
called fread(). This function requires two arguments. These must be the file pointer and the
length of the file expressed in bytes.

The files length can be found using the filesize() function which takes the file name as its
argument and returns the size of the file expressed in bytes.

So here are the steps required to read a file with PHP.

• Open a file using fopen() function.


• Get the file's length using filesize() function.
• Read the file's content using fread() function.
• Close the file with fclose() function.

The following example assigns the content of a text file to a variable then displays those
contents on the web page.

<html>
<head>
<title>Reading a file using PHP</title>
</head>

<body>
<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" );
Dept of Cse,TKRCET 13
Web technologies PHP

if( $file == false ) {


echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
</body>
</html>

It will produce the following result −

Writing a file

A new file can be written or text can be appended to an existing file using the PHP fwrite()
function. This function requires two arguments specifying a file pointer and the string of data
that is to be written. Optionally a third integer argument can be included to specify the length
of the data to write. If the third argument is included, writing would will stop after the
specified length has been reached.

The following example creates a new text file then writes a short text heading inside it. After
closing this file its existence is confirmed using file_exist() function which takes file name as
an argument

<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false ) {
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>
<?php
$filename = "newfile.txt";
$file = fopen( $filename, "r" );
Dept of Cse,TKRCET 14
Web technologies PHP

if( $file == false ) {


echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "$filetext" );
echo("file name: $filename");
?>
</body>
</html>
It will produce the following result −

18. Write a PHP script for uploading a file to the server and display the uploaded files
details
A PHP script can be used with a HTML form to allow users to upload files to the server.
Initially files are uploaded into a temporary directory and then relocated to a target
destination by a PHP script
Information in the phpinfo.php page describes the temporary directory that is used for file
uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is
stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini
The process of uploading a file follows these steps −
The user opens the page containing a HTML form featuring a text files, a browse button
and a submit button.
The user clicks the browse button and selects a file to upload from the local PC.

The full path to the selected file appears in the text filed then the user clicks the submit
button.
The selected file is sent to the temporary directory on the server.
The PHP script that was specified as the form handler in the form's action attr ibute
checks that the file has arrived and then copies the file into an intended directory.
The PHP script confirms the success to the user.

As usual when writing files it is necessary for both temporary and final locations to have
permissions set that enable file writing. If either is set to be read-only then process will fail.
An uploaded file could be a text file or image file or any document.
Creating an upload form
The following HTML code below creates an up loader form. This form is having method
attribute set to post and enctype attribute is set to multipart/form-data
There is one global PHP variable called $_FILES. This variable is an associate double
dimension array and keeps all the information related to uploaded file. So if the value
assigned to the input's name attribute in uploading form was file, then PHP would create
following five variables –
$_FILES['file']['tmp_name'] the uploaded file in the temporary dir on the web
server.
Dept of Cse,TKRCET 15
Web technologies PHP

$_FILES['file']['name'] − the actual name of the uploaded file.


$_FILES['file']['size'] − the size in bytes of the uploaded file.
$_FILES['file']['type'] − the MIME type of the uploaded file.
$_FILES['file']['error'] − the error code associated with this file upload.

Example: Below example should allow upload images and gives back result as uploaded
file information.
<?php
if(isset($_FILES['image']))
{
$file_name =
$_FILES['image']['name'];
$file_size =$_FILES['image']['size']; $file_type=$_FILES['image']['type'];
}
?>
<html> <body>
<form action="" method="POST"
enctype="multipart/form-data">
<input type="file" name="image" /> <input type="submit"/>
<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul>
<img src=" <?php echo $_FILES['image']['name']; ?>" height="200"
width="200" />
</form>
</body>
</html

Dept of Cse,TKRCET 16
Web technologies PHP

19. List and explain the string functions in PHP


PHP String Functions
some commonly used functions to manipulate strings.

• strlen() - Return the Length of a String


The PHP strlen() function returns the length of a string.
Example:
Return the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
• str_word_count() - Count Words in a String
The PHP str_word_count() function counts the number of words in a string.
Example:
Count the number of word in the string "Hello world!":
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
• strrev() - Reverse a String
The PHP strrev() function reverses a string.
Example:
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
• strpos() - Search For a Text Within a String
The PHP strpos() function searches for a specific text within a string. If a match is found, the
function returns the character position of the first match. If no match is found, it will return
FALSE.
Example:
Search for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
• str_replace() - Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a
string.
Example:
Replace the text "world" with "Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>

20. What are the differences between Get and post methods in form submitting. Give
the case where we can use get and we can use post methods

BASIS FOR
COMPARISON GET POST
Parameters are placed
inside URI Body

Dept of Cse,TKRCET 17
Web technologies PHP

Purpose Retrieval of documents Updation of data


Query results Capable of being bookmarked. Cannot be bookmarked.
Vulnerable, as present in
Security plaintext Safer than GET method
Form data type Only ASCII characters are No constraints, even binary data is
constraints permitted. permitted.
Should be kept as minimum as
Form data length possible. Could lie in any range.
Visibility Can be seen by anyone. Doesn't display variables in URL.
Variable size Up to 2000 character. Up to 8 Mb
Caching Method data can be cached. Does not cache the data.

21. List the statements that are used to connect PHP with MySQL.

MySQL Connection Using MySQL Binary


You can establish the MySQL database using the mysql binary at the command prompt.
Example:
Here is a simple example to connect to the MySQL server from the command prompt −
[root@host]# mysql -u root -p
Enter password:******
This will give you the mysql> command prompt where you will be able to execute any SQL
command. Following is the result of above command −
The following code block shows the result of above code −
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2854760 to server version: 5.0.9

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

In the above example, we have used root as a user but you can use any other user as well.
Any user will be able to perform all the SQL operations, which are allowed to that user.

You can disconnect from the MySQL database any time using the exit command at mysql>
prompt.
mysql> exit

MySQL Connection Using PHP Script

PHP provides mysql_connect() function to open a database connection. This function takes
five parameters and returns a MySQL link identifier on success or FALSE on failure.

Syntax
connection mysql_connect(server,user,passwd,new_link,client_flag);
Sr.No. Parameter & Description

server
1
Optional − The host name running the database server. If not specified, then the
default value will be localhost:3306.
user
2
Optional − The username accessing the database. If not specified, then the default
will be the name of the user that owns the server process.

Dept of Cse,TKRCET 18
Web technologies PHP

passwd
3
Optional − The password of the user accessing the database. If not specified, then
the default will be an empty password.
new_link
4
Optional − If a second call is made to mysql_connect() with the same arguments,
no new connection will be established; instead, the identifier of the already opened
connection will be returned.
client_flags

Optional − A combination of the following constants −

5 • MYSQL_CLIENT_SSL − Use SSL encryption.


• MYSQL_CLIENT_COMPRESS − Use compression protocol.
• MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names.
• MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds
of inactivity before closing the connection.

You can disconnect from the MySQL database anytime using another PHP function
mysql_close(). This function takes a single parameter, which is a connection returned by the
mysql_connect() function.
Syntax
bool mysql_close ( resource $link_identifier );

If a resource is not specified, then the last opened database is closed. This function returns
true if it closes the connection successfully otherwise it returns false.

Example
Try the following example to connect to a MySQL server −
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost:3306';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
</body>
</html>
22. Explain PHP form processing with an example
PHPFormHandling:The following is the process that how to collect user inputs submitted through
a form using the PHP superglobal variables $_GET, $_POST and $_REQUEST.

Dept of Cse,TKRCET 19
Web technologies PHP

Creating a Simple Contact Form


This is a simple HMTL contact form that allows users to enter their comment and feedback
then displays it to the browser using PHP.

Open up the favorite code editor and create a new PHP file. Now type the following code
and save this file as "contact-form.php" in the root directory of your project.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action="process-form.php" method="post">
<p>
<label for="inputName">Name:<sup>*</sup></label>
<input type="text" name="name" id="inputName">
</p>
<p>
<label for="inputEmail">Email:<sup>*</sup></label>
<input type="text" name="email" id="inputEmail">
</p>
<p>
<label for="inputSubject">Subject:</label>
<input type="text" name="subject" id="inputSubject">
</p>
<p>
<label for="inputComment">Message:<sup>*</sup></label>
<textarea name="message" id="inputComment" rows="5" cols="30"></textarea>
</p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>

Dept of Cse,TKRCET 20
Web technologies PHP

Explanation of code

Notice that there are two attributes within the opening <form> tag:

• The action attribute references a PHP file "process-form.php" that receives the data
entered into the form when user submit it by pressing the submit button.
• The method attribute tells the browser to send the form data through POST method.

Rest of the elements inside the form are basic form controls to receive user inputs.

Capturing Form Data with PHP

To access the value of a particular form field, you can use the following superglobal
variables. These variables are available in all scopes throughout a script.

Superglobal Description

Contains a list of all the field names and values sent by a form using the get method (i.e.
$_GET
via the URL parameters).

Contains a list of all the field names and values sent by a form using the post method
$_POST
(data will not visible in the URL).

Contains the values of both the $_GET and $_POST variables as well as the values of
$_REQUEST
the $_COOKIE superglobal variable.

When a user submit the above contact form through clicking the submit button, the form data
is sent to the "process-form.php" file on the server for processing. It simply captures the
information submitted by the user and displays it to browser.

Dept of Cse,TKRCET 21
Web technologies PHP

The PHP code of "process-form.php" file will look something like this:

Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h1>Thank You</h1>
<p>Here is the information you have submitted:</p>
<ol>
<li><em>Name:</em> <?php echo $_POST["name"]?></li>
<li><em>Email:</em> <?php echo $_POST["email"]?></li>
<li><em>Subject:</em> <?php echo $_POST["subject"]?></li>
<li><em>Message:</em> <?php echo $_POST["message"]?></li>
</ol>
</body>
</html>

The PHP code above is quite simple. Since the form data is sent through the post method, you
can retrieve the value of a particular form field by passing its name to the $_POST
superglobal array, and displays each field value using echo() statement.

In real world we cannot trust the user inputs; you must implement some sort of validation to
filter the user inputs before using them. In the next chapter you will learn how sanitize and
validate this contact form data and send it through the email using PHP.

23. A. Discuss different types of Conditional statements in PHP.

PHP Conditional Statements

PHP also allows you to write code that perform different actions based on the results of a
logical or comparative test conditions at run time. This means, you can create test conditions
in the form of expressions that evaluates to either true or false and based on these results
you can perform certain actions.

There are several statements in PHP that you can use to make decisions:

• The if statement
• The if...else statement
• The if...elseif....else statement
• The switch...case statement

The if Statement
The if statement is used to execute a block of code only if the specified condition evaluates to
true. This is the simplest PHP's conditional statements and can be written like:

Dept of Cse,TKRCET 22
Web technologies PHP

if(condition){
//Codetobeexecuted
}

The following example will output "Have a nice weekend!" if the current day is Friday:

Example
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
}
?>

The if...else Statement

You can enhance the decision making process by providing an alternative choice through
adding an else statement to the if statement. The if...else statement allows you to execute one
block of code if the specified condition is evaluates to true and another block of code if it is
evaluates to false. It can be written, like this:

if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}

The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!"

Example
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>

The if...elseif...else Statement

The if...elseif...else a special statement that is used to combine multiple if...else statements.

if(condition1){
// Code to be executed if condition1 is true
} elseif(condition2){
// Code to be executed if the condition1 is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}
Dept of Cse,TKRCET 23
Web technologies PHP

The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday, otherwise it will output "Have a nice
day!"

Example
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>

The Ternary Operator

The ternary operator provides a shorthand way of writing the if...else statements. The ternary
operator is represented by the question mark (?) symbol and it takes three operands: a
condition to check, a result for true, and a result for false.

To understand how this operator works, consider the following examples:

Example
<?php
if($age < 18){
echo 'Child'; // Display Child if age is less than 18
} else{
echo 'Adult'; // Display Adult if age is greater than or equal to 18
}
?>

Using the ternary operator the same code could be written in a more compact way:

Example
<?php echo ($age < 18) ? 'Child' : 'Adult'; ?>

The ternary operator in the example above selects the value on the left of the colon (i.e.
'Child') if the condition evaluates to true (i.e. if $age is less than 18), and selects the value on
the right of the colon (i.e. 'Adult') if the condition evaluates to false.Code written using the
ternary operator can be hard to read. However, it provides a great way to write compact if-
else statements.

24. Write a PHP program to demonstrate the passing a variable by reference


pass by reference: When variables are passed by reference, use & (ampersand) symbol
need to be added before variable argument. For example: function( &$x ). Scope of both
global and function variable becomes global as both variables are defined by same
reference. Therefore, whenever global variable is change, variable inside function also
gets changed and vice-versa is applicable.

Dept of Cse,TKRCET 24
Web technologies PHP

Example:

<?php
// Function used for assigning new value to
// $string variable and printing it
function print_string( &$string ) {
$string = "Function hello TKR \n";
// Print $string variable
print( $string );
}

// Driver code
$string = "Global hello TKR \n";
print_string( $string );
print( $string );
?>
Output:
Function hello TKR
Function hello TKR

Dept of Cse,TKRCET 25
Web technologies PHP

Dept of Cse,TKRCET 26

You might also like