Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

How does the garbage collector work in PHP?

 In PHP, the Garbage Collector (GC) is responsible for automatically manages memory, freeing up resources that are no longer in use by your scripts, preventing memory leaks. PHP primarily uses reference counting, but it also has a cycle collector to deal with more complex scenarios like circular references.

Freeing objects that are no longer needed prevents memory leaks.

The GC uses a counting mechanism to determine the elements to drop. If no references point to a particular object (i.e., $counter = 0), then this object is eligible for cleanup.

1. Reference Counting

Every PHP variable (zval) holds a refcount—an internal counter that tracks how many symbols (variable names or properties) refer to it.

  • Every variable in PHP has a reference count.

  • When you assign a variable or pass it to a function, the reference count increases.

  • When the reference count drops to zero, PHP frees the memory.

Example:


$a = new stdClass(); // refcount = 1 $b = $a; // refcount = 2 unset($a); // refcount = 1 unset($b); // refcount = 0 → object is destroyed

2.  Circular References Problem


Reference counting alone can't detect circular references — when two or more objects reference each other, even if nothing else does.

Example:

$a = new stdClass();
$b = new stdClass();
$a->ref = $b;
$b->ref = $a;
unset($a);
unset($b);
// Objects still exist because of mutual references → memory leak!

3. Cycle Collector (Since PHP 5.3+)

To solve this, PHP introduced a cycle collector:

  • It periodically scans memory for circular references.

  • It finds groups of objects that reference each other but are otherwise unreachable.

  • It breaks these cycles and frees the memory.

4. Triggering and Controlling GC

You can manually interact with the GC using these functions:

gc_enable();       // Enable garbage collection (default is on)

gc_disable();      // Disable garbage collection

gc_collect_cycles(); // Force collection of cycles

gc_enabled();      // Check if GC is enabled


5. Performance Considerations

  • GC adds some overhead, but it’s essential for long-running scripts (e.g., daemons, workers).

  • For short scripts, reference counting alone is usually enough.

Top 50 PHP Interview Questions and Answer

PHP is a widely used programming language for web development. If you're preparing for a PHP job interview, having a strong grasp of key concepts is essential. In this article, we’ll explore the top 50 PHP interview questions and answers to help you confidently succeed in your next interview. 

  Q1. What is PHP?

Answer: PHP stands for Hypertext Preprocessor. It is an open-source, server-side scripting language designed for creating dynamic web pages.

Q2. What are the common uses of PHP?

Answer: PHP is commonly used for:
  • Server-side scripting
  • Command-line scripting
  • Creating dynamic websites
  • Interacting with databases (e.g., MySQL)
  • Building RESTful APIs

Q3. How do you declare a variable in PHP?

Answer: Variables are declared using the $ symbol, e.g., $name = "Waliullah";.

Q4. What are PHP data types?

