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
$ipAddressfilter_var($ipAddressFILTER_VALIDATE_IP);
echo $ipAddress;
?>




DRUPAL 9 - Module Required for Development

1- Admin Toolbar

The Admin Toolbar module intends to improve the default Toolbar (the administration menu at the top of your site) to transform it into a drop-down menu, providing a fast access to all administration pages.
The module works on the top of the default toolbar core module and is therefore a light module and keeps all the toolbar functionalities (shortcut / media responsive).

2- Token

Provides additional tokens not supported by core (most notably fields), as well as a UI for browsing tokens.
Example:
Site Information: name,login_url,email,slogan etc
Required Module for pathauto, google Analytics etc.

3- Chaos Tool Suite (ctools)

This suite is primarily a set of APIs and tools to improve the developer experience. It also contains a module called the Page Manager whose job is to manage pages. In particular it manages panel pages, but as it grows it will be able to manage far more than just Panels.

For the moment, it includes the following tools:

Plugins -- tools to make it easy for modules to let other modules implement plugins from .inc files.
Exportables -- tools to make it easier for modules to have objects that live in database or live in code, such as 'default views'.
AJAX responder -- tools to make it easier for the server to handle AJAX requests and tell the client what to do with them.
Form tools -- tools to make it easier for forms to deal with AJAX.
Object caching -- tool to make it easier to edit an object across multiple page requests and cache the editing work.
Contexts -- the notion of wrapping objects in a unified wrapper and providing an API to create and accept these contexts as input.
Modal dialog -- tool to make it simple to put a form in a modal dialog.
Dependent -- a simple form widget to make form items appear and disappear based upon the selections in another item.
Content -- pluggable content types used as panes in Panels and other modules like Dashboard.
Form wizard -- an API to make multi-step forms much easier.
CSS tools -- tools to cache and sanitize CSS easily to make user-input CSS safe.

4- Devel

Devel module contains helper functions and pages for Drupal developers and
inquisitive admins:

A block and toolbar for quickly accessing devel pages
Debug functions for inspecting a variable such as dpm($variable)

Debug a SQL query dpq($query or print a backtrace ddebug_backtrace()

A block for masquerading as other users (useful for testing)
A mail-system class which redirects outbound email to files
Drush commands such as fn-hook, fn-event, token, uuid, and devel-services


Webprofiler. Adds a debug bar at bottom of all pages with tons of useful
information like a query list, cache hit/miss data, memory profiling, page
speed, php info, session info, etc.

Devel Generate. Bulk creates nodes, users, comment, taxonomy, media, menus for development. Has
Drush integration.

This module is safe to use on a production site. Just be sure to only grant
access development information permission to developers.

5- Pathauto

The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

6- Paragraphs

Paragraphs is the new way of content creation!
It allows you — Site Builders — to make things cleaner so that you can give more editing power to your end-users.

Instead of putting all their content in one WYSIWYG body field including images and videos, end-users can now choose on-the-fly between pre-defined Paragraph Types independent from one another. Paragraph Types can be anything you want from a simple text block or image to a complex and configurable slideshow.

Paragraphs module comes with a new "paragraphs" field type that works like Entity Reference's. Simply add a new paragraphs field on any Content Type you want and choose which Paragraph Types should be available to end-users. They can then add as many Paragraph items as you allowed them to and reorder them at will.

Paragraphs module does not come with any default Paragraph Types but since they are basic Drupal Entities you can have complete control over what fields they should be composed of and what they should look like through the typical Drupal Manage Fields and Manage Display screens.

You can also add custom option fields and do conditional coding in your CSS, JS and preprocess functions so that end-users can have more control over the look and feel of each item. This is way much cleaner and stable than adding inline CSS or classes inside the body field's source.

Some more examples:

Add a block of text with an image left to it
Add a slideshow between blocks of text
Add a youtube embed between your text
Add quotes between your content blocks

Paragraph






Paragraphs





















7- Redirect

Provides the ability to create manual redirects and maintain a canonical URL for all content, redirecting all other requests to that path.

This module provides a common API for loading, deleting, and saving redirects. It also provides case-sensitive redirect matching with a hook to allow the other modules to decrease the candidate redirects.

8- Twig Tweak

Twig Tweak is a small module which provides a Twig extension with some useful functions and filters that can improve development experience.

Drupal View

{{ drupal_view('whos-s_new','block_1')}}

Drupal View Result

{{ drupal_view_result('who_s_new','block_1')}}

9- Webform

The Webform module allows you to build any type of form to collect any type of data, which can be submitted to any application or system.

Every single behavior and aspect of your forms and their inputs are customizable. Whether you need a multi-page form containing a multi-column input layout with conditional logic or a simple contact form that pushes data to a SalesForce/CRM, it is all possible using the Webform module for Drupal 8/9.

10-Backup and Migrate

Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.

With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

11-Advanced CSS/JS Aggregation

AdvAgg allows you to improve the frontend performance of your site. Be sure to do a before and after comparison by using Google's PageSpeed Insights and WebPagetest.org. The performance benefits are achieved by using some of the features found in AdvAgg and its sub modules. Out of the box AdvAgg's frontend performance will be similar to cores.

13- Diff, Shield & Socket

Diff 

This module adds a tab for sufficiently permissioned users. The tab shows all revisions like standard Drupal but it also allows pretty viewing of all added/changed/deleted words between revisions.

Shield 

PHP Authentication shield. It creates a simple shield for the site with Apache authentication. It hides the sites, if the user does not know a simple username/password. It handles Drupal as a "walled garden".
This module helps you to protect your (dev) site with HTTP authentication.

Socket

SecKit provides Drupal with various security-hardening options. This lets your mitigate the risks of exploitation of different web application vulnerabilities.

Cross-site Scripting
Content Security Policy implementation via Сontent-Security-Policy (official name), X-Content-Security-Policy (Firefox and IE) and X-WebKit-CSP (Chrome and Safari) HTTP response headers (configuration page and reporting CSP violations to watchdog)

Control over Internet Explorer / Apple Safari / Google Chrome internal XSS filter via X-XSS-Protection HTTP response header

14- Environment Indicator

This module will help you to keep sane while working on your different environments by adding a configurable color bar to each one of your environments. The Environment Indicator adds a coloured bar on the site informing you which environment you're currently in (Development, Staging, Production, etc.). This is incredibly useful if you have multiple environments for each of your sites, and like me, are prone to forgetting which version of the site you are currently looking at.

This module can help you avoid making configuration changes to your live server by mistake by adding a coloured strip to the side of your site, clearly marking each version of the site.


15- Configuration Split

This module allows to define sets of configuration that will get exported to separate directories when exporting, and get merged together when importing. It is possible to define in settings.php which of these sets should be active and considered for the export and import.



Drupal 8 and 9 delete file programmatically

Code that can be used to permanently delete unused/orphaned files in drupal 9 and 8.

// get all files ids

  $fids = \Drupal::entityQuery('file')->execute();

  $file_usage = \Drupal::service('file.usage');

  // loop all fids and load files by fid

  foreach ($fids as $fid) {

    $file = \Drupal\file\Entity\File::load($fid);

    $usage = $file_usage->listUsage($file);

    // check if file not used

    if (count($usage) == 0) {

      $file->delete();

    }

  }

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