
PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language.
- Created by Rasmus Lerdorf
- Year 1994
- PHP (Originally) Called Personal Home Page
- PHP (Now) Called PHP: Hypertext Preprocessor
It is used to print a data in the webpage
Following are the built-in variables that are always available in all scopes, called "superglobals" in PHP.
- $GLOBALS
- $_SERVER
- $_GET
- $_POST
- $_REQUEST
- $_SESSION
- $_COOKIE
- $_FILES
- $_ENV
- Notices: As the name says, Notices are errors which occur while you may not initialize variable or any other things. This will generate only notice on the view page. This will not terminate the running script.
- Warnings: This is run-time warnings and does not terminate the script execution. This error mostly occurs when you forgot to
include ()
a file. - Fatal Errors:These are most critical error of the PHP. It can terminate your script. Example of this error is forgotten to semicolon (;) in the script. another example of a Fatal error would be accessing a property of a non-existent object or require() a non-existent file
- error_reporting(E_ALL);
- ini_set(‘display_errors’, 1);
You may also like: OOPS Interview Questions and Answers
- Session: A session is a way to store data on the web-server. You can use session variables throughout all pages of your application. Normally session will destroy when you close the browser.
- Cookie: A Cookies is a way to store data on the user’s computer. It is mostly used for identify user. You can set cookies, get cookies or delete cookies by php functions.
Sr.No | Session | Cookie |
1 | Sessions are small files that are stored on the website's server. in other words Sessions are server-side files that contain user information | Cookies are small files that are stored in the visitor's browser. in other words Cookies are client-side files that contain user information |
2 | Sessions have a limited lifespan; they expire when the browser is closed. | Cookies can have a long lifespan, lasting months or even years. |
3 | Sessions are only limited in size if you limit their size on the server. | Cookies are limited in size depending on each browser's default settings. |
4 | Sessions cannot be disabled by the visitor because they are not stored in the browser. | Cookies can be disabled if the visitor's browser does not allow them (uncommon). |
5 | Sessions cannot be edited by the visitor. | Cookies can be edited by the visitor. (Do not use cookies to store sensitive data.) |
6 | Safe | Not very safe |
7 | In php $_SESSION super global variable is used to manage session. | In php $_COOKIE super global variable is used to manage cookie. |
8 | You can store as much data as you like within in sessions.The only limits you can reach is the maximum memory a script can consume at one time, which by default is 128MB. php.ini, memory_limit = 128M | Official MAX Cookie size is 4KB |
9 | Before using $_SESSION, you have to write session_start(); In that way session will start and you can access $_SESSION variable on that page.To avoid header already sent issue use ob_start(); on top of script | You don't need to start Cookie as It is stored in your local machine. |
Yes, session will work when cookies is disabled. In PHP, Sessions use cookies. By default the sessionid stores in Cookies.
This is most frequently asked interview question related to session and cookies
- Form -Hidden Input
- In URL using Query String
- Cookies - recommended
- Form - not recommended
- URL parameter - A major disadvantage it is not safe and may be cause of session hijacking.
Note- Following config seeting should be taken care of (php.ini)
- session.use_cookies=1
- session.use_only_cookies=1
- session.use_trans_sid=0
using header() funtion
#Example:you should use die() or exit() after header() function
header("Location: http://www.fullstacktutorials.com/contact.html");
die();
Note: header() redirects only work before anything is written out.
You may also like: React Js Interview Questions and Answers
GET
and POST
are two most popular HTTP methods normally uses for send data from one page to another page.
Key | GET | POST |
---|---|---|
Bookmarked | Can be bookmarked | Cannot be bookmarked |
Cached | Can be cached | Not cached |
Encoding | application/x-www-form-urlencoded | application/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data |
History | Parameters remain in browser history | Parameters are not saved in browser history |
Data length | Yes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters) | No restrictions |
Data type | Only ASCII characters allowed | No restrictions. Binary data is also allowed |
BACK button/Reload | Harmless | Data will be re-submitted (the browser should alert the user that the data are about to be re-submitted) |
Security | GET is less secure compared to POST because data sent is part of the URL Never use GET when sending passwords or other sensitive information! |
POST is a little safer than GET because the parameters are not stored in browser history or in web server logs |
Visibility | Data is visible to everyone in the URL | Data is not displayed in the URL |
isset(): checks if a variable has a value including ( False , 0 , or empty string) , but not NULL. Returns TRUE if var exists; FALSE otherwise.
empty(): function checks if the variable has an empty value empty string , 0, NULL ,or False. Returns FALSE if var has a non-empty and non-zero value."
$_SESSION
to retrieve session variables.
destroy($_SESSION);
or unset($_SESSION['VARIABLE_NAME'])
;
We can include a file using "include()" or "require()" function with file path as its parameter.
- include() will attempt to load the specified file, but will allow the script to continue if not successfully loaded.
- require(), on the other hand will cause a “Fatal Error” to occur if the specified file is not successfully loaded.
The only difference between the two is that require and require_once throw a fatal error if the file is not found, whereas include and include_once only show a warning and continue to load the rest of the page.
explode() function convert a string into an array, while implode() function convert an array into string.
- count($array)
- sizeof($array)
array_merge() - merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one.
Note - If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.array_combine() - creates an array by using one array as keys and another array as its values.
Note - Both array must have same number of elements.
- For loop
- Foreach loop
- While loop
- Do…While loop
You may also like: Node Js Interview Questions and Answers
- explode(): Convert string to Array
- implode(): Convert Array to string
print_r($array);
function to print array.
rand()
function to generate random number
- sort() – sort arrays in ascending order
- rsort() – sort arrays in descending order
- asort() – sort associative arrays in ascending order, according to the value
- ksort() – sort associative arrays in ascending order, according to the key
- arsort() – sort associative arrays in descending order, according to the value
- krsort() – sort associative arrays in descending order, according to the key
password_hash() – it uses a strong hash, generates a strong salt, and applies proper rounds automatically.
md5() – Note that md5() is not secure now days. Please take care.
bcrypt() – The salt
parameter is optional. However, crypt() creates a weak password without the salt
.
$var (single dollar) is a normal variable with the name var that stores any type of value like string, integer, float, etc.
$$var (double dollar) is a reference variable that stores the value of the $var inside it.
"=="
checks the left and right values are equal or not whether "==="
check the left and right values are equal with their data types (e.g. int, float etc)
unset(array_element)
function to delete array.
var_dump();
array_filter();
array_chunk()
is used to split array element in group of small arrays.
array_sum()
function is used to get total sum of array elements.
array_unique()
function to get unique values.
== and === both are comparison operator and using to check values.
== it check only values and return true if values are same.
=== it check value with it's datatype and return true if both value and datatype are same.
Since PHP is scripting language so when script code gets parsed line by line PHP parser sent output to browser
if you will put ob_start(); at top of your script code it will tell the PHP parser to send the data to the browser at once when full code get parsed.
You may also like: Top 50 Laravel Interview Questions
The Magic methods always start with double underscore "__" and Magic methods are member functions that are available to all the instance of class.
The Magic Methods are:
- __call()
- __toString()
- __sleep()
- __wakeup()
- __isset()
- __unset()
- __autoload()
- __clone()
- __construct()
- __destruct()
- __set()
- __get()
You may also like: MySQL Interview Questions and Answers
PSRs are PHP Standards Recommendations that aim at standardising common aspects of PHP Development.
An example of a PSR is PSR-4, This PSR describes a specification for autoloading classes from file paths
Composer have the following advantages:
- The dependencies required by the package you are pulling in are automatically taken care by Composer itself, leaving you free to focus on the programming instead of dependency management
- When the package you are using gets a new version, a simple composer update will do everything for you, without ever needing to do any file management manually
- With Composer you get a centralized autoload.php file which also is optimized with Composer. It loads everything you need and all you do is include one file.
- You can use psr-4 namespaces to load a specific path on your application and have it be included in the autoloader file. Then you can simply use the namespace and its available application wise!
One way to detect an AJAX request is by using the following PHP code:
You may also like: MongoDB Interview Questions
SQL injection is a malicious code injection technique. It exploiting SQL vulnerabilities in Web applications
By changing max_execution_time either in php.ini config file OR in code using ini_set
"; $a = $a+$b; $b = $a-$b; $a = $a-$b; echo "New values of a and b are $a, $b
"; //Output //Old values of a and b are 5, 10 //New values of a and b are 10, 5
"; } } } printPrimeNo(100); //print all prime numbers from 1-100
Fibonacci series A series of numbers in which each number is the sum of the two preceding numbers.
A simple of Fibonacci series is 0, 1, 1, 2, 3, 5, 8, etc.
"; //Output //PHPINTERVIEWQUESTIONS //First Method, Using PHP Inbuilt function echo strrev($input)."
"; //Output //SNOITSEUQWEIVRETNIPHP //Second Method for($i=1;$i<=strlen($input); $i++){ $data = substr($input, -$i, 1); $output .= $data; } echo $output; //Output //SNOITSEUQWEIVRETNIPHP
"; } $n = 1; echo callByValue($n); /* Output 2 */ echo $n; /* Output 1 */ //Output /* 2 1 */ echo "
"; //Call by Reference in PHP //In call by reference, the address of a variable (their memory location) is passed. In the case of call by reference, we prepend an ampersand (&) to the argument name in the function definition. Any change in variable value within a function can reflect the change in the original value of a variable which we have shown in the following Example. function callByReference(&$num) { $num = $num + 1; return $num."
"; } $n = 1; echo callByReference($n); /* Output 2 */ echo $n; /* Output 2 */ //Output /* 2 2 */