Answer : PHP supports:

  • String
  • Integer
  • Float (Double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

Q5. What is the difference between echo and print?

Answer:

  • echo: Outputs data, can take multiple parameters, no return value.
  • print: Outputs data, returns 1, works like a function.

Q6. How do you define a constant in PHP?

Answer: Using the define() function, e.g., define("SITE_NAME", "Shikshatech");.

Q7. What are PHP magic constants?

Answer: Special constants starting with double underscores, like:

  • __LINE__
  • __FILE__
  • __DIR__
  • __FUNCTION__
  • __CLASS__

Q8. What is the difference between == and ===?

Answer:

  • ==: Compares values only.
  • ===: Compares values and data types.

Q9. What are superglobals in PHP?

Answer: 

Predefined global arrays like 

  • $_POST, 
  • $_GET, 
  • $_SESSION, 
  • $_COOKIE, 
  • $_SERVER.

 Q10. How to connect to a MySQL database using PHP?

Answer:

To connect to a MySQL database using PHP, you can use either the MySQLi (MySQL Improved) extension or PDO (PHP Data Objects). Here's how to do it both ways:

Using MySQLi (Object-Oriented Style)


<?php
$host = "localhost"; $username = "your_username"; $password = "your_password"; $database = "your_database"; // Create connection $conn = new mysqli($host, $username, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>


Using MySQLi (Procedural Style)


<?php $host = "localhost"; $username = "your_username"; $password = "your_password"; $database = "your_database"; // Create connection $conn = mysqli_connect($host, $username, $password, $database); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; ?>

Using PDO (Recommended for Flexibility and Security)


<?php $host = 'localhost'; $db = 'your_database'; $user = 'your_username'; $pass = 'your_password'; $charset = 'utf8mb4'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; try { $pdo = new PDO($dsn, $user, $pass); // Set error mode to exception $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>

PHP - Remove warning and notice

error_reporting function in PHP allows  to tell which errors to report.

For example, if we want to display all error messages except warnings, we can use the following line of code:

//Report all errors except warnings.

error_reporting(E_ALL ^ E_WARNING);

Typically speaking, the error_reporting function should be placed at the top of your code. This is because the function can only control errors that occur in the code below it.

If you also want to hide notice messages, then you can set the following level in the error_reporting function:

Stopping warning messages from being displayed.

If you simply want to stop warning messages from being displayed, but not prevent them from being logged, then you can use the following piece of code:

**********************************************

//Tell PHP to log errors

ini_set('log_errors', 'On');

//Tell PHP to not display errors

ini_set('display_errors', 'Off');

//Set error_reporting to E_ALL

ini_set('error_reporting', E_ALL );

***********************************************

Here, we are using PHP’s ini_set function to dynamically modify the settings in our php.ini file:

1- We set log_errors to On, which means that PHP will log warnings to our error log.

2- We set display_errors to Off. As a result, PHP will not output errors to the screen.

3- Finally, we set error_reporting to E_ALL.

Using the @ character to suppress errors.

In some cases, you might not have control over certain warnings.

For example, a GET request to an external API could fail, resulting in a “failed to open stream” warning. To prevent this from occurring, we could use the @ character like so:

//API URL

$url = 'http://example.com/api';

//Attempt to get contents of that URL

$result  = @file_get_contents($url);

As you can see, we have placed the @ (AT) character next to our function call. This means that if file_get_contents fails, it will not throw an E_WARNING message.

This works because the @ character is an error control operator that tells PHP to ignore any errors.

Note that error suppression should be used sparingly. Abusing this control operator can lead to issues that are difficult to debug.

Prevention of Host Header Injection in PHP

Host Header or HTTP Host Header

The host header specifies which website or web application should process an incoming HTTP request. The web server uses the value of this header to dispatch the request to the specified website or web application. Each web application hosted on the same IP address is commonly referred to as a virtual host.

Host header is a piece of information that can be used to identify web domain. For example host header for the URL

https://www.wartalab.blogspot.com is www.wartalab.blogspot.com.

The Host header specifies the domain name of the server.

Host Header Injection Prevention in PHP

As a web developer, you must know about host header injection so that you can secure your web application from malicious attacks.

What is Host Header Injection?

A host header injection exploits the vulnerability of some websites to accept host headers indiscriminately without validating or altogether escaping them.

This is dangerous because many applications rely on the host header to generate links, import scripts, determine the proper redirect address, generate password reset links, etc. So when an application retrieves the host header, it may end up serving malicious content in the response injected there.

An example would be a request to retrieve your e-banking web page: https://www.your-ebanking.com/login.php.

If the attacker can tamper with the host header in the request, changing it to https://www.attacker.com/login.php, this fake website could be served to users and trick them into entering their login credentials. 

The above is a rough example of how a host header could be injected. A successful host header injection could result in web cache poisoning, password reset poisoning, access to internal hosts, cross-site scripting (XSS), bypassing authentication, virtual host brute-forcing, and more!

How to Prevent Host Header Injection in PHP

Copy the given below code and paste in your web application common file like header

<?php

$allowed_host = array('www.wartalab.blogspot.com', 'www.demos.wartalab.blogspot.com');

if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_host)) 

{

    header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');

    exit;

}

?> 

How to prevent Host header attacks?

Depending on your configuration type, there are different ways you can prevent host header injections. Of course, the most straightforward approach is to distrust the host header at all times and not use it in server-side code. This simple change can essentially eliminate the possibility of a host header attack being launched against you. 

However, this may not always be possible, and if you need to use the host header, you should consider implementing the following measures.

