IPU BCA 5th Sem – PHP End Term 2015 Question Paper Solved

0
2215
IPU BCA PHP END TERM SOLVED QUESTION PAPER

The complete solved question paper for IPU BCA 5th semester exam which was given in PHP End Term Examinations of 2015. If you have any doubt comment below, and follow our Learn PHP Programming Tutorials for stronger basics.

IPU BCA – PHP End Term Question Paper

Question: 1

  • Differentiate between static and dynamic web page
S.No. Static  web page Dynamic  web page
1. Content can get stagnant New content brings people back to the site & helps in the search engines
2. Requires web development expertise to update site Much easier to update
3. Cheap to host Hosting costs a little more
4. Cheap to develop Slower / more expensive to develop
5. Site not as useful for the user Can work as a system to allow staff or users to collaborate

 

Static web pages:

Static website design is the simplest way to create web pages. They are normal HTML pages which will have images, texts and widgets. These are the most affordable type of web pages, but nevertheless very effective if designed properly.

You could create such websites by using any builder software or you could code them from scratch by using HTML language. You could also use CSS coding to get design uniformity in all your web pages.

Static web pages can also be embedded by the flash files. You can easily create
tables, add images, JavaScript and widgets on static website design. The advantage of such websites is that they load fairly fast, and can be manipulated quite easily while optimizing them for search engines.

Dynamic website design:

Basically, dynamic web site design is all about creating interactive pages, where your users can input information and submit them. Some of the most common examples are login pages, registration pages, contact forms etc. When they submit their information, the data gets saved in the database, or get delivered to an e-mail address. You could retrieve them from the database whenever you require them.

Developing dynamic pages is fairly expensive when compared to static web pages. Some of the common programming languages used for creating dynamic web site design are PHP and .Net.  Make sure that you contact a reliable web developer to create such online applications.

 

  • How can you incorporate one PHP file within another with example?

You can include the content of a PHP file into another PHP file before the server executes it.The include and require statements are used to insert useful codes written in other files, in the flow of execution. There are two PHP functions which can be used to included one PHP file into another PHP file.

  • The include() Function
  • The require() Function

This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file.

Include and require are identical, except upon failure:

  • require will produce a fatal error (E_COMPILE_ERROR) and stop the script
  • include will only produce a warning (E_WARNING) and the script will continue

So, if you want the execution to go on and show users the output, even if the include file is missing, use include. Otherwise, in case of FrameWork, CMS or a complex PHP application coding, always use require to include a key file to the flow of execution. This will help avoid compromising your application’s security and integrity, just in-case one key file is accidentally missing.

The include() Function

Syntax:

include ‘filename‘;

Example:

Assume that you have a standard header file, called “header.php”. To include the header file in a page, use include/require:

<html>
<body><?php include ‘header.php’; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>

</body>
</html>

 

The require() Function

The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.

So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.

Syntax:

require ‘filename‘;

You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results.

<html>
<body>
<?php include(“xxmenu.php”); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>

 

 

 

  • What is garbage collection and type juggle in PHP?

Answer:

Garbage Collection

PHP performs garbage collection at three primary junctures:

  1. When you tell it to
  2. When you leave a function
  3. When the script ends

Situation 1 occurs when you use unset ()mysql_free_result(), or other resource-destroying functions that explicitly clear up after your variables.

Situation 2 clears up resources implicitly – any variable that leaves scope, i.e. is no longer applicable, gets cleared up for you.

Finally, Situation 3 frees up all script-related resources implicitly.

It is important to understand that situations 2 and 3 both use the same code path as situation 1 – that is, if you free up a resource using unset() or another resource-destroying function, it will take as much time to do as if PHP had to destroy the resource at the end of the script. This might sound like a rather mundane and, quite frankly, obvious thing to say, however it has profound implications because it means there is little reason to rely on PHP for garbage collection unless you are lazy!

Now, of course that is not quite true – unless you are really strapped for resources, there is little point calling unset () on each of your variables when you are done with them, and similarly there is little point in explicitly cleaning up after a resource just before the script is about to end, as it is going to happen anyway without the need to clog up your script. However, if there is any sizeable delay between you finishing using a big resource, and the juncture at which automatic garbage collection will take place (usually script end, but might also be function end), then you should clean up after yourself and claim the resource back.

Type Juggle:

Type Juggling means dealing with a variable type. In PHP a variables type is determined by the context in which it is used. If an integer value is assigned to a variable, it becomes an integer.

E.g. $var3= $var1 + $var2

Here, if $var1 is an integer,$var2 and $var3 will also be treated as integers.

In order to declare a variable in PHP, the type of the variable is not required. The data type is determined by the value / context of the variable. If integer value is assigned to the variable $num, then the variable $num is of the type integer. If string value is assigned to the variable $str, the variable $str is of the type string.

Unlike other programming languages like C,C++ and Java, PHP does not require to declare any variable specifically. It means if we assign a float value to a variable then it becomes float type and if we assign a string value then the variable will become string data type.

Another example of implicit typecasting is if we add two integer variables then the result is integer type, but if we add one integer and one float type variable then the result will of float data type because float data type has a higher precedence than integer.

PHP Juggling Type Example:

<?php

$temp=”0″;

echo “Value of temp is:”.$temp.” and data type is: “.gettype($temp).”<br/>”;

$temp=”12″;

echo “Value of temp is:”.$temp.” and data type is: “.gettype($temp).”<br/>”;

$temp=12;

echo “Value of temp is:”.$temp.” and data type is: “.gettype($temp).”<br/>”;

$temp+=12;

echo “Value of temp is:”.$temp.” and data type is: “.gettype($temp).”<br/>”;

?>

Output:

Value of temp is:0 and data type is: string
Value of temp is:12 and data type is: string
Value of temp is:12 and data type is: integer

Value of temp is:24 and data type is: integer

 

What is session, how session is created and destroyed

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the user’s computer.

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.

Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favourite colour, etc). By default, session variables last until the user closes the browser.

So; Session variables hold information about one single user, and are available to all pages in one application.

Creation of a session:

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();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION[“favcolor”] = “green”;
$_SESSION[“favanimal”] = “cat”;
echo “Session variables are set.”;
?>
</body>
</html>

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();
?>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo “Favorite color is ” . $_SESSION[“favcolor”] . “.<br>”;
echo “Favorite animal is ” . $_SESSION[“favanimal”] . “.”;
?>
</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();
?>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

 

 

  • What is printf function and difference between echo and print statement in PHP?

PHP printf() Function

Definition and Usage

The printf() function outputs a formatted string.

The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works “step-by-step”. At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.

Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and “\$”. See example two.

  • Syntax
printf(format,arg1,arg2,arg++)

 

echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:

<?php echo ‘Welcome ‘, ‘to’, ‘ ‘, ‘TechInterviews!’; ?>

and it will output the string “Welcome to TechInterviews!” print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.

 

Difference between echo and print()

Echo :

echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:

<?php echo ‘Welcome ‘, ‘to’, ‘ ‘, ‘TechInterviews!’; ?>

and it will output the string “Welcome to TechInterviews!” print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.

printf() is a direct analog of c’s printf(). If you’re comfortable in the c idiom, you might use printf(). A lot of people in the younger generation though, find printf()’s special character syntax to be less readable than the equivalent echo code.

The print function is slightly more dynamic than the echo function by returning a value, and the echo function is slightly (very slightly) faster. The printf function inserts dynamic variables/whatever into wherever you want with special delimiters, such as %s, or %d. For example, printf(‘There is a difference between %s and %s’, ‘good’, ‘evil’) would return ‘There is a difference between good and evil’.

 

