PHP Interview Questions & Answers for Freshers
PHP interview questions for freshers: what PHP is, data types, variables, operators, strings, arrays, include vs require, GET vs POST, cookies, sessions and file basics.
What is the use of substr_count() in PHP?
The substr_count() function counts how many times a small text (substring) is found in a bigger string.
<?php
echo substr_count("hello world, hello PHP", "hello") . "<br>";
// Overlapping matches are not counted twice
echo substr_count("aaa", "aa");
?>
Output:
2
1
- It is case-sensitive. “Hello” and “hello” are different.
- It does not count overlapping matches.
- To count the words of a string use
str_word_count(), and to count array elements usecount().
What is the use of strip_tags() in PHP?
The strip_tags() function removes HTML and PHP tags from a string. Only the tags are removed, the text inside them stays.
<?php
echo strip_tags("<b>Hello</b> <i>PHP</i>");
?>
Output:
Hello PHP
You can keep some tags by passing them as second parameter. Here we allow only the bold tag, and we use htmlspecialchars() just to show the HTML code as text.
<?php
$text = "<p><b>Hello</b> <i>PHP</i></p>";
echo htmlspecialchars(strip_tags($text, "<b>"));
?>
Output:
<b>Hello</b> PHP
What is the difference between strstr() and stristr() in PHP?
Both functions find the first match of a text inside a string and return the part of the string from that match to the end. The difference is that strstr() is case-sensitive, and stristr() is case-insensitive (it ignores upper or lower case).
<?php
$email = "sonia@example.com";
echo strstr($email, "@") . "<br>";
echo strstr($email, "@", true) . "<br>";
var_dump(strstr("Hello World", "world"));
echo stristr("Hello World", "world");
?>
Output:
@example.com
sonia
bool(false)
World
The third parameter true returns the part before the match. If there is no match, both functions return false. When you only want to know if a text exists, str_contains() is simpler.
What is the maximum file size we can upload using PHP? How to increase it?
By default PHP allows files up to 2 MB. This limit is set by the upload_max_filesize setting. You can increase it in the php.ini file.
upload_max_filesize = 15M
post_max_size = 20M
memory_limit = 128M
You need to change post_max_size also. It is the limit for the whole form data (the file plus other fields), so it must be bigger than upload_max_filesize. If it is smaller, the upload fails without a clear error and $_FILES stays empty.
You can check the current values with ini_get().
<?php
echo ini_get("upload_max_filesize") . "<br>";
echo ini_get("post_max_size");
?>
Output:
2M
8M
Also read PHP File Upload and the safe upload rules in PHP Security Tips.
How to get the previous page (referrer) URL in PHP?
Use $_SERVER["HTTP_REFERER"]. It has the address of the page from which the visitor came to the current page. Note that the spelling is “REFERER” (one R is missing), because of an old mistake in the HTTP standard.
<?php
$ref = $_SERVER["HTTP_REFERER"] ?? "No referrer";
echo $ref;
?>
Output:
The value can be missing or empty, so always use ?? like in the example. It is sent by the browser, so it is not reliable. Never use it alone for security checks, use a CSRF token instead (see PHP Security Tips).
How to get the IP address of a visitor in PHP?
Use $_SERVER["REMOTE_ADDR"]. It has the IP address of the client that connected to your server.
<?php
$ip = $_SERVER["REMOTE_ADDR"];
echo "Your IP: " . $ip;
?>
Output:
Your IP: 203.0.113.25
If your website is behind a proxy, load balancer or a service like Cloudflare, REMOTE_ADDR shows the IP of that proxy. The real visitor IP is then sent in a header like HTTP_X_FORWARDED_FOR.
What are the reasons for using the LAMP stack for PHP development?
LAMP is a group of free and open-source software used together to run websites. The name comes from the first letter of each software.
| Letter | Software | Job |
|---|---|---|
| L | Linux | Operating system of the server |
| A | Apache | Web server that sends pages to the browser |
| M | MySQL (or MariaDB) | Database to store the data |
| P | PHP | Language that makes the pages dynamic |
Why it is popular:
- Free: all four parts are open source, so there is no license cost.
- Easy hosting: almost every shared hosting provider offers LAMP, and it is cheap.
- Big community: you can find tutorials, help and ready-made tools for each part.
- Works with popular software: WordPress, Joomla, Drupal and many other CMS run on LAMP.
- Flexible and stable: you can change any part, and the stack is proven for many years.
Some variations: LEMP uses Nginx in place of Apache. On your own computer you can use XAMPP or WAMP to get the same stack for learning. Note that other stacks are also good, so choose by the needs of your project.
What is the use of the header() function in PHP?
The header() function sends a raw HTTP header to the browser, before the page content. With headers you can give instructions to the browser.
Common uses of header():
- Redirect the user to another page (
Locationheader). - Tell the type of response, like JSON (
Content-Typeheader). - Force a file download (
Content-Dispositionheader). - Control browser cache (
Cache-Controlheader). - Set the HTTP status code, for example 404 or 301.
<?php
header("Content-Type: application/json");
echo json_encode(["status" => "ok"]);
?>
Output:
{“status”:”ok”}
What is .htaccess and why do we use it?
.htaccess (hypertext access) is a configuration file of the Apache web server. You can put it in any folder of your website, and the rules inside it apply to that folder and its sub-folders. The big benefit is that you can change server settings without touching the main server configuration.
Common uses of .htaccess:
- Redirect pages and force HTTPS
- Block or allow access to files and folders
- Password protect a directory
- Show custom error pages (404, 500)
- Enable browser caching to make the site faster
- Add security rules and hide the directory list
# Stop showing the list of files of a folder
Options -Indexes
How to run a PHP script from the command line?
Open the terminal and use the php command (PHP CLI) with the file name. You do not need a web server for this.
php hello.php
Here is the script. The values you type after the file name are available in the $argv array. The first item, $argv[0], is the file name.
<?php
echo "Hello " . ($argv[1] ?? "World") . PHP_EOL;
?>
Now run the command with a name:
php hello.php Robin
Output:
Hello Robin
Some more useful commands:
| Command | What it does |
|---|---|
php -v | Shows the PHP version |
php -r "echo 2+2;" | Runs a small piece of code directly |
php -l file.php | Checks the file for syntax errors |
php -m | Lists the installed PHP modules |
php -S localhost:8000 | Starts the built-in web server for testing |
The older form php -f file.php also works and gives the same result.
How to store passwords securely in PHP?
Never save the real password. Save a hash of it. In PHP use password_hash() to create the hash and password_verify() to check a password at login.
<?php
$password = "MySecret@123";
// Save this hash in the database
$hash = password_hash($password, PASSWORD_DEFAULT);
// At login, compare the typed password with the saved hash
var_dump(password_verify("MySecret@123", $hash));
var_dump(password_verify("wrong-password", $hash));
?>
Output:
bool(true)
bool(false)
- Do not use
md5()orsha1()for passwords. They are very fast, so attackers can try billions of guesses per second. - password_hash() adds a random salt itself, you do not need to create one.
- The hash can be long, so use a
VARCHAR(255)column. - Use
password_needs_rehash()to upgrade old hashes when PHP changes the default algorithm.
Related: PHP Security Tips.
What is the difference between isset(), empty() and is_null() in PHP?
All three check a variable, but in different ways.
- isset() is true when the variable exists and is not NULL.
- empty() is true when the variable does not exist or has a false-like value (0, “”, “0”, NULL, false, []).
- is_null() is true only when the value is NULL (and it gives a warning for an undefined variable).
| Value | isset() | empty() | is_null() |
|---|---|---|---|
| NULL | false | true | true |
| 0 | true | true | false |
| “” (empty string) | true | true | false |
| “Hello” | true | false | false |
| Undefined variable | false | true | true (with warning) |
<?php
$a = null;
$b = 0;
$c = "Hello";
var_dump(isset($a), empty($a), is_null($a));
var_dump(isset($b), empty($b), is_null($b));
var_dump(isset($c), empty($c), is_null($c));
?>
Output:
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(false)
Each group of three lines is for one variable: $a, $b and $c. Read the full chapters: isset(), empty() and is_null().
What is the difference between explode() and implode() in PHP?
explode() breaks a string into an array. implode() joins the elements of an array into a string. They do opposite work.
| explode() | implode() |
|---|---|
| String to array | Array to string |
explode(separator, string) | implode(separator, array) |
| Splits at every separator | Puts the separator between elements |
<?php
$text = "apple,banana,cherry";
$fruits = explode(",", $text);
print_r($fruits);
echo implode(" - ", $fruits);
?>
Output:
Array
(
[0] => apple
[1] => banana
[2] => cherry
)
apple – banana – cherry
Learn more in PHP explode() Function and PHP implode() Function.
What are superglobals in PHP?
Superglobals are built-in variables that PHP creates by itself. They are available in every place of your script (inside functions and classes also), and you do not need the global keyword to use them.
| Superglobal | Use |
|---|---|
$_GET | Data sent in the URL |
$_POST | Data sent by a form using the POST method |
$_REQUEST | Data of GET, POST and cookies together |
$_SESSION | Session data of the current user |
$_COOKIE | Cookies sent by the browser |
$_FILES | Details of uploaded files |
$_SERVER | Server and request information, like the method and IP address |
$_ENV | Environment variables |
$GLOBALS | Access to the global variables |
<?php
echo $_SERVER["REQUEST_METHOD"];
?>
Output:
GET
- « Previous
- 1
- 2
- 3
- 4