Secret mind

hi Friends, I am Aman gupta and a web developer. I learned many languages such as java, javaScript, python, clang, php, jquery, mysql database, Html and css and many more just to make a perfect and wonderfully website. Here i will upload related post of PHP, Secret of world, computer science, Feelings, GK, And Question paper.

Trending video

Responsive Ads Here

Sunday, December 22, 2019

PHP Important Qenstions For Exam

PHP Important Questions For Exam


Secret MInd

1.What is the difference between echo and print with examples.
Ans:-
echo:- 

  1. echo statement is used to display the output. echo can be used with parentheses or without parentheses.
  2. We can pass multiple strings with echo and all of these must separate with commas(,).
  3. echo doesn’t return any value.
  4. When we print with echo, the operation is fast as compared to print.
Examples:
 <?php
$name="Abhi";
echo $name;
//or
echo ($name);
?>

print:- 

  1. print statement is used to display the output. print can be used with parentheses or without parentheses.
  2. using print can doesn’t pass multiple arguments
  3. print always return 1
  4. When we print with print, the operation is slow as compared to echo.


Example:
<?php
$name="Abhi";
print $name;
//or
print ($name);
?>

2. Different between $_GET and $_POST briefly.
Ans:- Using the GET and POST methods, the browser client can send data to the web server. In PHP the GET and POST methods are used to retrieve information from forms, such as user input. Get and Post are methods used to send data to the server. These methods are used for data handling in forms.  Where each method varies a little in the way they work.

$_GET:-
In the GET method, we can also send data to the server. But when using the GET method we can't send the login details with a word because it is less secure (information sent from a form with the GET method is visible to everyone). We can say that the GET method is for getting something from the server; it doesn't mean that you cannot send a parameter to the server.
The main points about the GET method are as follows:

  • The GET method is used to collect values in a form.
  • GET method is used when the URL is sent to the server.
  • GET method has limits on the amount of information to send because URL lengths are limited.
  • The Get method is used to retrieve web pages from the server.
  • The GET method is the default method for many browsers.
  • Data is sent as a part of the URL in 'name-value' pairs.
  • In the GET method page and the encoded information are separated by the question mark  (?) sign.
  • In the GET method, the browser appends the data onto the URL.
  • The Get method is less secure because information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) .
  • GET can't be used to send binary data, like images or word documents, to the server.
Example:-
First of all we create a PHP file which is called by the HTML page in later.

<html>
<body bgcolor="pink">
Welcome <?php echo $_GET ["Name"]; ?>.<br/>
You are <?php echo $_GET ["Class"]; ?> Qualified !!
</body>
</html>

The above file is to be saved with the name "get.php", which is called by the HTML page later.

<html>
<body bgcolor="pink"><table>
<form action="get.php" method="get">
<tr><td>Name: <input type="text" name="Name" /></td></tr>
<tr><td>Class : <input type="text" name="Class" /></td></tr>
<input type="submit" " value="Submit"/>
</form>
</body>
</html>

 $_POST:-
In PHP $_POST variable is used to collect values from a form sent with method="post". In the POST method one can request as well as send some data to the server. The POST method is used when one can send a long enquiry form. Using the POST method the login details with word can be posted because it is secure (information sent from a form with the POST method is invisible to everyone).

The main points about POST method are as follows:

  • The POST method is used to collect values from a form.
  • The POST method has no limits on the amount of information to send because URL lengths are unlimited.
  • The POST method is the not default method for many browsers.
  • In the POST method, the page and the encoded information are not separated by the question mark  (?) sign.
  • In the POST method, the browser doesn't append the data onto the URL.
  • The POST method is secure because information sent from a form with the GET method is invisible to everyone.
  • The POST method can be used to send binary data, like images or Word documents, to the server.
  • In the POST method, the data is sent as standard input.
  • The POST method is slower than the GET method.
  • PHP provides the $_POST associative array to access all the information sent using the GET method.
Example:-

First of all we create a PHP file which is called by the HTML page later.

<html>
<body bgcolor="pink">
Welcome <?php echo $_POST ["Name"]; ?>.<br/>
You are <?php echo $_POST ["Class"]; ?> Qualified !!
</body>
</html>

The above file is saved with the "post.php" name, which is called by the HTML page later.

<html>
<body bgcolor="pink">
<table>
<form action="post.php" method="post">
<tr><td>Name: <input type="text" name="Name" /></td></tr>
<tr><td>Class : <input type="text" name="Class" /></td></tr>
<input type="submit" " value="Submit"/>
</form>
</body>
</html>

This file is saved as "post.html".

3.What are super-global variable? Explain All.
Ans:- Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
The PHP superglobal variables are:
  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE
  • $_SESSION