(f)  How can you submit a form without displaying it in browser? Which associative array is used to pass data to PHP?

Ans: There are two ways the browser client can send information to the web server.

  • The GET Method
  • The POST Method

We can submit a form without displaying it in browser using ‘The Post Method’ by using hidden fields.

The POST Method

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

  • The POST method does not have any restriction on data size to be sent.
  • The POST method can be used to send ASCII as well as binary data.
  • The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
  • The data sent by POST method is not visible in URL.
  • The PHP provides $_POST associative array to access all the sent information using POST method.

Try out following example by putting the source code in P1.php script.

<html>

<head>

</head

<body>

<form name=”Form1″ action=”P2.php”  method=”POST” >

name<input type=”text” name=”T1″ > <br>

course<input type=”text” name=”T2″> <br>

<input  type=”submit” name=”go” value=”save”>

</form>

</body>

</html>

 

P2.php

<?php

$a=$_REQUEST[‘T1’];

$b=$_REQUEST[‘T2’];

$c=$_REQUEST[‘go’];

?>

 

In PHP there lays an array used to call data from our form. It’s a super global array of PHP and it’s one that is great to have memorized. $_POST retrieves our form data and output’s it directly to our browser. The best way to do this is to make variables for each element in our form, so we can output this data at will, using our own variable names. Place the following lines of code at the top of your form file using the correct PHP syntax.

 

(g)  Name three conditional statements in PHP. When would you use the === operator?

Ans:   Conditional statements in PHP are as follows –

  1. if Statement

If statement is used to execute some code only if a specified condition is true.

 

  • Syntax
if (condition) {
code to be executed if condition is true
;
}

 

Example-

<?php
$t=date(“H”);
if ($t<“20”) {
echo “Have a good day!”;
}
?>

 

  1. If… else Statement

Use If….else statement to execute some code if a condition is true and another code if the condition is false.

  • Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

 

Example-

<?php
$t=date(“H”);
if ($t<“20”){
echo “Have a good day!”;
} else {
echo “Have a good night!”;
}
?>

 

  1. Switch Statement

The switch statement is used to perform different actions based on different conditions.

  • Syntax
switch (n) {
case label1:
  code to be executed if n=label1;
    break;
case label2:
  code to be executed if n=label2;
break;
case label3:
  code to be executed if n=label3;
break;

default:
  code to be executed if n is different from all labels;
}

 

This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

 

Example-

<?php
$favcolor=”red”;
switch ($favcolor) {
case “red”:
echo “Your favorite color is red!”;
break;
case “blue”:
echo “Your favorite color is blue!”;
break;
case “green”:
echo “Your favorite color is green!”;
break;
default:
echo “Your favorite color is neither red, blue, or green!”;
}
?>

 

  • ‘===’ is a comparison operator, as their name implies, allow you to compare two values.
$a===$b Identical True if $a is equal to $b, and they are of same type

 

Example– Case1 (if we use “==”)

<?php

$a=5;

$b=”5″;

if($a==$b){

echo “correct”;

}

else{

echo “false”;

}

?>

 

Output:-   Here Output will be “Correct

Case2 (if we use “===”)

<?php

$a=5;

$b=”5″;

if($a===$b)

{

echo “correct”;

}

else

{

echo “false”;

}

?>

 

Output:- Here Output will be false because there is difference in data type of $a & $b.

(h)   What are the different types of errors in PHP?

Ans:  An error is a type of mistake. We can say an error is a condition of having Incorrect or false knowledge or an error is defined as an unexpected, invalid program state from which it is possible to recover.

 

Types of Error

Basically there are four types of errors in PHP, which are as follows:

  • Parse error (Syntax error)
  • Fatal error
  • Warning error
  • Notice error

 

  1. Parse Errors (Syntax errors)

The Parse error occurs if there is a syntax mistake in the script; the output is parse errors. A parse error stops the execution of the script. There are many reasons for the occurrence of parse errors in PHP. The common reasons are as follows:

  • Unclosed quotes
  • Missing or Extra parentheses
  • Unclosed braces
  • Missing semicolon

 

Example-

 

<?php

echo “cat”;

echo “Dog”

echo “Lion”;

?>

 

Output: – In the above code we missed semicolon in the second line. When that happens there will be a parse error which stops execution of the script.

 

 

  1. Fatal errors

Fatal errors are caused when PHP understands that you’ve written, however what you’re asking it to do can’t be done. Fatal errors stop the execution of the script. If you are trying to access the undefined functions, then the output is fatal error.

 

Example-

 

<?php

Function  fun1()

{

echo “ABC”;

}

Fun2()

echo “Fatal error !”;

?>

 

Output: – In the above code we defined a function fun1() but we call another function fun2() i.e., fun2() is not defined. So a fatal error will be produced that stops execution of the script.

 

  1. Warning Errors

Watching errors will not stop execution of the script. The main reason for warning errors is to include a missing file or using the incorrect number of parameters in a function.

 

Example-

 

<?php

echo “Warning error”;

Include(‘welcome.php’);

?>

 

 

Output: – In the above we include a welcome.php, however the welcome.php file does not exist in the directory so there will be a warning ever produced but that does not stop the execution of the script i.e., you will see a message warning error.

 

  1. Notice errors

Notice error is the same error as a warning error i.e., in the notice error execution of the script does not stop. Notice that the error occurs when you try to access the undefined variable, and then produce a notice error.

 

Example –

 

<?php

$a= “Hello”;

echo “Notice error”;

echo $b;

?>

 

Output: – In the above code we defined a variable which named $a. but we call another variable $b which is not defined so there will be a notice error produced but execution of the script does not stop, you will get a message notice error.

 

 

 

 

 

  • How can we get the properties (size, type, width, height) of an image using PHP image functions?

Ans:  The “GD Library” is the most used image-processing tool in PHP, allowing the dynamic creation and editing of images, charts, thumbnails, etc. The file types that can be created and/or edited using the GD library are GIF, JPEG and PNG.

The GD library will be included with most PHP installations. To confirm if the GD library is activated on your server/host, you can run <?php echo phpinfo(); ?> and scroll down to “GD” to confirm its status.

The GD library includes over 100 functions:

1. getimagesize() Get the size of an image
2. exif_imagetype()  Determine the type of an image
3. imagesx() Get image width
4. imagesy() Get image height

 

  1. getimagesize()

Syntax:    array getimagesize ( string $filename [, array &$imageinfo ] )

The getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag and the correspondant HTTPcontent type.

