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:

Tutorials Class - Output Window

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 use count().

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:

Tutorials Class - Output Window

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:

Tutorials Class - Output Window

<b>Hello</b> PHP

Note: strip_tags() is not a full protection for XSS. The text inside a script tag stays as text, and attributes of allowed tags are not checked. To print user data safely use htmlspecialchars(), see PHP Security Tips.

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:

Tutorials Class - Output Window

@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:

Default values

2M
8M

Note: You can not change upload_max_filesize with ini_set() inside the script. Change it in php.ini, in a .user.ini file, or ask your hosting provider. Also check the limit of your web server (for Nginx it is client_max_body_size).

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:

Tutorials Class - Output Window

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:

Sample output, yours will be different

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.

Note: Headers like X-Forwarded-For can be faked by the visitor. Trust them only when your own proxy sets them. Also remember that an IP address is personal data in some countries, so store it only when you need it.

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.

LetterSoftwareJob
LLinuxOperating system of the server
AApacheWeb server that sends pages to the browser
MMySQL (or MariaDB)Database to store the data
PPHPLanguage 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 (Location header).
  • Tell the type of response, like JSON (Content-Type header).
  • Force a file download (Content-Disposition header).
  • Control browser cache (Cache-Control header).
  • Set the HTTP status code, for example 404 or 301.
<?php
header("Content-Type: application/json");

echo json_encode(["status" => "ok"]);
?>

Output:

Tutorials Class - Output Window

{“status”:”ok”}

Note: header() must be called before any output, even a blank space. Otherwise PHP shows the “headers already sent” warning. Full details and more examples are in PHP header() Function.

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:

# Stop showing the list of files of a folder
Options -Indexes
Note: .htaccess works only on Apache (and compatible servers like LiteSpeed). Nginx does not read it. A wrong rule can break your site with a 500 error, so always take a backup of the file before you edit it.

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:

Tutorials Class - Output Window

Hello Robin

Some more useful commands:

CommandWhat it does
php -vShows the PHP version
php -r "echo 2+2;"Runs a small piece of code directly
php -l file.phpChecks the file for syntax errors
php -mLists the installed PHP modules
php -S localhost:8000Starts 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:

Tutorials Class - Output Window

bool(true)
bool(false)

  • Do not use md5() or sha1() 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).
Valueisset()empty()is_null()
NULLfalsetruetrue
0truetruefalse
“” (empty string)truetruefalse
“Hello”truefalsefalse
Undefined variablefalsetruetrue (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:

Tutorials Class - Output Window

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 arrayArray to string
explode(separator, string)implode(separator, array)
Splits at every separatorPuts the separator between elements
<?php
$text = "apple,banana,cherry";

$fruits = explode(",", $text);
print_r($fruits);

echo implode(" - ", $fruits);
?>

Output:

Tutorials Class - Output Window

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.

SuperglobalUse
$_GETData sent in the URL
$_POSTData sent by a form using the POST method
$_REQUESTData of GET, POST and cookies together
$_SESSIONSession data of the current user
$_COOKIECookies sent by the browser
$_FILESDetails of uploaded files
$_SERVERServer and request information, like the method and IP address
$_ENVEnvironment variables
$GLOBALSAccess to the global variables
<?php
echo $_SERVER["REQUEST_METHOD"];
?>

Output:

When the page is opened normally in the browser

GET

Note: All the data in $_GET, $_POST and $_COOKIE comes from the visitor, so never trust it. Validate it and escape it before use. See PHP Forms Handling.