1. Which superglobal provides information about headers, paths, and script locations?
$_SERVER contains server and execution environment information like REQUEST_METHOD, PHP_SELF, and SERVER_NAME.
echo $_SERVER['PHP_SELF'];
Get the Preplance app for a seamless learning experience. Practice offline, get daily streaks, and stay ahead with real-time interview updates.
Get it on
Google Play
4.9/5 Rating on Store
Wipro · PHP
Practice PHP questions specifically asked in Wipro interviews – ideal for online test preparation, technical rounds and final HR discussions.
Questions
76
Tagged for this company + subject
Company
Wipro
View company-wise questions
Subject
PHP
Explore topic-wise practice
Go through each question and its explanation. Use this page for targeted revision just before your Wipro PHP round.
$_SERVER contains server and execution environment information like REQUEST_METHOD, PHP_SELF, and SERVER_NAME.
echo $_SERVER['PHP_SELF'];
For complete preparation, combine this company + subject page with full company-wise practice and subject-wise practice. You can also explore other companies and topics from the links below.
The count() function returns the number of elements in an array or object implementing Countable.
count($arr);
implode() joins array elements into a string, and explode() splits a string into an array based on a delimiter.
$s = implode(',', $arr); $a = explode(',', $s);When a cookie is set with an expiry time in the past, the browser automatically removes it from storage, effectively deleting it.
setcookie('user','',time()-3600);file_put_contents writes data to a file in one call. If the file does not exist, it creates it automatically.
file_put_contents('info.txt','Hello World');PDO stands for PHP Data Object. It provides a database abstraction layer that works with many database systems like MySQL, SQLite, and PostgreSQL.
$pdo = new PDO('mysql:host=localhost;dbname=test','root','pass');PHP’s garbage collector automatically frees memory by removing objects and variables that are no longer referenced, improving efficiency.
gc_collect_cycles();
The nullsafe operator prevents runtime errors when accessing methods or properties on null objects by returning null instead of throwing an error.
$user?->getProfile()?->getName();
The str_contains function returns true if one string is found within another. It replaces the need for using strpos with manual comparison.
str_contains('Hello World','World');All web routes that respond to HTTP requests in Laravel are typically defined in the routes/web.php file using simple route definitions.
Route::get('/home', [HomeController::class, 'index']);Each number in the Fibonacci sequence is the sum of the two preceding ones. After 5 comes 8 (3 + 5).
The modulus operator (%) checks the remainder of division. If number % 2 equals zero, the number is even; otherwise, it's odd.
if($num % 2 == 0) echo 'Even';
If mysqli_connect fails, it returns false. You can check this and display an error using mysqli_connect_error.
if(!$conn){ echo mysqli_connect_error(); }In PHP, the 'extends' keyword allows one class to inherit properties and methods from another class. Example: class ParentClass {} class ChildClass extends ParentClass {}
class Vehicle {}
class Car extends Vehicle {}The break statement stops execution of the current case in a switch block. Without it, PHP continues to the next case.
switch($day){ case 'Mon': echo 'Work'; break; }The error_reporting() function sets which levels of errors PHP reports. For example, error_reporting(E_ALL) enables all errors.
error_reporting(E_ALL);
Constructor property promotion simplifies class definitions by allowing properties to be defined and assigned directly in the constructor parameter list.
class User { function __construct(public string $name, private int $age){} }The error_log() function sends error messages to a log file or email for debugging without displaying them to users.
error_log('Database connection failed');The $_SESSION superglobal holds data for the current session, allowing values to be shared across different pages for the same user.
$_SESSION['user'] = 'John';
trigger_error() allows you to create custom warning or notice messages in PHP code. Useful for debugging or enforcing logic.
trigger_error('Invalid input', E_USER_WARNING);The $_COOKIE superglobal is used to access cookie values that have been sent from the browser back to the server.
echo $_COOKIE['user'];
The __construct() method is called automatically when a class object is created. It is used to initialize values. Example: class Car { function __construct(){ echo 'Car ready'; } }
class Car {
function __construct(){ echo 'Object created'; }
}The GET method appends form data to the URL, making it visible in the address bar. It is used for non-sensitive data requests.
The $_FILES array stores information about uploaded files like name, type, size, and temporary location.
echo $_FILES['myfile']['name'];
setcookie() is used to send a cookie from the server to the client. Cookies store small data on the user's browser.
setcookie('user','John',time()+3600);The count function returns the total number of elements in an array or the number of properties in an object.
count([1,2,3,4]); // 4
A palindrome string remains the same when reversed, such as level or madam. Checking this is a common PHP coding test question.
The array_sum function adds up all numeric elements of an array and returns the total.
array_sum([2,4,6]); // 12
Static properties and methods belong to the class itself, not to instances. You can access them using ClassName::method().
class Math { static $pi=3.14; static function add($a,$b){ return $a+$b; } }
echo Math::$pi;$this refers to the current object instance inside a class. It is used to access class properties or methods of that object.
class User { public $name; function say(){ echo $this->name; } }A for loop includes three expressions: initialization, condition, and increment or decrement.
for($i=0; $i<5; $i++){ echo $i; }A while loop checks the condition first, then executes the body. A do-while loop executes once before checking.
while($x < 5){ echo $x; $x++; }Traits allow code reusability in multiple classes. They provide a way to use common methods across unrelated classes.
trait Logger { function log(){ echo 'Logging...'; } }
class App { use Logger; }The mysqli_query function sends a query to the MySQL server and returns a result object for SELECT or true for successful INSERT, UPDATE, or DELETE operations.
$result = mysqli_query($conn,'SELECT * FROM users');
The foreach loop is made for iterating arrays. It can loop through both keys and values easily.
foreach($arr as $val){ echo $val; }Prepared statements increase performance by precompiling SQL and prevent SQL injection by separating query structure from user data.
$stmt = $pdo->prepare('SELECT * FROM users WHERE id=?');If a function has no return statement, PHP automatically returns null. This is common for functions that only print or modify data.
function test(){} $x = test(); // nullarray_key_exists() checks if a key exists in an array. isset() also works but returns false for null values.
array_key_exists('name', $user);substr() extracts part of a string from a start position and optional length.
substr('Hello',1,3); // ellArrays can be created using the array() function or square brackets from PHP 5.4 onward.
$a = array(1,2,3); $b = [1,2,3];
PHP originally stood for Personal Home Page, but now it means PHP Hypertext Preprocessor. It is a recursive acronym and used mainly for server-side scripting.
PHP allows single-line comments using double slashes or a hash. Multiline comments use slash star and star slash.
// comment or # comment
The echo statement outputs text or variables. It is faster than print and can take multiple arguments.
echo 'Hello World';
PHP variable names are case-sensitive. $Name and $name are different variables. However, function names are not case-sensitive.
define() is used to create a constant that cannot be changed once declared. Example: define('PI', 3.14).
define('PI', 3.14);The dot operator in PHP is used for string concatenation, not addition. 10 dot 5 results in '105'.
$result = 10 . 5; // gives 105
The throw keyword is used to manually generate an exception in PHP. It is followed by an Exception object.
throw new Exception('Invalid input');The Exception class is the base for all exceptions. You can create your own exceptions by extending it.
class MyError extends Exception {}Custom exceptions are created by extending PHP’s built-in Exception class and overriding its methods if needed.
class MyException extends Exception { }Using mode 'a' opens the file for writing at the end. The pointer moves to the end and preserves existing content.
fopen('log.txt','a');The fwrite function is used to write data to an open file. If the file is not writable, it returns false.
fwrite($handle,'Hello');
file_get_contents reads the entire file content into a single string, making it a simple way to load small files.
$data = file_get_contents('info.txt');The unlink function deletes a file from the file system. It returns true on success or false on failure.
unlink('old.txt');By default, PHP stores session data as temporary files on the server in a directory defined by the session.save_path configuration in php.ini.
The json_encode function converts PHP data structures like arrays or objects into JSON strings, which can be sent over APIs or stored easily.
json_encode($data);
The PUT method is used to update or replace an existing resource on the server. It is idempotent, meaning multiple identical requests produce the same result.
cURL is a PHP library used to send and receive HTTP requests. It helps in communicating with APIs, external services, and web servers programmatically.
$ch = curl_init('https://api.example.com');The Content-Type header tells the browser how to interpret the response data, such as text/html or application/json.
header('Content-Type: application/json');Autoloading allows PHP to automatically include the required class file when an object is created. It removes the need for manual include statements.
spl_autoload_register(function($class){ include $class.'.php'; });Composer is PHP’s dependency manager. It automatically downloads and installs external libraries and manages their versions for your project.
composer install
The memory_limit directive in php.ini defines the maximum amount of memory a single PHP script can use, preventing memory overflows.
ini_set('memory_limit','256M');Xdebug is a PHP extension used for debugging and profiling. It helps developers analyze script execution time and memory usage for performance optimization.
Union types let you declare that a parameter or return value can accept multiple types, such as int or float. It improves type safety and flexibility.
function sum(int|float $a, int|float $b){ return $a+$b; }Named arguments allow passing arguments to functions by name instead of position, improving code readability and allowing flexible argument ordering.
displayUser(age:25, name:'John');
Service Providers bootstrap application services like event listeners, middleware, and routes. They register bindings and configurations during app startup.
Attributes allow developers to add structured metadata to classes, methods, or properties. They can be read using reflection for configuration or annotations.
#[Route('/home')] class HomeController {}A CSRF token is a random, unique value added to each form or request. The server verifies it to ensure the request came from a trusted source, preventing forgery attacks.
A WeakMap stores object references as keys without preventing them from being garbage collected, improving memory efficiency in complex systems.
$map = new WeakMap();
MVC stands for Model View Controller. It separates data handling (Model), presentation (View), and business logic (Controller) for better organization and maintainability.
Eloquent is Laravel’s Object-Relational Mapper that simplifies database interactions by representing tables as models with expressive query methods.
User::where('active',1)->get();Migrations are version control for your database. They allow you to create, modify, and share database structures across different environments easily.
php artisan make:migration create_users_table
Middleware filters HTTP requests entering your application. It’s often used for authentication, logging, and modifying requests or responses before reaching controllers.
php artisan make:middleware CheckUser
Escaping output ensures user input is shown as plain text instead of executable HTML or JavaScript. This prevents Cross-Site Scripting attacks.
echo htmlspecialchars($input, ENT_QUOTES);
The password_hash function automatically salts and hashes passwords using strong algorithms like bcrypt, making stored passwords secure.
password_hash('mypassword', PASSWORD_DEFAULT);Using HTTPS encrypts session data in transit, while regenerating session IDs after login prevents attackers from reusing old session tokens.
session_regenerate_id(true);
The .env file contains sensitive information like API keys and database credentials. It should never be shared or committed to version control.