<?php
$size = getimagesize(“http://www.example.com/gifs/logo.gif”);
?>

 

  1. exif_imagetype()

Syntax:   int exif_imagetype ( string $filename )

exif_imagetype() reads the first bytes of an image and checks its signature.

<?php
if (exif_imagetype(‘image.gif’) != IMAGETYPE_GIF) {
echo ‘The picture is not a gif’;
}
?>

 

  1. imagesx()

Syntax:   int imagesx ( resource $image )

Returns the width of the given image resource.

<?php
// create a 300*200 image
$img = imagecreatetruecolor(300, 200);
echo imagesx($img); // 300
?>

 

  1. imagesy()

Syntax:   int imagesy ( resource $image )

Returns the height of the given image resource.

<?php
// create a 300*200 image
$img = imagecreatetruecolor(300, 200);
echo imagesy($img); // 200
?>

(j) What is query string? Give example in PHP.

       Ans: Query string is usual part of any website it sits in the URL bar and associated with website URL for navigation to the different sections of the website. Query string is used to send data from one page to another.

In a URL (Uniform Resource Locator) The query string always starts with Question mark (?) and separates two variables with address operator (&). For example, consider the following URL:

http:// www.example.com/page.php?mode=1&style=red”

 

This page is being passed variables and their values through the query string, here the variables “mode” and “style” are being passed, with values “1” and “red” respectively. The page is then able to read these variables and react according to them.

·         Passing a Query string to a page

There are two ways to pass a Query String to a page; the first is to enter it manually, for Example –

<a href=”page.php?mode=1″>Mode 1</a>

The above HTML creates a link to a page passing the variable mode with the value “1”.

An alternative, and perhaps more useful, way is to use HTML forms. The main thing to remember with forms is that you need to use the GET method to send information via the query string.

Example:

<form method=”GET” action=”page.php”>

Please enter your name: <input type=”text” name=”username” />

<input type=”submit” value=”submit” />

</form>

 

  • Accessing a query string element in a PHP page

In PHP, all the information passed via the query string is held in the $_GET super global array. To access an item, type $_GET[‘varName’], where varName is the name of the variable in the query string.

 

IPU BCA – PHP Solved Question Paper

Question 2:

  1. a) What is web application? Differentiate between client side scripting and server side scripting.

web application or web app is any software that runs in a web browser. It is created in a browser-supported programming language (such as the combination of JavaScript, HTML and CSS) and relies on a web browser to render the application. The ability to update and maintain web applications without distributing and installing software on potentially thousands of client computers is a key reason for their popularity, as is the inherent support for cross-platform compatibility. Common web applications include webmail, online retail sales, online auctions, wikis and many other functions.

Applications are usually broken into logical chunks called “tiers”, where every tier is assigned a role. Traditional applications consist only of 1 tier, which resides on the client machine, but web applications lend themselves to an n-tiered approach by nature. Though many variations are possible, the most common structure is the three-tiered application. In its most common form, the three tiers are called presentationapplication and storage, in this order. A web browser is the first tier (presentation), an engine using some dynamic Web content technology (such as ASP, ASP.NET, CGI,ColdFusion, JSP/Java, PHP, Perl, Python, Ruby on Rails or Struts2) is the middle tier (application logic), and a database is the third tier (storage).The web browser sends requests to the middle tier, which services them by making queries and updates against the database and generates a user interface.

For more complex applications, a 3-tier solution may fall short, and it may be beneficial to use an n-tiered approach, where the greatest benefit is breaking the business logic, which resides on the application tier, into a more fine-grained model.

 

Differences between client side scripting and server side scripting:

  1. i) Server side scripting is used to create dynamic pages based a number of conditions when the users browser makes a request to the server.

Client side scripting is used when the user’s browser already has all the code and the page is altered on the basis of the users input.

 

  1. ii) The Web Server executes the server side scripting that produces the page to be sent to the browser.

The Web Browser executes the client side scripting that resides at the user’s computer.

 

iii) Server executes server-side scripts to send out a page but it does not execute client-side scripts.

The browser receives the page sent by the server and executes the client-side scripts.

 

  1. iv) Server side scripting is used to connect to the databases that reside on the web server.

Client side scripting cannot be used to connect to the databases on the web server.

 

  1. v)Server side scripting can access the file system residing at the web server.

Client side scripting can’t access the file system that resides at the web server.

 

vi)The settings that belong to Web server can be accessed using Server side scripting.

The files and settings that are local at the user’s computer can be accessed using Client side scripting.

 

vii) Server side scripting can’t be blocked by the user.

Client side scripting is possible to be blocked by the user.

viii) Response from a server-side script is slower as compared to a client-side script because the scripts are processed on the remote computer.

Response from a client-side script is faster as compared to a server-side script because the scripts are processed on the local computer.

 

  1. ix)Examples of Server side scripting languages: PHP, JSP, ASP, ASP.Net, Ruby, Perl n many more.

Examples of Client side scripting languages: JavaScript, VB script, etc.

 

  1. b) What is a web server? Differentiate between local server and remote server.

web server is a computer system that processes requests via HTTP, the basic network protocol used to distribute information on the World Wide Web. The term can refer either to the entire system, or specifically to the software that accepts and supervises the HTTP requests.

The most common use of web servers is to host websites, but there are other uses such as gaming, data storage, running enterprise applications, handling email, FTP, or other web uses.

Web servers often come as part of a larger package of Internet- and intranet-related programs for serving e-mail, downloading requests for File Transfer Protocol (FTP ) files, and building and publishing Web pages. Considerations in choosing a Web server include how well it works with the operating system and other servers, its ability to handle server-side programming, security characteristics, and publishing, search engine, and site building tools that may come with it.

Two leading Web servers are Apache , the most widely-installed Web server, and Microsoft’s Internet Information Server (IIS ). Other Web servers include Novell’s Web Server for users of its NetWare operating system and IBM’s family of Lotus Domino servers, primarily for IBM’s OS/390 and AS/400 customers.

Differences between local server and remote server:

Local server:

Local server or locally hosted solutions are commonly referred to as client server solution. In this model, a small unit has a dedicated server on a site and the application software is distributed. In a local server solution, the physical medium on which the data or application is stored exist within the local area in which it is used or accessed.

Remote server:

These solutions are commonly referred to as server hosting. We access the application and its data through the web browser using www. In such solutions, the physical medium on which the data or application are stored exist in an area remote from that in which it is used or accessed.

  1. c) What is the difference between WAMP, NAMP, and LAMP?

All these are used for php website and act as a local server. So with the help of this we can test our website first locally then upload to the server without any error and bugs.

The major difference between WAMP, LAMP, and MAMP is operating system.

LAMP is for Linux operating system
WAMP is for windows operating system
MAMP is for Mac OS X operating system.

Xampp is for X-OS, Apache, Mysql, Php, Perl. 

 

What is LAMP SERVER?

 

  1. Full form of LAMP is Linux, Apache, MySQL and PHP.
  2. This is an open source platform.
  3. LAMP Server is work on Linux Operating System only.
  4. LAMP is a combine package of  Linux, Apache, MySQL and PHP.
  5. Apache is the web server
  6. Mysql is the relational database management system.
  7. PHP is the object-oriented scripting language.

 

What is WAMP SERVER?

  1. Full form of WAMP is Windows, Apache, MySQL and PHP.
  2. This is an open source platform.
  3. WAMP Server is work on Windows Operating System only.
  4. LAMP is a combine package of  Windows, Apache, MySQL and PHP.
  5. Apache is the web server
  6. Mysql is the relational database management system.
  7. PHP is the object-oriented scripting language.

 

What is MAMP SERVER?

  1. Full form of MAMP is MAC, Apache, MySQL and PHP.
  2. This is an open source platform.
  3. MAMP Server is work on MAC Operating System only.
  4. LAMP is a combine package of MAC, Apache, MySQL and PHP.
  5. Apache is the web server
  6. Mysql is the relational database management system.
  7. PHP is the object-oriented scripting language.

 

Question 3

(a) PHP being an open source is there any support available to it? How the web server interprets  PHP and interacts with the client?

