Web Programming – II (PHP) | Short Question Answer

    • What is PHP?

    PHP stands for Hypertext Pre-processor. PHP is a server side scripting language and  scripts are executed on server that is used to develop Static websites or Dynamic websites or Web applications.

    Syntax:

    <?php
    // PHP code goes here
    ?>
  • List out the advantage of using PHP
    • PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
    • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
    • PHP supports a wide range of databases
    • PHP is free. Download it from the official PHP resource: php.net
    • PHP is easy to learn and runs efficiently on the server side
  • What is use of identical operator(===)

→ The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is “=”. It means that the left operand gets set to the value of the assignment expression on the right.

  • Write syntax of foreach loop

forEach(function(element) {

……………..

});

  • How a function is declared using default values for its arguments

→ Function arguments Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right. PHP supports passing arguments by value (the default), passing by reference, and default argument values.

  • “validations should be performed on both the client and server side”. Why

→ validations should be performed on client side in order to validate data and validations should be performed on server side in order to check user

  • Define server variable HTTP_USER_AGENT with an example

→ The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

  • What are the advantage of using PEAR over PHP built in functions to work with the database

→ The advantage of using PEAR over PHP built in functions to work with the database is it can be used in any database

  • How to display the current date in web page using PHP statement

→ the current date can be display using date function in web page using PHP statement

  • What is use of mysql_fetch_assoc() function

→ The mysql_fetch_assoc() used to retrieve a row of data as an associative array from a MySQL result handle. … Refers to the resource return by a valid mysql query (calling by mysql_query() function). … An array containing one row of data, or FALSE if there are no more rows

  • What are the different ways of writing comments in PHP

// and /* are the different ways of writing comments in PHP

  • Write the function to convert given array to string. Give examples

→ mysql_fetch_array() is the function to convert given array to string

  • How do you connect to database server? Write example
<?php

$con=mysql_connect("localhost","root","");or die("Cannot Connect to server");’

?>

 

  • What are the difference between include() and require() function

→ 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.

  • What is the use of intval() function

→ One thing to note about the difference between (int) and intval() : intval() treats variables which are already int s and float s as needing no conversion, regardless of the base argument (as of PHP 5.3.5 at least). … The common rules of integer casting apply

  • How to display the current date in web page

→ the current date can be display using date function in web page using PHP statement

  • What is the use of foef() function

→ The feof() function checks if the “end-of-file” (EOF) has been reached.

  • Write two difference between HTTP GET and 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.

  1. Write the advantage of writing function in program

→ A function in a program is important because of following reasons:

  1. Code reusability
  2. Manageability
  3. Reduced redundancy in programming
  4. Logical clarity
  5. Easy to divide the task among programmer

 

  • What is web server? Give example

→ A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers’ HTTP clients. Dedicated computers and appliances may be referred to as Web servers as well

 

  • What is web server

→ A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers’ HTTP clients. Dedicated computers and appliances may be referred to as Web servers as well

  • What is client side validation

→ Validations can be performed on the server side or on the client side ( web browser). The user input validation take place on the Server Side during a post back session is called Server Side Validation and the user input validation take place on the Client Side (web browser) is called Client Side Validation.

  • Write rules for creating function in php

→ Any valid PHP code may appear inside a function, even other functions and class definitions. Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

  • What is the use of foreach in php

→ PHP 5.5 added the ability to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value. // $a contains the first element of the nested array, // and $b contains the second element.

  • Give a condition when variable declared will be a local scope

→ When we need the variable within then function then we will declared a local scope

  • What is the use of strpost() function

→ The strpos() function finds the position of the first occurrence of a string inside another string. … stripos() – Finds the position of the first occurrence of a string inside another string (case-insensitive)

  • What do you understand by file permission

→ Most file systems have methods to assign permissions or access rights to specific users and groups of users. These systems control the ability of the users to view, change, navigate, and execute the contents of the file system.

  • What does mysqli_fetch_array() does

→ Fetch a result row as an associative array, a numeric array, or both. Warning. … Instead, the MySQLi or PDO_MySQL extension should be used.

  • What is web server

→ A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers’ HTTP clients. Dedicated computers and appliances may be referred to as Web servers as well

  • Differentiate between require() and require_one()

→ require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example.

  • What is server side validation

→ Validations can be performed on the server side or on the client side ( web browser). The user input validation take place on the Server Side during a post back session is called Server Side Validation and the user input validation take place on the Client Side (web browser) is called Client Side Validation.

  • How can we display time in php

→ the current time can be display using date function in web page using PHP statement

  • Give a condition when a variable has a Global scope

→ If we need the same variables within whole program then a variable has a Global scope

  • Where will be the file pointer placed in w and w+ mode

→ Both of them will create the file if it doesn’t exist. Then it will clear it out if it has information in it. … Then it will clear it out if it has information in it. w works for writing, w+ will work for reading a… … ‘w’ Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length

  • What is the use of file_get_contain()

→ The file_get_contents() reads a file into a string

  • What is header()

→ Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called.

  • What does mysqli_field_count() does

→ mysqli_field_count() return column of table

  • What are the different ways of writing comments in PHP

// and /* are the different ways of writing comments in PHP

  • Write the function to convert given array to string. Give examples

→ mysqli_fetch_array() convert given array to string

  • What is dynamic web page? How it is differ to static

→ The web page which can be modify without reaching source code is called dynamic web page. But in static web page we have to reach to source code for that

  • What are the differences between require() and require_one() function

→ require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example.

  • What is the use of intval() function

→One thing to note about the difference between (int) and intval() : intval() treats variables which are already int s and float s as needing no conversion, regardless of the base argument (as of PHP 5.3.5 at least). … The common rules of integer casting apply

  • How to display the current date in web page

→ the current date can be display using date function in web page using PHP statement

  • What is the use of feof() function

→ The feof() function checks if the “end-of-file” (EOF) has been reached.

  • Write two differences between HTTP GET and 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.

  • Write the advantages of writing function in program

→ A function in a program is important because of following reasons:

  1. Code reusability
  2. Manageability
  3. Reduced redundancy in programming
  4. Logical clarity
  5. Easy to divide the task among programmer

 

  • What is web server? Give example

→A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers’ HTTP clients. Dedicated computers and appliances may be referred to as Web servers as well

 

  • Why comments are important in program

→ Comment are important in program in order to increase reliability

  • Write the function to convert given string to array. Give examples

→ mysqli_fetch_array() help to convert given string to array

  • What is required technology to make web page dynamic