Use relative URLs as much as possible.

Start by considering whether your absolute URLs are vital. Frequently, it is possible to use relative URLs instead.

If you need to use specific absolute URLs, such as transactional emails, the domain must be specified in the server-side configuration file and taken from there. This eliminates the possibility of password reset poisoning, as it will not refer to the host header when generating a token. 

Validate Host headers

User input must always be considered unsafe and should be validated and sanitized first. One way to validate host headers, where needed, is to create a whitelist of permitted domains and check host headers in incoming requests against this list. Respectively, any hosts that are not recognized should be rejected or redirected.

To understand how to implement such a whitelist, see the relevant framework documentation. 

When validating host headers, you must also establish whether the request came from the original target host or not.

Whitelist trusted domains

Already at the development stage, you should whitelist all trusted domain names from which your reverse proxy, load balancer, or other intermediary systems are allowed to forward requests. This will help you prevent routing-based attacks such as a Server-Side Request Forgery (SSRF).

Implement domain mapping

Map every origin server to which the proxy should serve requests, i.e., mapping hostnames to websites.

Reject override headers

Host override headers, such as X-Host and X-Forwarded-Host, are frequently used in header injections. Servers sometimes support these by default, so it’s essential to double-check that this is not the case.

Avoid using internal-only websites under a virtual host

Host headers injections can be used to access internal (private) domains. Avoid this scenario, do not host public and private websites on the same virtual host. 

Create a dummy virtual host

If you use Apache or Nginx, you can create a dummy virtual host to capture requests from unrecognized host headers (i.e., forged requests) and prevent cache poisoning.

Fix your server configuration

Host header injections are frequently due to default settings, and faulty or old server configurations. Inspecting and fixing your server configuration can eliminate significant vulnerabilities that open the door for injections.

Hope you  understood how to prevent host header inject in PHP. If you liked this article, please share with others.

PHP : Validating and Sanitizing User Input Data with Filters

Sanitizing data means removing any illegal character from the data. sanitizing user input is one of the most common tasks in a web application.
To make this task easier PHP provides native filter extension that you can use to sanitize the data such as e-mail addresses, URLs, IP addresses, etc.
To validate data using filter extension you need to use the PHP's filter_var() function. The basic syntax of this function can be given with:

filter_var(variable, filter, options)

This function takes three parameters out of which the last two are optional. The first parameter is the value to be filtered, the second parameter is the ID of the filter to apply, and the third parameter is the array of options related to filter. Let's see how it works.

Sanitizing a String

Following example will sanitize a string by removing all HTML tags from it-

<?php
// Sample user comment
$comment = "<h1>Sanitizing and validating examples</h1>";
 
// Sanitize and print comment string
$sanitizedExp = filter_var($comment, FILTER_SANITIZE_STRING);
echo $sanitizedComment;
?>

Output

Sanitizing and validating examples

Validate Integer Values

<?php
// Sample user comment
$int = 20;
 
if(filter_var($int, FILTER_VALIDATE_INT)){
    echo "The <b>$int</b> is a valid integer";
} else{
    echo "The <b>$int</b> is not a valid integer";
}

?>


Validate Email Address

<?php
$email = "waliullahmca786@gmail.co<m>";
// Remove all illegal characters
// from email
$nemail = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $nemail;
?>

Validate IP Addresses

<?php
$ipAddress= "172.16.254.1<m>";
// Remove all illegal characters
// from email
$ipAddress= filter_var($ipAddress, FILTER_VALIDATE_IP);
echo $ipAddress;
?>




Static Keywords - Understanding of Static Functions , Method and Static Variables in PHP

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. These can also be accessed statically within an instantiated class object.

Any method declared as static is accessible without the creation of an object. Static functions are associated with the class, not an instance of the class. They are permitted to access only static methods and static variables. To add a static method to the class, static keyword is used.

Static methods are call without  creating an instance of the object,  so the pseudo-variable $this is not available inside methods declared as static.

Static methods are declared with the static keyword:

Syntax - 

<?php
class ClassName {
  public static function staticMethod() {
    echo "Hello World!";
  }
}
?>


To access a static method use the class name, double colon (::), and the method name:

ClassName::staticMethod();