PHP or Hypertext Processor, is basically a computer language code, mail used for the web development. It can produce incredible web pages when it is incorporated with the HTML code. The web servers which have a PHP processor module with them can interpret the PHP code and then a web page document is created. Generally, it takes input data from HTML. For a various purpose the scripting code is used. It has been processed to perform the operating system operations by creating a program output on its standard channel. Also it is used to perform graphical stuffs of a website. All the modern web servers are equipped with the inbuilt PHP processor.PHP is an open source language, and it is been said that it has very less support online and offline. But, PHP is all together a different language that is being developed by group of programmers, who writes the code. There is lots of available support for PHP, which mostly comes from developers and PHP users.

After installing and configuring the PHP, the web When PHP is installed, the Web server looks for PHP code that is embedded in HTML file with its extension. The extensions which are used are .php or .phtml. When web server receives a request for the file with an appropriate extension, HTML statements are processed and PHP statements are executed on the server itself. When the processing gets over the output is being shown in HTML statements.

Being a server side scripting language PHP can be smoothly embedded with the HTML. For dynamic and interactive websites, PHP is an indispensible thing. This scrip0ting language is so vast that it can be used with the JAVA script and database such as MySQL server. The open source technology of PHP is backed with a large community support. The benefit of PHP is − it is not platform supported. It works smoothly for all the operating systems including LINUX and Windows. For the core development of PHP, a large collection of open source is available.

 

 

 

 (b) PHP and JavaScript are both programming languages that generate dynamic results for web pages. What is the main difference and why would you use both of them.

PHP (PHP Hypertext Preprocessor) is a young language when compared to the likes of Perl and C and other largely popular languages. It was started in 1995 by Rasmus Lerdorf initially as a simple set of Perl scripts he named ‘Personal Home Page Tools’, later he expanded it and implemented it in C and then released it as an open source code base for all to use (The PHP Group, 2010). It has since then evolved from a procedural language to an OO language in its PHP 5 release (July 2004).

It is strictly a server side language which means the compilation, translation and actions are performed on the host computer it is running on. Syntax is similar to C/Java but it does not have certain rules of the other programming languages (such as declaring a variable as a certain type before using it, or the need to actually declare variables before using them). PHP’s purpose is predominantly for web applications but it can be used for non-web application scripting (command line tools etc.) although, from my experience, it is not well suited for background processing as it does tend to use up far more resources than languages like Perl and Python.

JavaScript is a language that was developed by Netscape to run on Netscape browsers and despite its name, is not a subset of the Java language or developed by Sun (Crockford, 2001). It is technically not an OO language, although it does have functions and objects it does not group entities into Classes. JavaScript is a client-side language meaning that it uses the client computers resources and compiler to execute its instructions, this makes it very light on the load of a server but also puts performance in the hands of the hardware that the users are accessing the script from, which, of course due to the nature of JavaScript being for web pages, is probably the most broad spectrum one could want when programming for consumers.

Differences

  1. PHP runs on server and the major functionality of PHP is to produce the HTML code which will be read by browser while JavaScript can handle only local tasks that are specific.
  2. In PHP, code will be available only after the server interprets it while In JavaScript the code can be viewed even after the output is interpreted.
  3. PHP is embedded only with HTML and PHP cannot be combined with XML while JavaScript can be combined with HTML, XML and AJAX.
  4. PHP is used to produce web pages on the go, read and deploy databases, import the files available on the server, and gain files of data from further domains while JavaScript can import files of information available by mentioning the URL of the file in the address bar of the browser.
  5. PHP does not execute within a browser’s window while JavaScript executes within a browser’s window.
  6. PHP commonly uses MYSQL as a database while MYSQL is not commonly used by JavaScript.

(c) Write down the steps for installation of Apache, lIS and PWS in windows OS.

STEPS TO INSTALL APACHE

1.Download the Apache HTTPD Web Server from the Apache web site .

2.Save the file to Windows Desktop.

3.Double click the msi file saved on Windows Desktop.

4.Click “Next>”.

5.Click the radio button “I accept the terms in the license agreement”.

6.Click “Next>”.

7.On the next window, again click “Next>”.

8.Next, fill in all the text boxes with the following information:

“Network Domain”: localhost

“Server Name”: localhost

“Administrator’s Email Address”: your email address

9.Make sure the radio button “for all users, on port 80, as a service – recommended” is selected.

10.Click “Next>”.

11.On the next window, click the radio button “Custom”, and then click “Next>”.

12.On the next window highlight “Apache HTTP Server” and click the “change” button.

13.We are going to install all the packages and scripts in the path C: Server\Apache2\ (assuming C: is your main hard drive). So in the text box “Folder name:” type in “C:\Server\Apache2\”. The ending backslash is important.

14.After you have typed in the path, click “OK” and then click “Next>”.

15.Click “Install” to begin the installation.

16.Once the Apache installation software has finished installing all the files on your computer, you will see a final window letting you know the installation was a success. Click the “Finish” button.

 

 

Installing IIS on Windows:
Microsoft Internet Information Server (IIS) is a web server that integrates into the Windows NT Server so no need to download from any where. Following are the steps to install IIS.

  1. From Start Button, go to Settings and Control Panel.
  2. In the Control Panel, select Add/Remove Programs, in that Select Add/Remove Windows Components.
  3. In the wizard, check Internet Information Services, click Ok. After this, an Inetpub folder will be created where you can find a folder named wwwroot.

Now your installation process is over. If you want to check whether IIS is running or not, Open Internet Explorer and type http://localhost in the address bar. If everything is working fine, it will display the default page generated by IIS. If not,

  1. Go to Control panel. Open Administrative Tools and double click “Internet Information Server”.
  2. Select “Default Web Site” and Click on the Start button present in the toolbar.

Installing Personal Web Server (PWS)

Personal Web Server ships with Windows 98 CD, you can find it in add-ons folder present in the Windows 98 CD. If you are using Windows 95, you have to download “Windows NT 4.0 Option Pack” from Microsoft.
Download “Windows NT 4.0 Option Pack”
If you don’t have Windows 98 CD with you, no problem. You can download it from Microsoft’s web site for free.
Download “Personal Web Server”
Installing Personal Web Server on Windows 98:

  1. Insert your Windows 98 CD into your CD-ROM Drive.
  2. Explore your CD-ROM Drive.
  3. Open “add-ons” folder, there you will find “pws” folder, run “setup.exe” from this folder.
  4. Follow the instructions on the screen to install “Personal Web Server”

After installation of PWS, you will find a PWS icon on your desktop and most probably a small icon of PWS in the right corner of the taskbar. Open any one of them. If the PWS is running then you will see an option “Stop PWS” or else you will see “Start PWS”.
To check if PWS is running, open your Internet Explorer. In the URL box enter http://127.0.0.1 or http://localhost and press Enter. If everything is working fine, you will see a default page generated by PWS. If you can see any page then PWS is running correctly or else you have to restart your computer and start PWS again and continue the same process. Hopefully everything will be alright now.

 

Question 4

 

(a) What is PHP .Explain data types and variables in PHP. What is the difference between $msg and $$msg?

 

PHP is a language that has outgrown its name. It was originally conceived as a set of macros to help coders maintain personal home pages, and its name grew from its purpose. Since then, PHP’s capabilities have been extended, taking it beyond a set of utilities to a full-featured programming language, capable of managing huge database-driven online environments.

 

PHP is now officially known as PHP: HyperText Preprocessor. It is a server-side scripting language usually written in an HTML context. Unlike an ordinary HTML page, a PHP script is not sent directly to a client by the server; instead, it is parsed by the PHP binary or module. HTML elements in the script are left alone, but PHP code is interpreted and executed. PHP code in a script can query databases, create images, read and write files, talk to remote servers— the possibilities are endless.

 