→ Database and JQuarries are required technology to make web page dynamic

  • What is the use of include_once() function

→ he problem is that is_int() thinks a string of numbers is a string, not an integer. … Note: This function require a string to be useful, so for example passing in an integer will always return FALSE

  • What is_numeric() function does

→ The problem is that is_int() thinks a string of numbers is a string, not an integer. … Note: This function require a string to be useful, so for example passing in an integer will always return FALSE

  • How to take user define date from user in php

→ the user define date from user can be display using date function in web page using PHP statement

  • What is the use of fwrite() function? Give example

→ The use of fwrite() function is to write in file

  • Write the advantage of array in a program

→ the advantage of array in a program is to reduce complexity and number of variables

  • What is web client? Give example

→ The client, or user, side of the Web. It typically refers to the Web browser in the user’s machine. It may also refer to plug-ins and helper applications that enhance the browser to support special services from the site.

  1. Write some words about php?

PHP: Hypertext preprocessor is a widely used open source general purpose scripting language that is especially suited for web development and can be embedded into HTML.

 

  1. How can you differentiate static and dynamic website?
Static Website Dynamic Website
Content is fixed and each page is coded in plain HTML and CSS. Content is dynamic which changes according to user’s preferences.
Display the same design and content to every user who visits the website. Offers a unique mix of dynamic contents, multimedia elements and interaction features.
More control and flexibility as each page design is unique. User has complete control over updating the design and changing the content.

 

  1. What is the uses of foreach in php?

The foreach loop is mainly used for looping through the values of an array. It loops over the array and each value for the content array element is assigned to $value and the array pointer is advanced by one to go the next element is the array.

Syntax:

<?php

foreach (array as $value)

{

//statement

}

?>

 

 

  1. What is the uses of strops() function.

The strops() function finds the position of the first occurrence of a string inside another string.

Example:

<?php

echo strpos(“Welcome to Study Notes Nepal ! Study Notes Nepal helps for BIM Students .” , “BIM”);

?>

 

 

  1. What does mysqli_fetch_array() does?

This function is used to fetch the mysql result into a numeric array one row at a time. It returns a numeric array if the data found otherwise it returns null.

Syntax:

<?php

mysql_fetch_array($sql_result);

?>

 

  1. Differentiate between include(), include_once(), require() and require_once() ?

The include() statement includes and evaluates a specified line ie. It will include a file based in the given path.

The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE.

Require() does the same thing except upon failure it will generate a fatal error and halt the script whereas include() will just give a warning and allow script to continue.

Require_once() will check if the file already has been included and if so it will not include the file again.

Web Programming – II (PHP) | Short Question Answer

  1. Define cookie in php.

A cookie is often used to identify a user. A cookie is small file that the server embeds on the user’s computer requests a page with the browser, it will send the cookie.

Example:

<?php

setcookie(‘user’,’admin’,time()+60*60*24)

echo $_COOKIEE[‘user’];

?>

 

  1. Give the condition when the variable has local scope.

A variable declared inside a function has a local scope. This variable is unique to this function and can only be accessed within the function.

Example:

<?php

function Hello(){

$txt=”Welcome to Study Notes Nepal”;

echo $txt;

}

Hello();

?>

 

 

  1. Write statement to connect mysql from PDO in php.

<?php

/*syntax:

new PDO(“host; database”, username, password);

Example:

*/

$con=

new PDO(“mysql:host=localhost;dbname=Study_Notes_Nepal”,”root”,” “);

?>

In the above example we assume the Study_Notes_Nepal is our database name.

 

  1. What do you know about the die() function in php?

The die() function is an inbuilt function in php used to print message and exit from the current php script.

Example:

<?php
$site=”https://www.studynotesnepal.com/”;
fopen($site,”r”)
or die (“Unable to connect to $site”);
?>

 

 

Group B

Web

 Exercise Problems:

  1. Make the following html table using PHP. Store values in multi-dimensional associative array.
S_id Name Address Phone
1 Ram Paknajol 422813
2 Shyam Ason 435012
3 Hari Balaju 456921

 

<?php

$item=array(

array('1','Ram','Paknajol','422813'),

array('2','Shyam','Ason','435012'),

array('3','Hari','Balaju','456921')

);

?>

<table align="center" cellspacing="0" cellpadding="10" border="1">

<tr>

<th>S_id</th>

<th>Name</th>

<th>Address</th>

<th>Phone</th>

</tr>

<?php

for($row=0; $row<3; $row++)

{

echo"<tr>";

for ($col=0; $col<4; $col++)

{

echo"<td>". $item[$row][$col]."</td>";

}

echo"</tr>";

}

?>

</table>

 

 

  1. Write the function? List the types of function. Write an example of dynamic function call.

Functions are important tools in any programming language which is define block of statement that perform particular job in a program. Function is a logical unit composed of number of statements group in a single unit. It also defines as section of a unit performing a specific job. Function is code3 snipped that accept values and produce result. Although to be supplied values to produce result. A function in a program is important because of following reasons.

  • Code reusability
  • Manageability
  • Reduce redundancy in programming
  • Logical clarity
  • Easy to divide task among programmer.

User defined Function:

User define function are just a function which are define by a programmer at the time of writing program. A function is just a segment of code that separate rest of code which can perform the similar type of task. The basic syntax for defining user defined function.

<?php

function_name([parameter_list])

{

……………

……………

[return statement]

}

?>

Built-in Function:

These function are already define in the application. These function are used by programmer to design the program. It makes easy to programmer in php, the built-in function are: echo(), print_r(), die(), etc.

The example of dynamic function call:

<?php

function area($l, $b)

{

echo $l*$b;

}

$rect=”area”;

$rect(10,5);

 

$square=”area”;

$square(10,10);

 

$shape=”area”;

$shape(5,5);

?>

 

  1. Write a program to save your personal details into a file “MyFile.csv”.
<?php

$file=fopen("MyFile.csv", 'w');

$name=$_POST[‘name’];

$address=$_POST[‘address’];

$age=$_POST[‘age’];

$arr=array($name, $address, $age);

foreach($arr as $v)

{

fputcsv($file, $v);

}

fclose($f);

echo"sucess";

?>

 

 

  1. What is session and why it is used? Give an example of session with session variables and their values.

A session is a way to store information (in variables) to be used across multiple pages. 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, favorite color, 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.

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Example:

Login.php

<?php

session_start();

$_SESSION[‘username’]=”admin”;