1.$GLOBALS:-  $GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods).

PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

The example below shows how to use the super global variable $GLOBALS
<?php
$x = 75;
$y = 25;
function addition() {
    $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
2. $_SERVER:-  $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

The example below shows how to use some of the elements in $_SERVER:
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>

3.$_REQUEST:-  PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an HTML form.

The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to this file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_REQUEST to collect the value of the input field:
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="fname">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_REQUEST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>

</body>
</html>

4. $_POST:- PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables.

The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to the file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_POST to collect the value of the input field:
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="fname">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_POST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>

</body>
</html>

5.$_GET:- PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get".

$_GET can also collect data sent in the URL.

Assume we have an HTML page that contains a hyperlink with parameters:

<html>
<body>

<a href="test_get.php?subject=PHP&web=Secretmind.cf">Test $GET</a>

</body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to "test_get.php", and you can then access their values in "test_get.php" with $_GET.

The example below shows the code in "test_get.php":
<html>
<body>

<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>

</body>
</html>

6.$_FILES:- $_FILES is a super global variable which can be used to upload files. Here we will see an example in which our php script checks if the form to upload the file is being submitted and generates a message if true.

Here is the html code (upload.php):
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Code of files.php file:

<?php
if ($_FILES["file"] > 0)
  {
  echo "You have selected a file to upload";
  }
?>

7.$_ENV:- $_ENV is used to return the environment variables from the web server.
<?php
echo $_ENV['username'];
?>

8.$_COOKIE:- Cookies are small text files loaded from a server to a client computer storing some information regarding the client computer, so that when the same page from the server is visited by the user, necessary information can be collected from the cookie itself, decreasing the latency to open the page.

$_COOKIE retrieves those cookies.

<?php
setrawcookie();
print_r($_COOKIE);
?>

9.$_SESSION:- Sessions are wonderful ways to pass variables. All you need to do is start a session by session_start();Then all the variables you store within a $_SESSION, you can access it from anywhere on the server. Here is an example:  

Example of $_SESSION

<?php
session_start();
$_SESSION['Secretmind']='The largest online tutorial';
echo $_SESSION['Secretmind'];
?>

4.What are the differences between session and cookie?
Ans:
The session is a global variable which is used in the server to store the session data. When a new session creates the cookie with the session id is stored on the visitor's computer. The session variable can store more data than the cookie variable.

Session data are stored in a $_SESSION array and Cookie data are stored in a $_COOKIE array. Session values are removed automatically when the visitor closes the browser and cookie values are not removed automatically.

5.Which functions are used to remove whitespaces from the string?
Ans: There are three functions in PHP to remove the whitespaces from the string.

trim() – It removes whitespaces from the left and right side of the string.
ltrim() – It removes whitespaces from the from the left side of the string.
rtrim() – It removes whitespaces from the from the right side of the string.

6.what is PHP array ? And what are the different between Index array and associative array?
Ans: A PHP array is a variable that stores more than one piece of related data in a single variable.

Index array
There are two ways to create indexed arrays.

  • first way to use array() function without any index, index are assigned automatically starting from 0.
  • second way to manually assign index and create the array.


PHP count() function is used to get the length of an array. We can use for loop to loop through all the values of an indexed array.

Below code shows both the ways to create an indexed array and loop through them in PHP.

<?php
$colors = array("Red","Green","Blue");

$colors1[0] = "Red";
$colors1[1] = "Green";

$length = count($colors);
echo "colors array length=" . $length; // prints "colors array length=3"
echo "<br>";
echo "colors1 array length=" . count($colors1); // prints "colors1 array length=2"

//looping an indexed array
for($i=0; $i<$length; $i++){
echo $colors[$i];
echo "<br>";
}
?>

Associative array
Associative arrays uses named keys for values and we can create them in similar way like indexed arrays. foreach is used to loop through an associative array.


<?php

$colors = array("0"=>"Red","1"=>"Green","2"=>"Blue");

echo "0th element of array is " . $colors["0"];
echo "<br>";
//looping
foreach ($colors as $key=>$value){
echo "Key=".$key." value=".$value;
echo "<br>";
}
?> 

7.What is cookie? Expain creation, modification and distrotion(Expiration of cookie).
Ans: Cookies are small text files loaded from a server to a client computer storing some information regarding the client computer, so that when the same page from the server is visited by the user, necessary information can be collected from the cookie itself, decreasing the latency to open the page.

PHP create or retrieve a cookie:-
The following example creates a cookie name "user" with the value "Aman".
The cookie will expire after 30 days(86400*30).The "/" means that the cookie is available in the entire website.
Than we retrieve the value of the cookie "user" (using the GLOBAL variable $COOKIE).Be also use the isset() function to find out it the cookies set.

<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "Aman Gupta";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
     echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
     echo "Cookie '" . $cookie_name . "' is set!<br>";
     echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

<p><strong>Note:</strong> You might have to reload the page to see the value of the cookie.</p>

</body>
</html>



Modify a Cookie Value:
To modify a cookie, just set (again) the cookie using the setcookie() function:

Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
    echo "Cookie '" . $cookie_name . "' is set!<br>";
    echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

Delete a Cookie:
To delete a cookie, use the setcookie() function with an expiration date in the past:

Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>

8.What is session ? Explain briefly it's start to end.
Ans:  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.

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
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$_SESSION["favcolor"]="red";
$_SESSION["facanimal"]="cat";
echo "session variable are set";
?>
</body>
</html>

Start a PHP Session:
A session is started with the session_start() function.

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

Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some session variables:

Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

9.Different between scripting and programming languages.
Ans:
Scripting language:-

Scripting languages, as the name suggests, is a programming language that supports scripts. A scripting language binds a set of software components that collaborate to solve a particular problem. Scripting assumes the existence of powerful components and provides the means to connect them together. Scripting languages are glue languages that integrate the execution of system utilities including compilers; command line interpretation; shell-based programming; and execution of codes written in web-based languages. The purpose of a scripting language is the development of applications by plugging existing components together and they generally favor high-level programming over execution speed. Scripting is used in a variety of applications, and scripting languages are correspondingly diverse. Python is a powerful scripting language for complex system involving operating system, networks, and web-based programming.

programming language:-

A programming language is an organized way of communicating with a computer, such that the computer behaves according to the instructions given by the programmer. A programming language is an artificial formalism in which algorithms can be expressed. In the modern era, the problems to be solved by computers lie in different problem domains such as scientific computing, database programming, business applications, process automation, and web-based applications. All these domains are quite different with varied requirements. A programming language is a specific set of instructions given to a computer in a language that the computer understands to perform specific tasks. Today’s programming languages are the product of development that started in the 1950s. The term programming languages usually refer to high-level languages such as C++, Java, Ada, Pascal, and FORTRAN.

Aman gupta


10.What do you mean by procedural programming structure and object oriented programming structure ?
Ans:
Aman gupta

11.Explain include and require with example.
Ans:-
INCLUDE()REQUIRE()
include() function takes one argument , a path/name of the specified file you want to include.require() function performs the similar functionality as include() function, takes one argument i.e. path/name of the file you want to include.
Syntax :
include(File-name);
Example :
include (“header.php”).
Syntax :
require(File-name);
Example :
require(“header.php”);
include() function does not stop execution , just give warning and continues to execute the script in case of file name not found i..e missing/misnamed files .require() function gives fatal error if it founds any problem like file not found or misnamed files and stops the execution once get fatal error.
include() function can be used in loops or control structure.require() function can not be used in loops or control structures.
You can return a value from an included file
Ex:
$result = include ‘rtnvalue.php’;
File included as the result of a require statement cannot return a value.
You can use include when file is not required or not so important .When file is required by the script, better to use require() instead of include().
The include() function:

This function is used to copy all the contents of a file called within the function, text wise into a file from which it is called. This happens before the server exceutes the code. Example:
Lets have a file called even.php with the following code:

<?php 
// file to be included 
echo "Hello Secret mind"
?> 

Now let us try to include this file into another php file index.php file. We will see that the contents of both the file are shown.

<?php  
    include("even.php"); 
    echo "<br>Above File is Included"
?> 

The require() function:

The require() function performs same as the include() function. It also takes the file that is required and copies the whole code into the file from where the require() function is called. There is a single difference between the include() and require() function which we will see following this example:
Lets have a file called even.php with the following code:
<?php 
// file to be included 
echo "Hello GeeksforGeeks"
?> 

Now if we try to include this file using require() function this file into a web page we need to use a index.php file. We will see that the contents of both the file are shown.

<?php  
    require("even.php"); 
    echo "<br>Above File is Required"
?> 


12.Write a program of form validation from server site scripting.
Ans:
<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed";
    }
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
    }
  }
    
  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL";
    }
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  Name: <input type="text" name="name" value="<?php echo $name;?>">
  <span class="error">* <?php echo $nameErr;?></span>
  <br><br>
  E-mail: <input type="text" name="email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
  Website: <input type="text" name="website" value="<?php echo $website;?>">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
  Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other  
  <span class="error">* <?php echo $genderErr;?></span>
  <br><br>
  <input type="submit" name="submit" value="Submit">  
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>


13. Different between == and === .
Ans: Coming soon.





 

  • 1
  • 2
  • 3
  • 4
  • 5



  • 2 comments:

    Please do not enter any spam link in the comment box.