Data Types

 

Different types of data take up different amounts of memory and may be treated differently when they are manipulated in a script. Some programming languages therefore demand that the programmer declare in advance which type of data a variable will contain. PHP4 is loosely typed, which means that it will calculate data types as data is assigned to each variable.

 

Type Example Description
Integer 5 A whole number
Double 3.2 A floating-point number
String “hello” A collection of characters
Boolean True/false One of the special values

true or false

Object
Array

 

Variables and Dynamic Variables

Variables

PHP is a very loosely typed language. This means that variables do not have to be declared before they are used, and that PHP always converts variables to the type required by their context when they are accessed.

A variable is a special container that you can define to “hold” a value. A variable consists of a name that you can choose, preceded by a dollar ($) sign. The variable name can include letters, numbers, and the underscore character (_). Variable names cannot include spaces or characters that are not alphanumeric.

 

Dynamic Variables

As you know, you create a variable with a dollar sign followed by a variable name. Unusually, the variable name can itself be stored in a variable. So, when assigning a value to a variable

$user = “ajay”;

is equivalent to

$holder=”user”;

$$holder = “ajay”;

 

The $holder variable contains the string “user”, so you can think of $$holder as a dollar sign followed by the value of $holder. You can use a string constant to define a dynamic variable instead of a variable. To do so, you must wrap the string you want to use for the variable name in braces:

${“user”} = “ajay”;

 

 

(b) What is the scope of variable .List and explain al. scope of variable and super Globals variable in PHP with example.

 

Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types:

 

  1. Local variables
  2. Global variables
  3. Static variables
  4. Function parameters

 

  1. Local variables

A variable declared within a PHP function is local and can only be accessed within that function. (the variable has local scope):

<?php

$a = 5; // global scope

function myTest()

{

echo $a; // local scope

}

myTest();

?>

The script above will not produce any output because the echo statement refers to the local scope variable $a, which has not been assigned a value within this scope.

You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared. Local variables are deleted as soon as the function is completed.

 

  1. Global variables

 

Global scope refers to any variable that is defined outside of any function. Global variables can be accessed from any part of the script that is not inside a function. To access a global variable from within a function, use the global keyword:

<?php

$a = 5;

$b = 10;

function myTest()

{

global $a, $b;

$b = $a + $b;

}

myTest();

echo $b;

?>

The script above will output 15.

 

PHP also stores all global variables in an array called $GLOBALS[index]. Its index is the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.

The example above can be rewritten as this:

<?php

$a = 5;

$b = 10;

function myTest()

{

$GLOBALS[‘b’] = $GLOBALS[‘a’] + $GLOBALS[‘b’];

}

myTest();

echo $b;

?>

 

  1. Static variables

 

When a function is completed, all of its variables are normally deleted. However, sometimes you want a local variable to not be deleted. To do this, use the static keyword when you first declare the variable:

 

static $rememberMe;

 

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

 

  1. Function parameters

 

A parameter is a local variable whose value is passed to the function by the calling code. Parameters are declared in a parameter list as part of the function declaration:

function myTest($para1,$para2,…)

{

// function code

}

Parameters are also called arguments.

 

(c) Define constants in PHP with example. What are implicit casting and explicit casting in PHP?

 

Constants

Constants are similar to variables, holding information to be accessed later, except that they are what they sound like—constant. In other words, once you have defined one, its value is set for the remainder of the program and cannot be altered. One example of a use for a constant might be to hold the location of your server root (the folder with the main files of your website). You would define such a constant like this:

define(“ROOT_LOCATION”, “/usr/local/www/”);

Then, to read the contents of the variable you just refer to it like a regular variable (but it isn’t preceded by a dollar sign):

$directory = ROOT_LOCATION;

 

Implicit and Explicit Casting

PHP is a loosely typed language that allows you to declare a variable and its type simply by using it. It also automatically converts values from one type to another whenever required. This is called implicit casting.

However, there may be times when PHP’s implicit casting is not what you want. There are various ways in which this could be achieved. One way is to force the variable to be cast to an integer value using the integer cast type (int), like this:

$c = (int) ($a / $b);

This is called explicit casting. Note that in order to ensure that the value of the entire expression is cast to an integer, the expression is placed within parentheses. Otherwise, only the variable $a would have been cast to an integer—a pointless exercise, as the division by $b would still have returned a floating-point number.

 

PHP Cast Types

Cast type Description
(int) (integer) Cast to an integer by dropping the decimal portion
(bool) (boolean) Cast to a Boolean
(float) (double) (real) Cast to a floating-point number
(string) Cast to a string
(array) Cast to an array
(object) Cast to an object

 

 

Question 5

(a) Differentiate numeric and associative array with example. Write a PHP script to create a multidimensional array.

 

An array is a special variable, which can hold more than one value at a time.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

  • Indexed 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.

 

PHP Indexed Arrays

These arrays can store numbers, strings and any object but their index will be prepresented 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.

<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”;
$numbers[2] = “three”;
$numbers[3] = “four”;
$numbers[4] = “five”;

foreach( $numbers as $value )
{
echo “Value is $value <br />”;
}
?>
</body>
</html>

 

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(
“ajay” => 2000,
“amit” => 1000,
“neha” => 500
);

echo “Salary of ajay is “. $salaries[ajay] . “<br />”;
echo “Salary of amit is “.  $salaries[amit]. “<br />”;
echo “Salary of neha is “.  $salaries[neha]. “<br />”;

?>
</body>
</html>

 

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(
“ajay” => array
(
“physics” => 35,
“maths” => 30,
“chemistry” => 39
),
“amit” => array
(
“physics” => 30,
“maths” => 32,
“chemistry” => 29
),
“neha” => array
(
“physics” => 31,
“maths” => 22,
“chemistry” => 39
)
);
/* Accessing multi-dimensional array values */
echo “Marks for ajay in physics : ” ;
echo $marks[ajay][‘physics’] . “<br />”;
echo “Marks for amit in maths : “;
echo $marks[amit][‘maths’] . “<br />”;
echo “Marks for neha in chemistry : ” ;
echo $marks[neha][‘chemistry’] . “<br />”;
?>
</body>
</html>

 

 

(b) What is foreach and each in PHP? Write a PHP program for passing by value and passing by reference?

 

Foreach Loop

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)    statementforeach (array_expression as $key => $value)    statement

The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you’ll be looking at the next element).

The second form will additionally assign the current element’s key to the $key variable on each iteration.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}

?>

 

each function

 

The each() function is used to fetch the key and value of the current element. The function also moves the internal array pointer forward.

 

This element key and value is returned in an array with four elements. Two elements (1 and Value) for the element value, and two elements (0 and Key) for the element key.

Related methods:

  • current() – returns the value of the current element in an array
  • end() – moves the internal pointer to, and outputs, the last element in the array
  • next() – moves the internal pointer to, and outputs, the next element in the array
  • prev() – moves the internal pointer to, and outputs, the previous element in the array
  • reset() – moves the internal pointer to the first element of the array

 

Passing Arguments by Reference:

It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable’s value.

Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.

<html><head><title>Passing Argument by Reference</title></head><body><?phpfunction addFive($num){   $num += 5;} function addSix(&$num){   $num += 6;}$orignum = 10;addFive( &$orignum );echo “Original Value is $orignum<br />”;addSix( $orignum );echo “Original Value is $orignum<br />”;?></body>

</html>

 

