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

Key differences between Drupal 9 and Drupal 10

 Drupal 10 builds upon the Drupal 9 but introduces several key changes and improvements. Below are the main differences:

1. Symfony Upgrade

  • Drupal 9: Based on Symfony 4, which is now end-of-life.
  • Drupal 10: Upgraded to Symfony 6, providing better performance, security, and support for modern PHP development practices.

2. CKEditor Upgrade

  • Drupal 9: CKEditor 4 was the default WYSIWYG editor.
  • Drupal 10: CKEditor 5 is now the default editor, offering a more modern user experience with enhanced collaboration features, better media handling, and more intuitive controls.

3. Theme Changes

  • Drupal 9: Used the Bartik theme as the default front-end theme and Seven as the default admin theme.
  • Drupal 10: Introduces a new default front-end theme called Olivero, which is modern, accessible, and mobile-first. The admin theme Claro replaces Seven, offering a cleaner and more accessible experience.

4. Removal of Deprecated Code

  • Drupal 9: Included deprecated code from earlier versions, which was required for backward compatibility.
  • Drupal 10: Deprecated code has been removed, making the core codebase more streamlined and improving performance. This also means that modules and themes must be compatible with the latest APIs.

5. jQuery and Front-End Dependencies

  • Drupal 9: Relied heavily on jQuery and older JavaScript libraries.
  • Drupal 10: Reduces reliance on jQuery, adopting modern JavaScript standards to improve performance and minimize dependencies.

6. New Starterkit Theme Generator

  • Drupal 9: No native tool for theme generation.
  • Drupal 10: Introduces the Starterkit theme generator, allowing developers to create custom themes more easily by providing a starting point that can be modified.

7. JavaScript Modernization

  • Drupal 9: Legacy JavaScript approaches (e.g., jQuery-based).
  • Drupal 10: Emphasizes modern JavaScript (ES6+), reducing the footprint of legacy scripts and focusing on modern browser APIs for faster performance and easier maintainability.

8. Database and Performance Improvements

  • Drupal 10 brings improvements in database handling and overall performance optimization compared to Drupal 9. This includes enhancements in caching, query performance, and rendering speed.

9. Automatic Updates (Experimental in Drupal 9)

  • Drupal 9: Automatic updates were experimental but not fully developed.
  • Drupal 10: Continuation of efforts to fully implement automatic updates, making it easier to maintain site security by keeping the core and contributed modules up-to-date without manual intervention.

10. PHP Compatibility

  • Drupal 9: Supports PHP 7.4 and later.
  • Drupal 10: Requires PHP 8.1 or later, leveraging the new features of modern PHP versions for better security and performance.

11. Modules and Deprecated Features

  • Drupal 9: Includes several modules that were marked as deprecated (e.g., Quick Edit, Aggregator).
  • Drupal 10: Removes deprecated modules and features to maintain a cleaner core, encouraging the use of external libraries or more modern alternatives.


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