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.

Drupal Service for IP Blocking and Whitelisting

 Here's a simple PHP OOP-based class that you can use in a custom Drupal 10 module to implement IP blocking and whitelisting, along with a form to manage IPs.


 1. Define the PHP Class (IPManager.php)

Put this in your module's src/Service/IPManager.php.

PHP

namespace Drupal\your_module\Service; use Symfony\Component\HttpFoundation\RequestStack; class IPManager { protected $requestStack; // Define allowed and blocked IPs for simplicity. protected $whitelist = ['127.0.0.1']; // Add your trusted IPs here. protected $blacklist = ['192.168.1.10']; // Add blocked IPs here. public function __construct(RequestStack $request_stack) { $this->requestStack = $request_stack; } public function getClientIp() { return $this->requestStack->getCurrentRequest()->getClientIp(); } public function isWhitelisted(): bool { return in_array($this->getClientIp(), $this->whitelist); } public function isBlacklisted(): bool { return in_array($this->getClientIp(), $this->blacklist); } public function checkAccess(): bool { if ($this->isWhitelisted()) { return true; } if ($this->isBlacklisted()) { return false; } return true; // Default allow } }



2. Register the Service (your_module.services.yml)

YAML

services: your_module.ip_manager: class: Drupal\your_module\Service\IPManager arguments: ['@request_stack']



 3. Create a Simple Form to Manage IPs

Put this in src/Form/IPAccessForm.php:

PHP

namespace Drupal\your_module\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; class IPAccessForm extends FormBase { public function getFormId() { return 'ip_access_form'; } public function buildForm(array $form, FormStateInterface $form_state) { $form['whitelist'] = [ '#type' => 'textarea', '#title' => $this->t('Whitelisted IPs'), '#default_value' => '127.0.0.1', '#description' => $this->t('Enter one IP per line.'), ]; $form['blacklist'] = [ '#type' => 'textarea', '#title' => $this->t('Blacklisted IPs'), '#default_value' => '192.168.1.10', '#description' => $this->t('Enter one IP per line.'), ]; $form['submit'] = [ '#type' => 'submit', '#value' => $this->t('Save IPs'), ]; return $form; } public function submitForm(array &$form, FormStateInterface $form_state) { // For demo purposes, just show a message. Save to config for real use. $whitelist = $form_state->getValue('whitelist'); $blacklist = $form_state->getValue('blacklist'); \Drupal::messenger()->addStatus($this->t('Saved IP settings.')); } }



4. Route and Menu

your_module.routing.yml:

YAML

your_module.ip_access_form: path: '/admin/config/ip-access' defaults: _form: '\Drupal\your_module\Form\IPAccessForm' _title: 'IP Access Settings' requirements: _permission: 'administer site configuration'

5. Use the IP Check in a Controller or Event Subscriber

Example use in a controller:

PHP

$ipManager = \Drupal::service('your_module.ip_manager'); if (!$ipManager->checkAccess()) { throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException(); }

Why Twig template is fast ?

 Twig is a PHP-based compiled templating language. 

When your web page renders, the Twig engine takes the template and converts it into a 'compiled' PHP

 template which is stored in a protected directory in sites/default/files/php/twig. 

The compilation is done once, template files are cached for reuse and are recompiled on clearing the Twig cache.

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(); } ?>

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)   {   $...