(c) Explain following array function with the help of example

  1. assort() 2. Exploder() 3. compact () 4. reset () 5. Is_array()

is_array()

Arrays and variables share the same namespace. This means that you cannot have a string variable called $fred and an array also called $fred. If you’re in doubt and your code needs to check whether a variable is an array, you can use the is_array function like this:

 

echo (is_array($fred)) ? “Is an array” : “Is not an array”;

Note that if $fred has not yet been assigned a value, an “Undefined variable” message will be generated.

shuffle()

There may be times when you need the elements of an array to be put in random order, such as when creating a game of playing cards:

 

shuffle($cards);

 

Like sort, shuffle acts directly on the supplied array and returns TRUE on success or FALSE on error.

 

explode()

This is a very useful function with which you can take a string containing several items separated by a single character (or string of characters) and then place each of these items into an array

 

<?php

$temp = explode(‘ ‘, “This is a sentence with seven words”);

print_r($temp);

?>

This example prints out the following (on a single line when viewed in a browser):

Array

(

[0] => This

[1] => is

[2] => a

[3] => sentence

[4] => with

[5] => seven

[6] => words

)

extract()

Sometimes it can be convenient to turn the key/value pairs from an array into PHP variables. One such time might be when processing the $_GET or $_POST variables as sent to a PHP script by a form.

When a form is submitted over the Web, the web server unpacks the variables into a global array for the PHP script. If the variables were sent using the GET method, they will be placed in an associative array called $_GET, and if they were sent using POST, they will be placed in an associative array called $_POST.

sometimes you just want to store the values sent into variables for later use. In this case, you can have PHP do the job automatically for you:

 

extract($_GET);

compact()

There are also times when you want to use compact, the inverse of extract, to create an array from variables and their values.

 

<?php

$fname = “Elizabeth”;

$sname = “Windsor”;

$address = “Buckingham Palace”;

$city = “London”;

$country = “United Kingdom”;

$contact = compact(‘fname’, ‘sname’, ‘address’, ‘city’, ‘country’);

print_r($contact);

?>

reset()

When the foreach…as construct or the each function walk through an array, they keep an internal PHP pointer that makes a note of which element of the array they should return next. If your code ever needs to return to the start of an array, you can issue reset, which also returns the value of that element.

 

reset($fred); // Throw away return value

$item = reset($fred); // Keep first element of the array in $item

end()

As with reset, you can move PHP’s internal array pointer to the final element in an array using the end function, which also returns the value of the element, and can be used as in these examples:

 

end($fred);

$item = end($fred);

assort() :
This function sorts an array such that array indices
maintain their correlation with the array elements they are
associated with. This is used mainly when sorting
associative arrays where the actual element order is
significant.

<?php
$fruits = array(“d” => “lemon”, “a” => “orange”, “b” =>
“banana”, “c” => “apple”);
asort($fruits);
foreach ($fruits as $key => $val) {
echo “$key = $val\n”;
}
?>

BCA PHP Question Paper Solved

 

Question 6

Q6 (a) Write a PHP code to design a registration form according to given field :name, E-mail, Phone number and comnient, and apply form validation on name, email and phone number, also make  buttons to send the data

 

Registeration Form

 

<html><head><title>Validation Form</title></head><body><form id=”contact_form” method=”post” action=”.”> <br />Label <input type=”text” name=”name” class=”textfield” value=”” /> <br />Email <input type=”text” name=”email” class=”textfield” value=”” /> <br />Phone Number <input type=”text” name=”number” class=”textfield” value=”” /> <br /><p><input type=”submit” name=”submit” class=”button” value=”Submit” /></p></form></body></html>

Following php code send the data to server for validation

 