$_SESSION[‘password’]=”Nepal”;

echo”Session created successfully”;

?>

 

Home.php

<?php

session_start():

echo”username is:”.$_SESSION[‘username’];

echo”password is:”.$_SESSION[‘password’];

?>

 

Logout.php

<?php

session_start();

session_unset();

session_destroy();

Echo”logout successfully”;

?>

 

  1. Write a program to read the string from form and display first and last character of string. Also validate the string for alphabet only.

form.html

<form action=”string.php” method=”POST”>

Enter String:<input type=”text” name=”txt”>

<input type=”submit” name=”btn”>

</form>

 

string.php

<php

$strtxt=$_POST[‘txt’];

$s=strlen($strtxt);

$validate=$_POST[‘txt’];

$first=substr($strtxt, 0,1);

$last=substr($strtxt,$s-1,1 );

$pattern_alpha=”/[^a-zA-Z\s]/”;

echo”first $first”;

echo”last $last”;

if(preg_match($pattern_alpha,$validate)){

echo “Correct alpha format”;

}else{

echo “Incorrect alpha format”;

}

?>

 

 

Group C

Comprehensive Answer Question:

  1. Write a PHP code for displaying a simple calendar of current months and year.

<table border=”1″ cellspacing=’0px’ cellpadding=’30px’ align=”center”>

<tr>

<th>Sun</th>

<th>Mon</th>

<th>Tue</th>

<th>Wend</th>

<th>Thur</th>

<th>Fri</th>

<th>Sat</th>

</tr>

<tr>

<?php

$year = $_POST[‘y’];

$month = $_POST[‘m’];

$obj = date_create(“$year/$month/01″);

$start = date_format($obj,”w”);

$totaldays = date_format($obj,”t”);

echo “<td colspan = $start>&nbsp</td>”;

for ($i=1; $i<=$totaldays ; $i++) {

 

if ($start==7) {

$start=0;

echo “</tr><tr>”;

}

$start++;

echo “<td>$i</td>”;

}

?>

</tr>

</table>

 

  1. How can you insert form data safely into database? Write an example.

We can insert form data safely into database by using POST method.

form.php

<form action=”string.php” method=”POST”>

Name:<input type=”text” name=”name”>

Address: <input type=”text” name=”address”

<input type=”submit” name=”btn”>

</form>

 

insert.php

<?php

$n = $_POST[‘name’];

$add = $_POST[‘address’];

$con = mysqli_connect(‘localhost’,’root’,”) or die(mysqli_error($con));

$db = mysqli_select_db($con,”asian”) or die(mysqli_error($con));

$q = “insert into student values(”,’$n’,’$add’)”;

$res = mysqli_query($con,$q) or die(mysqli_error($con));

echo “Your entry has been registered”;

?>

  1. Why PHP is called scripting language?

:     A scripting language is interpreted and executed rather than being compiled, and can be embedded into other languages (eg: HTML), and hence as PHP is able to work in such a way, so it is called a scripting language.

 

  1. Which function is used to convert a single string into array of strings?

                  :     The explode() function is used to convert a string into array of strings.

                  Syntax:

                         variable_name = explode(delimiter,string);

                  Example:

                        <?php

$str = ‘Hello World’;

$arr = explode(‘ ’,$str);

echo $arr[0].’<br>’.$arr[1];

?>

                   Output:

                        Hello

World

 

iii.   Differentiate between GET and POST.

                   :    They are as follows,

GET POST
This is a default method of form submission, in which the data is sent through the URL, which has a size limitation (255 characters is not the size limitation, but is a good practice to use as one), and cannot be used in for sensitive data, everything is visible in the URL. This is another form submission method, which sends the data through HTTP request body (say internally), which has no major size limitation, and can be used for sensitive data like password.

 

 

 

  1. When do the $_REQUEST variables are used?

                   :    We use the $_REQUEST variables to collect data after submitting the HTML    forms.

 

  1. Why do we need file?

                   :    We need file to manage data, i.e. to store data, update data, retrieve data, etc., in a particular manner.

 

  1. What is the use of foreach in php? Write with example.

                    :    The foreach is a looping statement, which is mainly used for looping through the values of an array. It loops over the array, and each value for the current array element is assigned to a variable (let $v), and the array pointer is advanced by one to go to the next element in the array.

           

vii.     How can you enable a session in PHP?

                      :  We can enable the session in PHP simply by using the session_start() function, and we can set the session variables with the help of PHP global variable $_SESSION.

 

viii.    Which function is used to read the data from the database?

                      :  For a mysql database, we can simply use the code “SELECT column_name FROM table_name” to read the data from the database, and we can read and display the data from the database as:

            Example:

                        <?php

//db_name: test, table_name: tab1, column_names: cl1, cl2

$C  = mysqli_connect(‘localhost’,’root’,’’,’test’) or die(‘Connection error’);

//Connecting with the database with localhost host, and root username

$code = “SELECT * FROM tab1”;

//sql code to display all the contents of tab1

$R = mysqli_query($C,$code);//Performing query against the database

echo ‘<h2>Data from the database</h2>’;

while($data = mysqli_fetch_array($R))

echo ‘Col1: ’.$data[0].’ & Col2: ’.$data[1].’.<br>’;

?>

 

  1. Write the output of the following:

                     <?php

                         function increment($x){

            return (++$x + 5 – 6 * 3 – $x–);

}

echo increment();

        ?>

       :    As too few arguments are passed in the function increment, as 0 passed, expected 1, and as a result of which an error message will be displayed.

 

  1. Define web server.

:     A web server is a system that delivers content or services to end users over the internet.

 

 

Group “B”

 

      Exercise Problems:

 

  1. Write a program to print the data of a student in a table with heading bold background green, and data in italic background orange, which is stored in database. Assume your own database parameters.

:           Program,

<?php

//db_name: ‘stu’, table_name: ‘student’, cols_names: ‘s_id’, ‘s_name’

$C = mysqli_connect(‘localhost’,’root’,”,’stu’) or die(‘Error’);

$code = ‘SELECT s_id, s_name FROM student’;

$R = mysqli_query($C,$code);

echo “<table bgcolor = ‘orange’ border = ‘1’ cellspacing = ‘0’ cellpadding = ’20’>”;

echo “<caption align = ‘bottom’>Student Information</caption>”;

echo “<tr bgcolor = ‘green’><th>ID</th><th>Name</th></tr>”;

while($a = mysqli_fetch_array($R))