Example: This example illustrates static function as counter.

<?php
/* Use static function as a counter */
  
class solution {
      
    static $count;
      
    public static function getCount() {
        return self::$count++;
    }
}
  
solution::$count = 1;

for($i = 0; $i < 5; ++$i) {
    echo 'The next value is: '. 
    solution::getCount() . "\n";
}
  
?>

Output:
The next value is: 1
The next value is: 2
The next value is: 3
The next value is: 4
The next value is: 5

Static properties
Static properties are accessed using the Scope Resolution Operator (::) and cannot be accessed through the object operator (->).

Difference Between Composer.json and Composer.lock or composer.json v/s composer.lock

 In a Simple ways

composer.json is the list of required libraries and versions for your project.

composer.lock is what is currently installed.

Composer Update ( Refers composer.json file )

When you do composer update it will check for the composer.json file and updates all the packages/libraries that are listed in it & once the packages are updated it will rewrite new updates in composer.json & composer.lock file by deleting old package updates.

Basically, the following process takes place

A - Read composer.json

B - Remove installed packages that are not required in composer.json

C- Check latest versions of required packages in composer.json from https://packagist.org

D - Install the latest versions of your packages

E - Update composer.lock with installed packages version & even update composer.json file with it

F - composer install


Composer Install ( Uses composer.lock file)

When you do composer install it will check for composer.lock file and install all the packages/libraries that are listed in composer.lock file.

This command won't update anything like composer update.

Basically, the following process takes place

1) composer.lock file 

If it does not exists then run composer-update and create it

If exists then read composer.lock file for installation of packages

2) Install the packages specified in the composer.lock file


what is the composer and use in drupal 8

 

Composer is a dependency manager for PHP. Drupal can be updated through composer using the command line.

Composer is an application-level package manager for the PHP programming language that provides a standard format for managing dependencies of PHP software and required libraries. It was developed by Nils Adermann and Jordi Boggiano, who continue to manage the project.

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. Drupal uses Composer to manage the various libraries that it depends on. Modules can also use Composer to include 3rd party libraries.

Drupal update through composer using the following command.

To update Drupal using composer, run the command 'composer update drupal/core --with-dependencies'

Using Composer with Drupal 8

There are many benefits to using Composer. In short, it allows us to systematically manage a sprawling list of dependencies (and their subsidiary dependencies). It assists with locating, downloading, validating, and loading said packages, all while ensuring that exactly the right versions for each package are used. 


Composer.json

Composer retrieves information from packagist.org to download packages, Drupal projects are not listed on Packagist, instead, Drupal.org provides its own repository of composer metadata for Drupal projects.


The Composer template, already includes it in therepositories ofcomposer.json:


"repositories": [

    {

        "type": "composer",

        "url": "https://packages.drupal.org/8"

    }

],

Core version

In Composer, Drupal core is a package like any other. So it is added to your project by adding a dependency to your composer.json.


Adding the following information to the composer.json will download the latest Drupal 7 release and place it in the web/-folder of the Composer project.


{

    "require": {

        "composer/installers": "~1.0",

        "drupal/drupal": "7.*"

    },

    "repositories": [

        {

            "type": "composer",

            "url": "https://packages.drupal.org/7"

        }

    ],

    "extra": {

        "installer-paths": {

            "web/": [

                "type:drupal-core"

            ]

        }

    }

}

With Drupal 8 we can choose the same approach ("drupal/drupal": "8.*") or we can use the subtree-split of the core-directory ("drupal/core": "8.*").


You can use the ready to go template for each version: Branch 8.x for Drupal 8 or Branch 7.x for Drupal 7


Projects

All Drupal projects to be retrieved should be added as dependencies in semantic versioning format.


The following will download the Chaos tool suite (ctools) module version 1.4 for Drupal 7.


{

    "require": {

        "drupal/ctools": "1.4"

    }

}

The module will be placed under sites/all/modules/contrib/.


You can also run php composer.phar require drupal/ctools from the command line in the root directory of the project. This will prompt for any additional information needed and update composer.json accordingly.


Since many Drupal projects are not available from the default Composer package repository Packagist, they will be downloaded from the Drupal repository defined in the composer.json

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...