<?php if(isset($_POST[‘submit’])) {//include validation class//assign post data to variables$name = trim($_POST[‘name’]); // Storing username$email = trim($_POST[’email’]); // Storing email address$number= trim($_POST[‘number’]); // storing the phone number}?>

To check if any field is left blank, we use the empty function and pass it the arguments.

if(empty($name) && empty($number) && empty($email)){echo “All fields are compulsory”}

The following code check for inappropriate characters. The following code is an example of this type of validation:

if (preg_match(“/^[a-z0-9_]+$/i”, $name) ){return true;} else{echo “Enter valid username”}

 

Validating email: The email field is validated for two things. First, it should not be blank and the entered email must be valid.

<?php$reg = ‘/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/’;if (preg_match($reg, $email)) {echo $email . \” Email Id is accepted.\”;} else {echo $email . \”Invalid Email ID.\”;}?>

Phone number validation:

if((preg_match(“/[^0-9]/”, ”, $str)) && strlen($str) == 10){echo “Invalid phone number}

 

Q6. (b) What are cookies? How can you create, access and delete a cookie in PHP with the help of example.

Ans(b) Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies. It can contain almost any alphanumeric information (as long as it’ under 4KB) and can be retrieved from our computer and returned to the server. Common uses include session tracking, maintaining data across multiple visits, holding shopping cart contents, storing login details , and more.

Due to the way the Internet works, multiple elements on a web page can be embedded from multiple domains, each of which can issue its own cookies. These are referred to as third-party cookies.  Most commonly, they are created by advertising companes in order to track users acrss multiple websites.

Cookies are exchanged during the transfer of headers, before the actual HTML of a web page is sent, and it is impossible to send a cookie once any HTML has been transferred. Therefore, careful planning of cookie usage is important. Following steps shows a browser receiving two pages:

  1. The browser issues a request to retrieve the main page, html, at the website http://www.webserver.com. The firs header specifies the field and the second header specifies the server.
  2. When the web server at com receives this pair of headers, it returns some of its own. The second header defines the type of content to be sent (text/html) and the third one sends a cookie with the name name and the value value. Only then are the contents of the web page transferred.
  3. Once the browser has received the cookie, it will then return it with every future request made to the issuing server until the cookie expires or is deleted. So, when the browser requests the new page /html, it also returns the cookie name with value value.
  4. Because the cookie has already been set , when the server receives the request to send /html, it does not have to resend the cookie, but just returns the requested page.
  • Setting a Cookie

PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately. Following is the syntax for setting a cookie :

setcookie(name, value, expire, path, domain, security);

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.

Following example will create two cookies name and age these cookies will be expired after one hour.

<? PHP

setcookie (“name”, “John Watkin”, time()+3600, “/”,””, 0);

setcookie (“age”, “36”, time()+3600, “/”, “”,  0);

?>

< html >

< head >

<title>Setting Cookies with PHP</title>

</head>

<body>

<? PHP echo “Set Cookies”?>

</body>

</html>

 

 

 

  • Accessing a Cookie

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><?phpecho $_COOKIE[“name”]. “<br />”;/* is equivalent to */echo $HTTP_COOKIE_VARS[“name”]. “<br />”; echo $_COOKIE[“age”] . “<br />”;/* is equivalent to */echo $HTTP_COOKIE_VARS[“name”] . “<br />”;?></body></html>

You can use isset() function to check if a cookie is set or not.

<html><head><title>Accessing Cookies with PHP</title></head><body><?php  if( isset($_COOKIE[“name”]))    echo “Welcome ” . $_COOKIE[“name”] . “<br />”;  else    echo “Sorry… Not recognized” . “<br />”;?></body></html>

  • Deleting a Cookie

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 echo “Deleted Cookies” ?></body></html>

 

Question 7

(a) Write a PHP script to open, close, read and write into a file.

 

 

Before you can work with a file, you must first open it for reading, writing, or both. PHP provides the fopen() function for this. fopen() requires a string containing the file path, followed by a string containing the mode in which the file is to be opened. The most common modes are read (‘r’), write (‘w’), and append (‘a’). fopen() returns an integer This integer is known as a file pointer and should be assigned to a variable. To open a file for reading, you would use the following:

$fp = fopen( “test.txt”, ‘r’ );

<html>

<body>

<?php

$filename = “test.txt”;

$fp = fopen( $filename, “r” ) or die(“Couldn’t open $filename”);

while ( ! feof( $fp ) )

{

$line = fgets( $fp, 1024 );

print “$line<br>”;

 

$fp = fopen( $filename, “w” ) or die(“Couldn’t open $filename”);

fwrite( $fp, “Hello world\n” );

fclose( $fp );

 

}

?></body></html>

 

 

(bWhat is File Handling in PHP? Write a PHP script to upload a file

 

File handling is an important part of any web application. You often need to open and process a file for different tasks. PHP has several functions for creating, reading, uploading, and editing files.

 

At the time you are controlling files you must be extremely watchful on the grounds that you can do a considerable measure of harm if something happens.

Regular errors include, editing the wrong file, filling a hard-drive with garbage data, and incidentally erasing a file’s content.

Normal errors include, editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file’s content.

Creating and Deleting Files

If a file does not yet exist, you can create one with the touch() function. Given a string representing a file path, touch() attempts to create an empty file of that name. If the file already exists, the contents are not disturbed, but the modification date is updated to the time at which the function executed.

touch(“myfile.txt”);

You can remove an existing file with the unlink() function. Once again, unlink() accepts a file path:

unlink(“myfile.txt”);

Opening a File for Writing, Reading, or Appending

Before you can work with a file, you must first open it for reading, writing, or both. PHP provides the fopen() function for this. fopen() requires a string containing the file path, followed by a string containing the mode in which the file is to be opened. The most common modes are read (‘r’), write (‘w’), and append (‘a’). fopen() returns an integer This integer is known as a file pointer and should be assigned to a variable. To open a file for reading, you would use the following:

$fp = fopen( “test.txt”, ‘r’ );

Reading from Files

PHP provides a number of functions for reading data from files. These enable you to read by the byte, the line, or even the character.

 

Reading Lines from a File with fgets() and feof()

After you have opened a file for reading, you will often need to access it line by line. To read a line from an open file, you can use fgets(), which requires the file pointer returned from fopen() as an argument. You must also pass it an integer as a second argument. This specifies the number of bytes the function should read if it doesn’t first encounter a line end or the end of the file. The fgets() function reads the file until it reaches a newline character (“\n”), the number of bytes specified in the length argument, or the end of the file.

 

$line = fgets( $fp, 1024 ); // where $fp is the file pointer returned by fopen()

Although you can read lines with fgets(), you need some way of telling when you have reached the end of the file. The feof() function does this, returning true when the end of the file has been reached and false otherwise. Once again this function requires a file pointer as its argument:

feof( $fp ); // where $fp is the file pointer returned by fopen()

Writing or Appending to a File

The processes for writing to or appending to a file are the same. The difference lies in the fopen() call. When you write to a file, you should use the mode argument “w” when you call fopen():

$fp = fopen( “test.txt”, “w” );

All subsequent writing will occur from the start of the file. If the file doesn’t already exist, it will be created. If the file already exists, any prior content will be destroyed and replaced by the data you write.

When you append to a file, you should use mode “a” in your fopen() call:

$fp = fopen( “test.txt”, “a” );

Any subsequent writes to your file are added to the existing content.

Writing to a File with fwrite() or fputs()

fwrite() accepts a file pointer and a string. It then writes the string to the file. fputs() works in exactly the same way.

fwrite( $fp, “hello world” );

fputs( $fp, “hello world” );

 

·         Copying Files PHP copy() is used to create a clone of myfile.txt. Type in below example and save it as copyfile.php, then call up the program in our browser.    e.g.       <?php // copyfile.php          copy(‘myfile.txt’,’myfile2.txt’) or die(“Could not copy file”);          echo ”File successfully copied to ‘myfile.txt’ ”;             ?>

 

·         Moving a File        To move file, rename it with the rename(), as in example shown below:              e.g.-            <?php // movefile.php                 if(!rename(‘myfile.txt’ , ‘myfile2.new’))                       echo “Could not rename file ”;                 else                       echo “File successfully renamed to ‘myfile2.new’ ”;              ?>

 

 

Program to upload a file and display the contents in server.

<html>
<body>

<form action=”” method=”post”
enctype=”multipart/form-data”>
<label for=”file”>Filename:</label>
<input type=”file” name=”file” id=”file” />
<br />
<input type=”submit” name=”submit_upload” value=”Submit” />
</form>

</body>
</html>

<?php
if(isset($_REQUEST[‘submit_upload’]))
{

move_uploaded_file($_FILES[“file”][“tmp_name”],”upload/” . $_FILES[“file”][“name”]);
echo “uploaded”;
}
?>

 

(c) What is HTTP application state?

Application state is used to store data on the application machine. It works as a global variable in other programming languages. Application variable is an object that is shared by the multiple sessions. We can use application variable within page, HttpHandler and Global.asax.

When request a page from client machine, an instance will create at application machine by the help of HttpApplicationState class. Entire application will have only one instance which is provided by HttpContext property named Application.

Question 8

What is MYSQL? What are the different data types in MYSQL? Explain each of them with suitable example.

MySQL, the most popular Open Source SQL database management system, is developed, distributed, and supported by Oracle Corporation.

MySQL is a database management system.

A database is a structured collection of data. It may be anything from a simple shopping list to a picture gallery or the vast amounts of information in a corporate network. To add, access, and process data stored in a computer database, you need a database management system such as MySQL Server. Since computers are very good at handling large amounts of data, database management systems play a central role in computing, as standalone utilities, or as parts of other applications.

MySQL software is Open Source.

Open Source means that it is possible for anyone to use and modify the software. Anybody can download the MySQL software from the Internet and use it without paying anything. If you wish, you may study the source code and change it to suit your needs.

The MySQL Database Server is very fast, reliable, scalable, and easy to use.

If that is what you are looking for, you should give it a try. MySQL Server can run comfortably on a desktop or laptop, alongside your other applications, web servers, and so on, requiring little or no attention. If you dedicate an entire machine to MySQL, you can adjust the settings to take advantage of all the memory, CPU power, and I/O capacity available. MySQL can also scale up to clusters of machines, networked together.

Data Types in MYSQL

MySQL uses many different data types broken into three categories: numeric, date and time, and string types.

Numeric Data Types:

MySQL uses all the standard ANSI SQL numeric data types, so if you’re coming to MySQL from a different database system, these definitions will look familiar to you. The following list shows the common numeric data types and their descriptions:

  • INT– A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from -2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295. You can specify a width of up to 11 digits.
  • TINYINT– A very small integer that can be signed or unsigned. If signed, the allowable range is from -128 to 127. If unsigned, the allowable range is from 0 to 255. You can specify a width of up to 4 digits.
  • SMALLINT– A small integer that can be signed or unsigned. If signed, the allowable range is from -32768 to 32767. If unsigned, the allowable range is from 0 to 65535. You can specify a width of up to 5 digits.
  • MEDIUMINT– A medium-sized integer that can be signed or unsigned. If signed, the allowable range is from -8388608 to 8388607. If unsigned, the allowable range is from 0 to 16777215. You can specify a width of up to 9 digits.
  • BIGINT– A large integer that can be signed or unsigned. If signed, the allowable range is from -9223372036854775808 to 9223372036854775807. If unsigned, the allowable range is from 0 to 18446744073709551615. You can specify a width of up to 20 digits.
  • FLOAT(M,D)– A floating-point number that cannot be unsigned. You can define the display length (M) and the number of decimals (D). This is not required and will default to 10,2, where 2 is the number of decimals and 10 is the total number of digits (including decimals). Decimal precision can go to 24 places for a FLOAT.
  • DOUBLE(M,D)– A double precision floating-point number that cannot be unsigned. You can define the display length (M) and the number of decimals (D). This is not required and will default to 16,4, where 4 is the number of decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a synonym for DOUBLE.
  • DECIMAL(M,D)– An unpacked floating-point number that cannot be unsigned. In unpacked decimals, each decimal corresponds to one byte. Defining the display length (M) and the number of decimals (D) is required. NUMERIC is a synonym for DECIMAL.

Date and Time Types:

The MySQL date and time datatypes are:

  • DATE– A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December 30th, 1973 would be stored as 1973-12-30.
  • DATETIME– A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00.
  • TIMESTAMP– A timestamp between midnight, January 1, 1970 and sometime in 2037. This looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ).
  • TIME– Stores the time in HH:MM:SS format.
  • YEAR(M)– Stores a year in 2-digit or 4-digit format. If the length is specified as 2 (for example YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). If the length is specified as 4, YEAR can be 1901 to 2155. The default length is 4.

String Types:

Although numeric and date types are fun, most data you’ll store will be in string format. This list describes the common string datatypes in MySQL.

  • CHAR(M)– A fixed-length string between 1 and 255 characters in length (for example CHAR(5)), right-padded with spaces to the specified length when stored. Defining a length is not required, but the default is 1.
  • VARCHAR(M)– A variable-length string between 1 and 255 characters in length; for example VARCHAR(25). You must define a length when creating a VARCHAR field.
  • BLOB or TEXT– A field with a maximum length of 65535 characters. BLOBs are “Binary Large Objects” and are used to store large amounts of binary data, such as images or other types of files. Fields defined as TEXT also hold large amounts of data; the difference between the two is that sorts and comparisons on stored data are case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not specify a length with BLOB or TEXT.
  • TINYBLOB or TINYTEXT– A BLOB or TEXT column with a maximum length of 255 characters. You do not specify a length with TINYBLOB or TINYTEXT.
  • MEDIUMBLOB or MEDIUMTEXT– A BLOB or TEXT column with a maximum length of 16777215 characters. You do not specify a length with MEDIUMBLOB or MEDIUMTEXT.
  • LONGBLOB or LONGTEXT– A BLOB or TEXT column with a maximum length of 4294967295 characters. You do not specify a length with LONGBLOB or LONGTEXT.
  • ENUM– An enumeration, which is a fancy term for list. When defining an ENUM, you are creating a list of items from which the value must be selected (or it can be NULL). For example, if you wanted your field to contain “A” or “B” or “C”, you would define your ENUM as ENUM (‘A’, ‘B’, ‘C’) and only those values (or NULL) could ever populate that field.

 

 

(b) Write connectivity and selecting database statement which is used to connect PHP with MYSQL.

 

Connecting to the Database Server

Before you can begin working with your database, you must first connect to the server. PHP provides the mysql_connect() function to do just this. mysql_connect() does not require any arguments but accepts up to three strings: the hostname, a usename, and a password. If you omit any or all of these arguments, the function assumes localhost as the host and that no password or username has been set up in the mysqluser table, unless defaults have been set up in the php.ini file. mysql_connect() returns a link identifier if the connection is successful. You can store this return value in a variable so that you can continue to work with the database server.

 

The following code fragment uses mysql_connect() to connect to the MySQL database server:

$link = mysql_connect( “localhost”, “root”, “n1ckel” );

if ( ! $link )

die( “Couldn’t connect to MySQL” );

 

Selecting a Database

Now that we have established a connection to the MySQL daemon, we must choose which database we want to work with. You can select a database with the mysql_select_db() function. mysql_select_db() requires a database name and optionally accepts a link identifier. If you omit this, the identifier returned from the last connection to the server will be assumed. mysql_select_db() returns true if the database exists and you are able to access it.

 

mysql_select_db( $sample ) or die ( “Couldn’t open $sample );

 

(c ) In how many ways we can retrieve the data in the result set of MySQL using PHP? What is the difference between mysqI_fetch_object and mysqljetch_array?

 

we can retrieve the data in the result set of MySQL using PHP in 4 Ways

  • mysql_fetch_row >> Get a result row as an enumerated array
  1. mysql_fetch_array >> Fetch a result row as associative and numeric array 3.mysql_fetch_object >> Returns the current row of a result set as an object
  2. mysql_fetch_assoc >> Fetch a result row as an associative array mysqli_fetch_object() is similar to mysqli_fetch_array(), with one difference – an object is returned, instead of an array.

 

BCA 5th Sem PHP Solutions

Question 9

  • Write a PHP script to create a database Course and create a student table with in the database with field. student_id, student_name, student_age. Insert maximum two records and select all records of student table.
<html>

<body>

<?php

$user = "root";

$pass = "";

$db = "Course";

$link = mysql_connect( "localhost", $user, $pass );

if ( ! $link )

die( "Couldn't connect to MySQL" );



mysql_select_db( $db, $link )

or die ( "Couldn't open $db: ".mysql_error() );

$query = "INSERT INTO student ( student_id,student_name,student_age ) values( 100, 'Amit',22)";



mysql_query( $query, $link )

or die ( "Couldn't add data to \"domains\" table: " .mysql_error() );

mysql_close( $link );

?>

</body>

</html>

Program to select all records

<html>

<body>

<?php

$user = "root";

$pass = "";

$db = "Course";

$link = mysql_connect( "localhost", $user, $pass );

if ( ! $link )

die( "Couldn't connect to MySQL" );

mysql_select_db( $db, $link )

or die ( "Couldn't open $db: ".mysql_error() );

$result = mysql_query( "SELECT * FROM student" );

$num_rows = mysql_num_rows( $result );

print "There are currently $num_rows rows in the table<P>";

mysql_close( $link );

?>

</body>

</html>

Question 9 (b)

Display records in a tabular fashion

<html>

<body>

<table width="100%" border="1" cellspacing="0" cellpadding="0">

<tr>

<td height="44" colspan="3>STUDENT Details </td>

</tr>

<tr>

<td width="7%">Enrolment Number </td>

<td width="10%">Name</td>

<td width="9%">Contact</td>

</tr>

<?php

$con = mysql_connect("localhost","root","");

if (!$con)

{

die('Could not connect: ' . mysql_error());

}

mysql_select_db("student", $con);

$result=mysql_query("select * from studetails");

while($row = mysql_fetch_array($result))

{

?>

<tr>

<td><?php echo $row['Enrollment_number'] ; ?></td>

<td><?php echo $row['Name'] ; ?></td>

<td><?php echo $row['Contact_number'] ; ?></td>

</tr>

<?php

}

mysql_close($con); ?>

</table></body></html>

 

If you want to Download .docx word File – click here

I Hope this will help you to score well in 5th Semesters PHP End Term Exams. Please do share this article if you want to appreciate the hard work Programmingy is doing for you all. I will post PHP 2014 Solved Paper very soon. Take Care, Keep coding.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here