{

echo “<tr>”;

echo “<td><i>”.$a[0].”</i></td>”;

echo “<td><i>”.$a[1].”</i></td>”;

echo “</tr>”;

}

?>

 

  1. Write a program to sort the array of strings in ascending order and display them without using any sorting functions.

:           Program,

<?php

$arr = array(‘Ram’,’Hari’,’Akshay Kumar’,’Shyam’);

echo “Elements of the array:<br>”;

foreach($arr as $v)

echo $v.”<br>”;

echo ‘<br>’;

$len = sizeof($arr);

for($i=0;$i<$len;$i++)

{

for($j=$i+1;$j<$len;$j++)

{

if($arr[$i]>$arr[$j])

{

$temp = $arr[$i];

$arr[$i] = $arr[$j];

$arr[$j] = $temp;

}

}

}

echo “Elements of the array(Sorted in asc. order):<br>”;

foreach($arr as $v)

echo $v.”<br>”;

?>

 

  1. Write an example program to which stores username and password valid for next 10 days.

:           Program,

<?php

$un = ‘Someone’;

$pw = ‘Something’;

if(setcookie(‘Username’,$un,time()+10*24*60*60) && setcookie(‘Password’,$pw,time()+10*24*60*60) )

echo “Cookies saved”;

else

echo “Error”;

?>

 

  1. Write a program which uses recursice function to display the nth number of a Fibonacci series.

:           Program,

<?php

function fibo($n)

{

if($n == 0)

return 0;

if($n == 1)

return 1;

return fibo($n-1)+fibo($n-2);

}

if(isset($_POST[‘cal’]))

{

$n = $_POST[‘num’];

echo $n.”th Fibonacci number is: “.fibo($n);

}

?>

<html>

<head>

<title>Fibonacci number</title>

</head>

<body>

<form method = ‘post’>

N: <input type = ‘number’ name = ‘num’ min = ‘0’><br>

<input type = ‘submit’ name = ‘cal’ value = ‘FIBO’>

</form>

</body>

</html>

 

  1. Write a program that takes date of birth as input and display the current age of the person.

:           Program,

<?php

if(isset($_POST[‘cal’]))

{

$dob = $_POST[‘dob’];//String YYYY-MM-DD

$arr = explode(‘-‘,$dob);

$age = time()-mktime(0,0,0,$arr[2],$arr[1],$arr[0]);

//difference in seconds

$age = (int)($age/(60*60*24*365)); //calculating year

echo “You are “.$age.” years old.”;

}

?>

<html>

<head>

<title>Fibonacci number</title>

</head>

<body>

<form method = ‘post’>

DOB: <input type = ‘date’ name = ‘dob’ requied><br>

<input type = ‘submit’ name = ‘cal’ value = ‘Calculate Age’>

</form>

</body>

</html>

 

Group “C”

 

Comprehensive Questions:

 

  1. Create a user login form in ‘home.php’ which would display the contents like ‘Hello XXXXX’ only upon providing the valid username and password to the login form which is verified from the database. The login form shouldn’t be displayed if user is authenticated. (Assume your own database parameters).

:           Program,

<?php session_start();

if(isset($_SESSION[‘user’]))

{

echo “Hello “.$_SESSION[‘user’].”!”;

echo “<form method = ‘post’><input type = ‘submit’ name = ‘lout’ value = ‘Logout’></form>”;

if(isset($_POST[‘lout’]))

{

unset($_SESSION[‘user’]);

header(‘location:home.php’);

}

die();

}

if(isset($_POST[‘Log’]))

{

//dbname: ‘pasal’ | tablename: ‘user_accounts’ | colsnames: ‘username’, ‘password’;

$u = $_POST[‘un’];

$p = $_POST[‘pw’];

$C = mysqli_connect(‘localhost’,’root’,”,’pasal’) or die(‘Error connecting to the database’);

$code = “SELECT * FROM user_accounts WHERE username = ‘$u’ AND password = ‘$p'”;

$R = mysqli_query($C,$code);

while($data = mysqli_fetch_assoc($R))

{

$_SESSION[‘user’] = $u;

header(‘location:home.php’);

}

if(!isset($_SESSION[‘user’]))

echo “Authentication error”;

}

?>

<html>

<head>

<title>home.php</title>

</head>

<body>

<form method = ‘post’>

Username: <input type = ‘text’ name = ‘un’ required><br>

Password: <input type = ‘password’ name = ‘pw’ required><br>

<input type = ‘submit’ name = ‘Log’ value = ‘Login’>

</form>

</body>

</html>

 

  1. Write a PHP program to create a form, which collects the data of a person (name, age, Mobile# and email address). Perform the server side validation of the data submitted by the following rule. (All fields are required, name cannot contain numbers and any other special characters, age must be whole number, mobile number must be in the format [98XXXXXXXX], and email also be in valid format).

:           Program,

<html>

<head>

<title>Login</title>

</head>

<body>

<?php

$msg = array(”,”,”,”);

//0=>name,1=>age,2=>mobile,3=>address

function validate($n,$a,$m,$e)

{

//Empty fields

if($n==”||$a==”||$m==”||$e==”)

{

echo “Empty fields are not allowed!”;

return false;

}

//name

$regN = “/^[A-Z]+[A-z\s]+[a-z]$/m”;

if(!preg_match($regN,$n))

{

echo “Invalid name”;

return false;

}

//Age

$regA = ‘/^[\d][\d]{0,2}$/m’;

if(!preg_match($regA,$a))

{

echo “Invalid age”;

return false;

}

//mobile

$regM = “/^(98)+\d{8}$/m”;

if(!preg_match($regM,$m))

{

echo “Invalid mobile number”;

return false;

}

//email

if(!filter_var($e,FILTER_VALIDATE_EMAIL))

{

echo “Invalid email”;

return false;

}

return true;

}

if(isset($_POST[‘login’]))

{

$name = $_POST[‘nm’];

$age = $_POST[‘age’];

$mobile = $_POST[‘mobile’];

$email= $_POST[‘eadd’];

if(validate($name,$age,$mobile,$email))

die(‘Your data is submitted.’);

}

?>

<form method = ‘post’>

Name: <input type = ‘text’ name = ‘nm’ size = ’50’ placeholder = ‘Should not contain numbers and special characters’><br>

Age: <input type = ‘text’ name = ‘age’ size = ’50’ placeholder = ‘Should be a whole number of 1-3 chracters’><br>

Mobile: <input type = ‘text’ name = ‘mobile’ size = ’50’ placeholder = ’98XXXXXXXX format’><br>

E-mail address: <input type = ‘text’ name = ‘eadd’ size = ’50’ placeholder = ‘[email protected] format’><br>

<input type = ‘submit’ name = ‘login’ value = ‘Login’>

</form>

</body>

</html>

2017

Group A

  1. Register_global variablesis an internal PHP setting which registers the $_REQUEST array’s elements as variables. If you submit a value in a form, via POST or GET, the value of that input will automatically be accessible via variable in the PHP script, named after the name of the input field.
  2. To create a constant,  weuse the define() function.
    Syntax :- define(name, value)
    Example:-

<?php

define(“GREETING”, “Welcome to BIM-Notes.com!”);

echo GREETING;

?>

 

  1. The substr() function returns a part of a string.

Example:-

<?php

// Positive numbers:

echo substr(“Hello  Everyone”,10).”<br>”;

?>

 

  1. A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers’ HTTP clients. Dedicated computers and appliances may be referred to as Web servers as well.
  2. The trim() function removes whitespace and other predefined characters from both sides of a string.
    Example:-

<?php

$str = ” Hello World! “;

echo “Without trim: ” . $str;

echo “<br>”;

echo “With trim: ” . trim($str);

?>

Output:-

Without trim: Hello World!
With trim: Hello World!

  1. A uniform resource locator (URL) is the address of a resource on the Internet. A URL indicates the location of a resource as well as the protocol used to access it.
  2. 7.  Mysql_fetch_row fetch result row an numeric way. This function return a row where the valuew will come in the order as they are defined in the query, and the keys will span from 0 to one less than the number of columns selected

Mysql_fetch_assoc() fetch a result row as an associative array.This function will return a row as an associative array where the column names will be the keys storing corresponding value.

8.

<?php

$mysqli = new mysqli(“localhost”, “username”, “password”, “dbname”);

?>

 

  1. The PHP date() function is used to format a date and/or a time.
    Example:-

<?php

echo “Today is ” . date(“Y.m.d”) . “<br>”;

?>

 

  1. A CSV (Comma Separated Values) file is a text based format that represents the data typically found in a spreadsheet or a database table.

Advantages of CSV :-

  1. CSV files can be opened or edited by text editors like notepad.
  2. In data-warehouse, CSV follows a fairly flat, simple schema.
  3. Any programming language to parse CSV data is trivial, generating it is extremely easy.
  4. Importing CSV files can be much faster, and it also consumes less memory.

Group B

  1. Write PHP code to perform server side validation. (check for empty, alphabets, numbers, email and password length validation) 
<?php

if(isset($_POST['submit'])){

if(isset($_POST['name']) && !empty($_POST['name']) && trim($_POST['name']) != ''){

$name = $_POST['name'];

 $regex = '/^[a-zA-Z ]*$/';

 if(!preg_match($regex, $name)){

 echo 'Only letters and space are allowed'; }else{ echo 'Name: '.$name; } }

else{ echo 'Enter name'; }
if(isset($_POST['phone']) && !empty($_POST['phone']) && trim($_POST['phone']) != ''){ $phone = $_POST['phone']; $regex = '/^([0-9]{10})$/'; if(!preg_match($regex, $phone)){ echo '<br ?I

invalid phone pattern';

}else{

echo '

Phone: '.$phone;

}

}else{

echo '

Enter name';

}

if(isset($_POST['email']) && !empty($_POST['email']) && trim($_POST['email']) != ''){

$email = $_POST['email'];

$regex = '/^([a-zA-Z0-9\.\-\_])+\@(([a-zA-Z0-9\.\-])+\.)+([a-zA-Z0-9]{2,4})+$/';

if(!preg_match($regex, $email)){

echo '

Invalid email pattern';

}else{

echo '

Email: '.$email;

}

}else{

echo '

Enter email';

}

if(isset($_POST['password']) && !empty($_POST['password']) && trim($_POST['password']) != ''){

if(strlen($_POST['password']) < 6){

echo '

Password must be greater than 6 character';

}else{

echo '

Password: '.$password = $_POST['password'];

}

}else{

echo '

Enter password';

}

}

?>

 

 

<body>

<form action="" method="post">

<label>Name</label>

<input type="text" name="name" /> <br />

<label>Phone</label>

<input type="text" name="phone" /> <br />

<label>Email</label>

<input type="text" name="email" /> <br />

<label>Password</label>

<input type="text" name="password" /> <br />

<input type="submit" name="submit" value="Submit" />

</form>

</body>

 

Top of Form

Name

Phone

Email

Password

Bottom of Form

  1. Write a function to calculate sum of all even numbers that occurs between given two integers passed as parameters. 
<?php

function even_sum($first_num, $second_num)

{

$sum = 0;

for($i = $first_num; $i <= $second_num; $i++){ //inclusive

 if($i % 2 == 0){

 $sum += $i;

}

 }

 return $sum;

}

$total_sum = even_sum(10, 20);

echo 'Total sum: '.$total_sum;

?>

 

 

  1. Create an array that contains your name, address, age, gender. Then write the array to the file name “profile.csv”. 
<?php

$file = fopen('profile.csv', 'w') or die('Cannot open file');

$title = array('Name', 'Address', 'Age', 'Gender');

if(fputcsv($file, $title)){

echo 'Title written to the file'; }

esle{

echo 'Title cannot written to the file';

}

$student = array('name' => 'Prakash', 'address' => 'Bhaktapur', 'age' => 20, 'gender' => 'Male'); if(fputcsv($file, $student)){

echo 'Contents written to the file'; }else{ echo 'Contents cannot written to the file';

}

fclose($file);

 

  1. 1 Create a login system, making your own assumptions about database, authorize the login credentials. 
<?php

$conn = mysqli_connect('localhost', 'root', '', 'registration');

$err = array();

if(isset($_POST['submit'])){

if(isset($_POST['username']) && !empty($_POST['username']) && trim($_POST['username']) != ''){

$username = mysqli_real_escape_string($conn, $_POST['username']);

}else{

$err['username'] = 'Username is required';

}

if(isset($_POST['password']) && !empty($_POST['password'])){

$password = mysqli_real_escape_string($conn, $_POST['password']);

}else{

$err['password'] = 'Password is required';

}

if(count($err) == 0){

$password = md5($password); //encrypt password before storing database

$sql = "SELECT * FROM student WHERE username = '$username' AND password = '$password'";

$result = mysqli_query($conn, $sql);




if (mysqli_num_rows($result) == 1) {

header('location: welcome.php');

}else{

$err['error'] = 'Wrong username/password combination';

}

}

}




?>

 

<body>

<form action="" method="post">

<?php if(isset($err['error'])){

echo $err['error'];

} ?> <br />

<label>Username</label>

<input type="text" name="username" />

<?php if(isset($err['username'])){

echo $err['username'];

} ?> <br />

<label>Password</label>

<input type="text" name="password" />

<?php if(isset($err['password'])){

echo $err['password'];

} ?> <br />

<input type="submit" name="submit" value="Submit" />

</form>

<p>Username: Prakash Adhikari</p>

<p>Password: prakash</p>

</body>

 

  1. Write a PHP function to calculate the difference between two dates in PHP. 
<?php

if (isset($_POST['submit'])) {

if (isset($_POST['date1']) && !empty($_POST['date1']) && trim($_POST['date1']) != '') {

$date1 = $_POST['date1'];

}else{

echo 'Enter first date';

}

if (isset($_POST['date2']) && !empty($_POST['date2']) && trim($_POST['date2']) != '') {

$date2 = $_POST['date2'];

}else{

echo 'Enter second date';

}

if(isset($date1) && isset($date2)){

$d1 = strtotime($date1);

$d2 = strtotime($date2);

function diff_date($date1, $date2){

$diff = abs($date1 - $date2);

$days = intval($diff / (24 * 60 * 60));

$years = intval($days / 365);

$days = $days % 365;

$months = intval($days / 30);

$days= $days % 30;

echo 'Difference between two dates is: '.$years.' years '.$months.' months '.$days.' days';

}

diff_date($d1, $d2);

}

}




?>

 

<body>

<form action="" method="post">

<label>Date1</label>

<input type="text" name="date1" placeholder="yyyy/mm/dd" /> <br />

<label>Date2</label>

<input type="text" name="date2" placeholder="yyyy/mm/dd" /> <br />

<input type="submit" name="submit" value="Submit" />

</form>

</body>

 

2016

Group A

1.List out the advantage of using PHP

  • PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP supports a wide range of databases
  • PHP is free. Download it from the official PHP resource: php.net
  • PHP is easy to learn and runs efficiently on the server side
  1. What is use of identical operator(===)
  • The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is “=”. It means that the left operand gets set to the value of the assignment expression on the right.
  1. Write syntax of foreach loop

forEach(function(element) {

 

……………..

});

 

 

  1. How a function is declared using default values for its arguments

Function arguments Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right. PHP supports passing arguments by value (the default), passing by reference, and default argument values.

  1. “validations should be performed on both the client and server side”. Why

validations should be performed on client side in order to validate data and validations should be performed on server side in order to check user.

  1. Define server variable HTTP_USER_AGENT with an example

The user agent string is a text that the browsers themselves send to the web server to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

  1. What are the advantage of using PEAR over PHP built in functions to work with the database

The advantage of using PEAR over PHP built in functions to work with the database is it can be used in any database

  1. How to display the current date in web page using PHP statement

Tthe current date can be display using date function in web page using PHP statement

  1. What is use of mysql_fetch_assoc() function

The mysql_fetch_assoc() used to retrieve a row of data as an associative array from a MySQL result handle. … Refers to the resource return by a valid mysql query (calling by mysql_query() function). … An array containing one row of data, or FALSE if there are no more rows

Group B

11.Write a PHP program to create a web form that contains a textbox for name, and checkboxes for hobbies. When a form is submitted, check a name is entered and at least one of the hobbies is selected.

<?php

if(isset($_POST['submit'])){

if(isset($_POST['name']) && !empty($_POST['name']) && trim($_POST['name']) != ''){

echo 'Name: '.$name = $_POST['name'];

}else{

echo 'Enter your name';

}

if(isset($_POST['checkbox'])){

$check_value = $_POST['checkbox'];

echo '<br />Hobbies: ';

foreach ($check_value as $check) {

echo $check.',';

}

}else{

echo '<br />Please select an option';

}

}




?>

 

<body>

<form action="" method="post">

<label>Name</label>

<input type="text" name="name" /> <br />

<label>Hobbies</label>

<input type="checkbox" name="checkbox[]" value="Dancing" />Dancing

<input type="checkbox" name="checkbox[]" value="Singing" />Singing

<input type="checkbox" name="checkbox[]" value="Playing" />Playing <br />

<input type="submit" name="submit" value="Submit" />

</form>

</body>

 

12.Write a PHP program to display the contents of a database. Make your own assumptions about database.

<?php

$conn = mysqli_connect('localhost', 'root', '', 'db_php');

if(!$conn){

die("Database connection error");

}

$sql = "SELECT * FROM test";

$result = mysqli_query($conn, $sql);

$data = array();

while($d = mysqli_fetch_array($result, MYSQLI_ASSOC)){

array_push($data, $d);

}

?>

<table border="1">

<tr>

<th>ID</th>

<th>Name</th>

<th>Email</th>

<th>Address</th>

</tr>

<?php foreach ($data as $value) { ?>

<tr>

<td><?php echo $value['id']; ?></td>

<td><?php echo $value['name']; ?></td>

<td><?php echo $value['email']; ?></td>

<td><?php echo $value['address']; ?></td>

</tr>

<?php } ?>

</table>

 

 

 

  1. Write a PHP function that makes three arguments: principle, rate and time and returns the calculated interest. Make all the required validation to calculate the interest. 

<?php

if(isset($_POST[‘submit’])){

if(isset($_POST[‘principle’]) && !empty($_POST[‘principle’]) && trim($_POST[‘principle’]) != ”){

if($_POST[‘principle’] < 0){

echo ‘Principle must be positive value’;

}else{

$principle = $_POST[‘principle’];

}

}else{

echo ‘Enter principle’;

}

if(isset($_POST[‘time’]) && !empty($_POST[‘time’]) && trim($_POST[‘time’]) != ”){

if($_POST[‘time’] < 0){

echo ‘<br />Time must be positive value’;

}else{

$time = $_POST[‘time’];

}

}else{

echo ‘<br />Enter time’;

}

if(isset($_POST[‘rate’]) && !empty($_POST[‘rate’]) && trim($_POST[‘rate’]) != ”){

if($_POST[‘rate’] < 0){

echo ‘<br />Rate must be positive value’;

}else{

$rate = $_POST[‘rate’];

}

}else{

echo ‘<br />Enter rate’;

}

if(isset($principle) && isset($time) && isset($rate)){

function simple_interest($principle, $time, $rate){

return ($principle * $time * $rate) / 100;

}

$simple_interest = simple_interest($principle, $time, $rate);

echo ‘Simple interest is: ‘.$simple_interest;

}

}

 

?>

<body>

<form action=”” method=”post”>

<label>Principle</label>

<input type=”text” name=”principle” /> <br />

<label>Time</label>

<input type=”text” name=”time” /> <br />

<label>Rate</label>

<input type=”text” name=”rate” /> <br />

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

</form>

</body>

 

 

  1. What is file? Write a program to write value taken from user to a file. 

<?php

if(isset($_POST[‘submit’])){

if(isset($_POST[‘text’]) && !empty($_POST[‘text’]) && trim($_POST[‘text’]) != ”){

$text = $_POST[‘text’];

$myfile = fopen(‘myfile.txt’, ‘w’) or die(‘Cannot open file’);

fwrite($myfile, $text);

fclose($myfile);

}else{

echo ‘Enter text’;

}

}

 

?>

<body>

<form action=”” method=”post”>

<label>Text</label>

<textarea name=”text” placeholder=”Write here..”></textarea> <br />

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

</form>

</body>

 

 

  1. Write a PHP program to create a multidimensional array that holds the cities of districts in Kathmandu valley such as Kathmandu(Newroad , Durbar Marg, Thamel) Lalitpur(Patan, Jawalakhel, Kupandole) Bhaktpur(Durbar Square, suryabinayak). Then display the contents of array. 

<?php

$district = array(

‘Kathmandu’ => array(‘Newroad’, ‘Durbar Marg’, ‘Thamel’),

‘Lalitpur’ => array(‘Patan’, ‘Jawalakhel’, ‘Kupandole’),

‘Bhaktapur’ => array(‘Durbar Square’, ‘Suryabinayak’)

);

?>

<table border=”1″>

<tr>

<th>SN</th>

<th>District</th>

<th>Location</th>

</tr>

<?php $x = 0; foreach ($district as $dis => $value) { ?>

<tr>

<td><?php echo ++$x; ?></td>

<td><?php echo $dis; ?></td>

<td><?php echo implode(‘,’, $value); ?></td>

</tr>

<?php } ?>

</table>

Group C

1.Explain the importance of default value in a form with example.

The importance of default value is that Default values will make  easier  for users to complete  forms and clear when a user begins typing in the field .These default values are not saved with the form submission. Default values will be used when a new entry is created or when a field is conditionally shown. Default values will NOT replace submitted values when you edit an entry, even if the submitted value is empty. When you redisplay a form because of an error, it is helpful to preserve any information that a user has already entered.

For example

if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {

$defaults = $_POST;

} else {

$defaults = array(‘delivery’ => ‘yes’,

‘size’ => ‘medium’,

‘main_dish’ => array(‘taro’,’tripe’),

‘sweet’ => ‘cake’);

}

2.What is session variable? How are session variable handled in php? Explain with example.

Session variable are special variables that exist only while the users session with application is active.Session variable handled by storing user information to be used across multiple pages. Session variable handled in php by using the following example.

<?php

// Start the session

session_start();

?>

<!DOCTYPE html>

<html>

<body>

 

<?php

// Set session variables

$_SESSION[“favcolor”] = “green”;

$_SESSION[“favanimal”] = “cat”;

echo “Session variables are set.”;

?>

 

</body>

</html>

year 2015

Group B

  1. Write a program in PHP to add three numbers. 

<body>

<form action=”” method=”post”>

<label>First Number</label>

<input type=”number” name=”first_num” /> <br />

<label>Second Number</label>

<input type=”number” name=”second_num” /> <br />

<label>Third Number</label>

<input type=”number” name=”third_num” />

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

</form>

</body>

 

<?php

if($_POST){

$first_num = $_POST[‘first_num’];

$second_num = $_POST[‘second_num’];

$third_num = $_POST[‘third_num’];

$sum = $first_num + $second_num + $third_num;

echo ‘Sum: ‘.$sum;

}

 

?>

  1. Write a PHP program to display first and last character of a string. 

<body>

<form action=”” method=”post”>

<label>Enter a string</label>

<input type=”text” name=”text” />

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

</form>

</body>

 

<?php

if($_POST){

$string = trim($_POST[‘text’]);

$length = strlen($string);

for($i = ($length – 1); $i >= 0; $i–){

if($i == ($length-1)){

echo ‘Last character is: ‘.$string[$i];

}

if($i == 0){

echo ‘<br />First character is: ‘.$string[$i];

}

}

}

 

?>

 

  1. Create two integer array of size 5 each with data item in them. Then display sum of all the number of both arrays. 

<?php

$first_array = array(2, 4, 6, 8, 10);

$second_array = array(3, 5, 7, 9, 11);

$result_array = array();

for($i = 0; $i < sizeof($first_array); $i++){

$result_array[$i] = $first_array[$i] + $second_array[$i];

}

echo “<pre>”;

print_r($result_array);

echo ‘Sum of two arrays is: ‘.array_sum($result_array);

 

?>

  1. Write a program in PHP to store “coding in PHP” in a file named “coding.txt” .

<?php

$text = ‘coding in PHP’;

$myfile = fopen(‘coding.txt’, ‘w’) or die(‘Cannot open file’);

fwrite($myfile, $text);

fclose($myfile);

echo ‘Content written to the file’;

 

?>

 

16.

<table border=”1″ style=”border-collapse: collapse; width: 250px”>

<thead>

<tr>

<th>Name</th>

<th>Age</th>

<th>Gender</th>

</tr>

</thead>

<tbody>

<tr>

<th>R</th>

<th>21</th>

<th>M</th>

</tr>

<tr>

<th>A</th>

<th>20</th>

<th>F</th>

</tr>

</tbody>

</table><input id=”6251.5200704804351″ class=”cdbx-try-code-web cdbx-btn-main” style=”background-color: #ffffff; margin-bottom: 0; color: #008b8b; border: 1px solid rgba(231, 231, 230, 1); border-radius: 10px; font-size: 13px; height: 30px; min-width: 110px; max-width: 220px; padding: 4px; font-weight: normal; outline: none; display: none; float: right;” type=”button” value=”Run HTML” data-lang=”html” data-code=”1534084070025.1526″ data-mce-style=”background-color: #ffffff; margin-bottom: 0; color: #008b8b; border: 1px solid rgba(231, 231, 230, 1); border-radius: 10px; font-size: 13px; height: 30px; min-width: 110px; max-width: 220px; padding: 4px; font-weight: normal; outline: none; display: none; float: right;”>

ASain 2073

  1. What are the different ways of writing comments in PHP
  • →// and /* are the different ways of writing comments in PHP
  1. Write the function to convert given array to string. Give examples
  • → mysql_fetch_array() is the function to convert given array to string
  1. How do you connect to database server? Write example
  •  <?php $con=mysql_connect(“localhost”,”root”,””);or die(“Cannot Connect to server”);’  ?>
  1. What are the difference between include() and require() function
  •  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.

5.What is the use of intval() function

  •  One thing to note about the difference between (int) and intval() : intval() treats variables which are already int s and float s as needing no conversion, regardless of the base argument (as of PHP 5.3.5 at least). … The common rules of integer casting apply
  1. How to display the current date in web page
  • The current date can be display using date function in web page using PHP statement

7.What is the use of foef() function

  •  The feof() function checks if the “end-of-file” (EOF) has been reached.
  1. Write two difference between HTTP GET and 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.
  1. Write the advantage of writing function in program
  • A function in a program is important because of following reasons:
  1. Code reusability
  2. Manageability
  3. Reduced redundancy in programming
  4. Logical clarity
  5. Easy to divide the task among programmer

10.What is web server? Give example

  • → A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers’ HTTP clients. Dedicated computers and appliances may be referred to as Web servers as well

NCCS 2016 [SET A]

  1. What is web server
  •  A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers’ HTTP clients. Dedicated computers and appliances may be referred to as Web servers as well
  1. What is client side validation
  • Validations can be performed on the server side or on the client side ( web browser). The user input validation take place on the Server Side during a post back session is called Server Side Validation and the user input validation take place on the Client Side (web browser) is called Client Side Validation.
  1. Write rules for creating function in php
  •  Any valid PHP code may appear inside a function, even other functions and class definitions. Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

4.Give a condition when variable declared will be a local scope

  • → When we need the variable within then function then we will declared a local scope
  1. What is the use of strpos() function

→ The strpos() function finds the position of the first occurrence of a string inside another string. … stripos() – Finds the position of the first occurrence of a string inside another string (case-insensitive)

  1. What do you understand by file permission

→ Most file systems have methods to assign permissions or access rights to specific users and groups of users. These systems control the ability of the users to view, change, navigate, and execute the contents of the file system.

  1. What does mysqli_fetch_array() does

→ Fetch a result row as an associative array, a numeric array, or both.

 

NCCS 2016 [SET B]

  1. What is web server ?

→ A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers’ HTTP clients. Dedicated computers and appliances may be referred to as Web servers as well

2.Differentiate between require() and require_one() ?

→ require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example.

3.What is server side validation ?

→ Validations can be performed on the server side or on the client side ( web browser). The user input validation take place on the Server Side during a post back session is called Server Side Validation and the user input validation take place on the Client Side (web browser) is called Client Side Validation.

  1. How can we display time in php ?

→ the current time can be display using date function in web page using PHP statement

5.Give a condition when a variable has a Global scope.

→ If we need the same variables within whole program then a variable has a Global scope

  1. Where will be the file pointer placed in w and w+ mode?

→ Both of them will create the file if it doesn’t exist. Then it will clear it out if it has information in it. … Then it will clear it out if it has information in it. w works for writing, w+ will work for reading a… … ‘w’ Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length

7 .What is the use of file_get_contain()?

→ The file_get_contents() reads a file into a string

8.What is header()?

→ Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called.

9.What does mysqli_field_count() does?

→ mysqli_field_count() return column of table.

 

Orchid 2073 [SET A]

1.What are the different ways of writing comments in PHP

  • // and /* are the different ways of writing comments in PHP
  1. Write the function to convert given array to string. Give examples.
  •  mysqli_fetch_array() convert given array to string

3.What is dynamic web page? How it is differ to static page?

  •  The web page which can be modify without reaching source code is called dynamic web page. But in static web page we have to reach to source code for that
  1. What are the differences between require() and require_one() function ?
  •  require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example.
  1. What is the use of intval() function ?
  • One thing to note about the difference between (int) and intval() : intval() treats variables which are already int s and float s as needing no conversion, regardless of the base argument (as of PHP 5.3.5 at least). … The common rules of integer casting apply
  1. How to display the current date in web page ?
  • The current date can be display using date function in web page using PHP statement
  1. What is the use of feof() function
  • The feof() function checks if the “end-of-file” (EOF) has been reached.
  1. Write two differences between HTTP GET and 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.
  1. Write the advantages of writing function in program

→ A function in a program is important because of following reasons:

  1. Code reusability
  2. Manageability
  3. Reduced redundancy in programming
  4. Logical clarity
  5. Easy to divide the task among programmer
  1. What is web server? Give example

→ A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers’ HTTP clients. Dedicated computers and appliances may be referred to as Web servers as well

Orchid 2073 [SET B]

1.Why comments are important in program?

→ Comment are important in program in order to increase reliability

2.Write the function to convert given string to array. Give examples.

→ mysqli_fetch_array() help to convert given string to array

3.What is required technology to make web page dynamic?

→ Database and JQuarries are required technology to make web page dynamic

  1. What is the use of include_once() function ?

→ he problem is that is_int() thinks a string of numbers is a string, not an integer. … Note: This function require a string to be useful, so for example passing in an integer will always return FALSE

5 .What is_numeric() function does

→ The problem is that is_int() thinks a string of numbers is a string, not an integer. … Note: This function require a string to be useful, so for example passing in an integer will always return FALSE

  1. How to take user define date from user in php

→ the user define date from user can be display using date function in web page using PHP statement

7 .What is the use of fwrite() function? Give example

→ The use of fwrite() function is to write in file

  1. Write the advantage of array in a program

→ the advantage of array in a program is to reduce complexity and number of variables

9 .What is web client? Give example

→ The client, or user, side of the Web. It typically refers to the Web browser in the user’s machine. It may also refer to plug-ins and helper applications that enhance the browser to support special services from the site.

 

 


Didn't Find Any Subjects/Contents?

Click on the contribute button to contribute subjects materials on Study Notes Nepal.

Contribute

Leave a Reply

Your email address will not be published. Required fields are marked *


Join Our Facebook Community Group

Study Notes Nepal