Difference between Drupal 8 and Drupal 9

Drupal 8 was released on 19 November 2015 and Drupal 9 was released on 3 June 2020.  Drupal 9 was built on version 8, so the changelog is shorter and the update from version 8 to 9 is simpler. The most important differences are the removal of almost all deprecated functions. In version 9, they've been replaced by other ones, and those that remained will be removed in the next installment of Drupal. A list of deprecated functions is available at Drupal.org. Also new in version 9 is the next version of Symfony. Drupal 8 used version 3, but now it's version 4. Additionally, the Twig theme engine version has been updated – has been changed from version 1 to 2. Another difference between Drupal 8 vs 9 is the fact that most of the jQuery UI library dependencies have been removed. In the case of performing tests, in the new version, we rely on the PHPUnit solution (previously, the SimpleTest framework could be used).

The next thing that was almost completely removed in Drupal 9 is the Simple Annotation Parser from Doctrine. However, the required elements were incorporated into the Drupal 9 core. We also need to pay attention to the Apache version, because in the case of Drupal 8 version 2.x was enough, but currently, Drupal 9 requires a min. version of 2.4.7. The situation is similar with PHP – this time a min. version of 7.3 is required, but version 7.4 and 8.0 are also supported (applies to Drupal 9.1.0). In terms of the database and the use of MySQL/Percona, Drupal 9 requires a min. version of 5.7.8; Drupal 8 worked with version 5.5.3. The same goes for using MariaDB and SQLite. These need to be min. versions of 10.3.7 and 3.26 respectively. The previous version of Drupal used version 5.5.20 for MariaDB and 3.6.8+ for SQLite.

Use Of Latest Versions Of Symphony Αnd Twig

Unlike Drupal 8 where Symphony 3 was used, Drupal 9 uses Symphony 4/5 for improving the website performance, scalability, quality, etc. Along with that, the new version uses Twig 2.0 as the templating engine.

Drupal 9 Is Backward Compatible

One of the major differences between the Drupal 9 upgrade from its predecessor upgrade is that it is backward compatible. If you have a fully updated Drupal 8 website, then it’s already compatible with the new version and can be easily upgraded. However, Drupal 8 wasn’t at all compatible with Drupal 7 and developers had a difficult time upgrading it to Drupal 8.

Upgraded Third-party Dependencies

Drupal 9 has also upgraded its third-party dependencies as it provides support for trusted third-party applications.

Performance

According to the above description of the differences between Drupal 8 vs 9, we can certainly say that the newer CMS release is much better in terms of speed. Using a min. PHP version of 7.3 improved the page loading speed. We can see an example on the PHP Benchmarks page, where all PHP versions are listed – from 5.6 to 8.0. At the very first glance, we can already see that between Drupal 8 and 9 there was an increase in performance of over 10%. This is the perfect reason to consider an upgrade, as each new version of PHP causes an even bigger leap in performance.


The situation is similar with Symfony. Version 3 has been used so far, but Drupal 9 needs the newer, fourth version of the framework. Thanks to it, we can significantly reduce the working time the developers need to create a new module or improve an existing one. The results of comparing Symfony versions from 2 to 5 can be checked on the already mentioned PHP Benchmarks page.

Get or set your site uuid with drush in Drupal 8

From time to time it comes in quite handy to import configuration from other websites into yours. You site uuid is unique though, with the following snippet you get yours.

drush config-get "system.site" uuid

To set the uuid in drush:

drush cset system.site uuid 9b13adbf-0da5-4937-a731-xxxxxxxxxxx -y

Drupal 8 delete menu link programmatically

Here's a snippet on how to delete all links in a menu.

// Need to replace 'sidebar-menu' menu name value with own name.
$mids = \Drupal::entityQuery('menu_link_content')
      ->condition('menu_name', 'sidebar-menu')
      ->execute();
$controller = \Drupal::entityTypeManager()->getStorage('menu_link_content');
$entities = $controller->loadMultiple($mids);
$controller->delete($entities);

For delete all the links in a particular menu like footer

$old_menu_links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
  ->loadByProperties(['menu_name' => 'footer']);
foreach ($old_menu_links as $old_menu_link) {
  $old_menu_link->delete();
}


For update to  existing menu


$menu_links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
  ->loadByProperties(['menu_name' => 'footer']);
foreach ($menu_links as $menu_link) {

  if ($menu_link->gettitle() == 'old-title') {
    $menu_link->set('title', 'new-title');
    $menu_link->save();
  }
}

What is a view in Drupal

A views in Drupal provide graphical interface for listing information. The views module allows administrators and site designers to create, manage, and display lists of content.
Each list managed by the views module is known as a "view", and the output of a view is known as a "display". Displays are provided in either block or page form, and a single view may have multiple displays. Optional navigation aids, including a system path and menu item, can be set for each page-based display of a view. By default, views may be created that list content (a Node view type), content revisions (a Node revisions view type) or users (a User view type). A view may be restricted to members of specific user roles, and may be added, edited or deleted at the views administration page.
For more technical users, views can be understood as a user interface to compose SQL-queries, pulling information (Content, Users, etc.) from the database and showing it on screen in the desired format.

Example formats include a HTML table, a RSS feed, a PDF document, a CSV document, an interactive map, an image slideshow, or a JSON representation to be used as a REST endpoint. The same content can be presented in multiple formats at the same time. For instance, you can present a table of user information and on the same page a link to download the data in CSV format.

Views is one of the many systems that allow you to create dynamic sites with Drupal. These sites that, once configured, update their content automatically as time passes. For example, if you have a website that contains information about events, you might want to have a page that lists only future events. To accomplish this you can create an “Event” content type that has a “date” field. Then you create a view with a filter criteria that uses this field so that only events whose date is “today” or greater appear on the final list. Note that it is possible to use date offsets as filter values. Once all the configuration is in place, content editors only need to add nodes and set a value for the “date” field. When Drupal shows the page for this view, it will respect the original configuration and only show results that match the condition from today onwards. This illustrates the need to store node data in separate fields. This way you can use them as fields (to show), filter criteria, sort criteria, and more. If you had this information inside the “body” field, it would be practically impossible to use it for these purposes.

Fields
Fields, or the individual pieces of data being displayed. Adding the fields Node: Title, Node: Type, and Node: Post date to a node view, for example, includes the title, content type and creation date in the displayed results.

Relationships
Relationships, or information about how data elements relate to one another. If relationship data is available, like that provided by a CCK node reference field, items from a related node may be included in the view.

Sort criteria
Sort criteria, which determine the order of items displayed in the view results. Adding the sort criteria Node: Post date (in descending order) to a node view, for example, sorts the displayed posts in descending order by creation date.

Filters
Filters, which limit items displayed in the results. Adding the filter Node: Published (and setting it equal to "Published") to a node view, for example, prevents unpublished items from being displayed.

Displays
Displays, which control where the output will be seen. Every view has a default display, which doesn't actually display the view anywhere but is used to hold the default settings for the view. This default display is also used when the view is called programmatically without specifying another display. Much more useful to users are the page display, which gives a view a path and allows it to be the primary content of a page, or the block display which allows it to appear as secondary content on other pages.

Header
Header, which allow you to add by default one or more text area above the views output.

Footer
Footer, which allow you to add by default one or more text area beneath the views output.

Empty Text
The Empty Text content will be displayed, when you choose in the Arguments Section "Action to take if argument is not present" the option "Display empty text".

Drupal 8 Cache

Caching is the process of storing copies of files in a cache, or temporary storage location, so that they can be accessed more quickly.

Drupal 8 enables two modules: Internal Page Cache and Internal Dynamic Page Cache. Internal Page Cache caches pages for anonymous users. 

Internal Page Caching

The Internal Page Caching module when enabled, stores the complete page information even if the user visiting the site hasn’t logged in. Future anonymous visitors will then observe that the same content is loaded extremely fast since the page wasn’t put together from scratch. This module is useful for websites with a lot of unregistered users.

Internal Dynamic Page Cache

The Internal Dynamic Page Cache module is designed to cache small sections of each page for all users whether they are logged in or not. Whenever the page content is requested by the same or different user, the module can pull in those individual parts to speed up the building of the page on the fly.

Basic configuration

Drupal offers basic performance tuning at
Administration > Configuration > Development > Performance (admin/config/development/performance)

It is recommended that block and page caching be enabled. Instead of Drupal dynamically performing complex SQL queries it caches these for quick retrieval.
If you enabled caching, remember, you may need to Flush Cache (Clear all caches button) to see any changes made to your site. The Devel module has a block named “Development” you can enable that gives easy access to quick cache flushing. If you're a more technical user look at Drush. You can flush cache with one shell command drush cc all.
Typically during development, caching should be disabled. On production sites, caching should always remain enabled for best performance.
Page and block caching is not always available. For example, page caching will not be available when a component of the page has marked the page as explicitly not cacheable, such as using sessions. Block caching will not be available when using a module that utilizes node access, such as Organic Groups or Taxonomy Access Control Lite.

Opcode Caching (PHP - high CPU)

PHP out of the box is a dynamic language and can lead to heavy CPU usage on web servers. There are multiple types of opcode caching add-ons for PHP available that will convert your .php page into memory (byte code) to provide a major benefit in load time and reduced CPU usage. Each of these will require root access to install and have their own specific configurations that will need some attending before using. Once configured and enabled they can provide a substantial benefit to a slow site and greatly reduce CPU usage from PHP.

Database Caching

Database caching can be provided by a distributed memory object caching system, such as Memcache. Memcached allows you to allocate memory where you have more than you need and make it accessible to areas where you have less than you need. When implemented with Drupal, Memcached can store the result of your database query’s in the memory for a specified time, reducing database traffic.

Web Server (Proxy) Caching

HTTP acceleration, or Web Server (Proxy) Caching, will significantly reduce resource requirements and page load times. Varnish Cache, is a widely-used HTTP accelerator for Drupal sites.
HTTP acceleration is handled by a reverse proxy. A reverse proxy is a type of proxy server that retrieves resources (pages, images, files, etc.) prior to being requested by a website visitor. These resources are stored in virtual memory and are quickly retrieved by the proxy server when requested. Reverse proxies are heavily threaded and optimized for data retrieval.

Twig cache

Twig is used for Drupal 8 theming, and it relies on having its own cache of compiled Twig templates, which is separate from other caches that are cleared with the drush cache:rebuild command in Drupal 8. 

Drupal 8 theming concepts

A theme is a collection of files that define the presentation layer. You can also create one or more "sub-themes" or variations on a theme. drupal.org/docs/8/theming.

The big change from Drupal 7 to Drupal 8 for theming is the change from PHP templates to twig and the use of yml "YAML" files.

CSS file organization

Drupal 8 follows the SMACSS-style categorization. (SMACSS = Scalable and modular architecture for css).

Base — CSS reset/normalize plus HTML element styling.
Layout — macro arrangement of a web page, including any grid systems.
Component — discrete, reusable UI elements.
State — styles that deal with client-side changes to components.
Theme — purely visual styling (“look-and-feel”) for a component.

CSS file naming conventions

CSS files should be placed in a css/ directory and broken down by module, theme, and admin files.
Note: Modules should never have any base styles. Drupal core's modules do not have any base styles. Instead Drupal core uses the Normalize.css library augmented with a drupal.base.css library.If a module attaches a CSS file to a template file, the CSS file should be named the same as the template file, e.g. the system-plugin-ui-form.html.twig CSS file should be named system-plugin-ui-form.css

YAML / YML

yaml  is a "human readable" markup language designed for data serialization for all programing languages.

Syntax for yml is key : value
Use a colon as a separator
Tabs are NOT allowed. Use spaces ONLY.
Properties and lists MUST be indented by two (2) spaces.
Yaml files end in the .yml file extension.
In Drupal 7, modules needed a MODULE_NAME.info file. Now, in Drupal 8 requires a MODULE_NAME.info.yml
Use yaml lint to find syntax errors. BLT can validate yml with blt validate:yaml.

Example - 

name: Hello World Module
description: Creates a page showing "Hello World".
package: Custom

type: module
core: 8.x

Libraries

Sometimes a site will require an external library. Libraries can be defined 3 different ways, within a theme, on a single page, or on a subset of pages with a preprocess function.

Each asset/library needs to be defined in the root of your module folder or in your theme root directory. For example the Drupal contrib module slick requires the external slick library. Inside of the theme directory docroot/themes/custom/MY_THEME there needs to be a MY_THEME.libraries.yml file.


slick:  
  version: 1.0.0  
  css:    
    theme:      
        stylesheets/ui/slick-rotator.css: {}


In the above example the theme key is for visual styling for a component. You can assign weights, or specify a theme. Therefore, in this example the asset/library slick has defined a css file included inside of the slick module directory.

Define a library on a single template

External libraries can increase the weight of a project and slow down a site's performance. If a custom javaScript library only needs to load on a single template, it might make sense to attach the library to only that template. For example, if you add attach_library to the top of twig template file, the library will only load whenever that twig template is used.

{# Place attach_library in a twig template. #}

{{ attach_library('THEME_NAME/library-name') }}

Define a library on a subset of pages

There can also be instances where you only need to add a library to a specific set of pages instead of every page. You can accomplish this with a preprocess function added the THEME_NAME.theme file.

function MY_THEME_page_attachments(array &$attachments) {

if (!\Drupal::currentUser()->hasPermission('access contextual links')) {  
  return;  

}

$attachments['#attached']['library'][] = 'contextual/drupal.contextual-links';

}

What are disadvantages of Drupal

Drupal is not user friendly interface. It requires advanced knowledge and few basic things about the platform to install and modify.

Drupal is a new content management system. It is not compatible with other software.

Performance is low compared to other CMS's. The website which is built using Drupal will generate big server loads and never opens with a slow internet connection.

Advanced interface. Professional construction systems make Drupal difficult to master. Due to its complex interface, it is not very intuitive.

High system requirements. Before turning to the use of this CMS, you must be prepared to forget about cheap fares and pay an expensive hosting fee.

Difficulty in the installation of updates and program modules. This system is complicated for those web developers who previously had to deal with a simple CMS, as the installation of updates and additional modules in the Drupal software is made through FTP.

What is PDO

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions.

PDO is a lean, consistent way to access databases. This means developers can write portable code much easier. PDO is not an abstraction layer like PearDB. PDO is a more like a data access layer which uses a unified API (Application Programming Interface).

Drupal provides a database abstraction layer, which helps the developer to work easily with multi-database servers. It is used to preserve the syntax and power of SQL and to work with complex functionality. It provides a defined interface for dynamic queries with using security checks and good practices. This process is developed at the top of the PDO database API.

How to enable PDO

To enable PDO, configure --enable-pdo and --with-pdo-sqlite --with-pdo-mysql or whatever database needs supporting by PDO (see the PHP manual for more information).

PHP type casting

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used.

PHP is supper-friendly. Also, it is a loosely typed language. This means PHP allows us to declare a variable and simply use it, the data type will be automatically determined.

Note: PHP determines the data type of variables automatically. We just declare a variable and assign it a value. PHP determines the type from the value.

Furthermore, PHP continuously and automatically converts types from one to another when necessary. This is called implicit casting or Type Juggling. Why is PHP juggling types? Because it is always trying to make sense of our code.

An example of PHP's automatic type conversion is the multiplication operator '*'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as ints, and the result will also be an int. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

<?php

$foo = "1";  // $foo is string (ASCII 49)

$foo *= 2;   // $foo is now an integer (2)

$foo = $foo * 1.3;  // $foo is now a float (2.6)

$foo = 5 * "10 Little Piggies"; // $foo is integer (50)

$foo = 5 * "10 Small Pigs";     // $foo is integer (50)

?>

Type Casting 

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

<?php

$foo = 10;   // $foo is an integer

$bar = (boolean) $foo;   // $bar is a boolean

?>

The casts allowed are

(int), (integer) - cast to int

(bool), (boolean) - cast to bool

(float), (double), (real) - cast to float

(string) - cast to string

(array) - cast to array

(object) - cast to object

(unset) - cast to NULL

(binary) casting and b prefix exists for forward support. Note that the (binary) cast is essential the same as (string), but it should not be relied upon.

The (unset) cast has been deprecated as of PHP 7.2.0. Note that the (unset) cast is the same as assigning the value NULL to the variable or call. The (unset) cast is removed as of PHP 8.0.0.

"An example of PHP's automatic type conversion is the multiplication operator '*'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is."

I understand what the doc is trying to say here, but this sentence is not correct as stated, other types can be coerced into floats.

e.g.

<?php

$a = "1.5"; // $a is a string

$b = 100; // $b is an int

$c = $a * $b; // $c is a float, value is 150

// multiplication resulted in a float despite fact that neither operand was a float

?>

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)  
{  
$rem = $num % 10;  
$revnum = ($revnum * 10) + $rem;  
$num = ($num / 10);   
}  
echo "Reverse number of 23456 is: $revnum";  
?>  

PHP header() Function

The PHP header() function is an inbuilt function in PHP which is used to send a raw HTTP header. The HTTP functions are those functions which manipulate information sent to the client or browser by the Web server, before any other output has been sent. One important point to be noted about the header() function is that it must be called before sending any actual output.

The header() function sends an HTTP header in raw form to the client or browser. Before sending any other output, the HTTP functions manipulate the information sent by the web-server to the client or browser.

Syntax - 

void header( $header, $replace = TRUE, $http_response_code )

Parameters

This function accepts three parameters as mentioned above and described below:

$header: This parameter hold the header string. There are two types of header calls. The first header starts with string “HTTP/”, which is used to figure out the HTTP status code to send. The second case of header is the “Location:”. It is mandatory parameter.

$replace: It is optional parameter. It denotes the header should replace previous or add a second header. The default value is True (will replace). If $replace value is False then it force multiple headers of the same type.

$http_response_code: It is an optional parameter. It forces the HTTP response code to the specified value (PHP 4.3 and higher).

Return Values: This function doesn’t return any value.

Changes

After PHP version 5.1.2, this function stops sending more than one header to prevent the header injection attacks. It allows only one header at a time.

Uses

It changes the page location.

It sets the time zone.

It sends the STOP status.

This function sets the caching control.

It initiates the force download.

Example 1 - 

The following code will redirect your user to some another page.

<?php  

    // This will redirect the user to the new location  

    header('Location: https://wartalab.blogspot.com/');  

    //The below code will not execute after header  

    exit;  

?>  


Write a program in php to find the factorial of a number

The factorial of a number n is defined by the product of all the digits from 1 to n (including 1 and n).

For example,

4! = 4*3*2*1 = 24  

6! = 6*5*4*3*2*1 = 720  

Logic:

Take a number.

Take the descending positive integers.

Multiply them.

Code

<?php

//example to calculate factorial of a number using function

//defining the factorial function

function Factorial_Function($number) {

$input = $number;

$fact=1;

//iterating using for loop

for($i=$input; $i>=1;$i--) {

$fact = $fact * $i;

}

return $fact;

}

//calling the factorial function

$result = Factorial_Function(8);

echo 'Factorial of the number 4 is '.$result;

?>

Output - 

Factorial of the number 8 is 40320


Write a PHP program to find a string is palindrome or not

A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam or racecar. There are also numeric palindromes, including date/time stamps using short digits 11/11/11 11:11 and long digits 02/02/2020. Sentence-length palindromes ignore capitalization, punctuation, and word boundaries.


<?php

function check_plaindrome($string) {

    //remove all spaces

    $string = str_replace(' ', '', $string);

    //remove special characters

    $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);

    //change case to lower

    $string = strtolower($string);

    //reverse the string

    $reverse = strrev($string);

    if ($string == $reverse) {

        echo "<p>It is Palindrome</p>";

    } else {

        echo "</p>Not Palindrome</p>";

 }

}

$string = "madam";

check_plaindrome($string);

Output - 

It is Palindrome

Write a program in PHP to find no of days between two dates

 <?php

function dateDiffDays($date1, $date2)  {

    $diff = strtotime($date2) - strtotime($date1);

     return abs(round($diff / 86400));

}


$date1 = "01-10-2021";

$date2 = "11-10-2021";

$dateDiff = dateDiffDays($date1, $date2);


printf("Difference between two dates: ". $dateDiff . " Days ");

?>

Output - 

Difference between two dates: 10 Days

Write a program in Php to check whether a number is prime or not

 A prime number is a number that can only be divided by itself and 1 without remainders. Here we explain what exactly this means, give you a list of the prime numbers children need to know at primary school and provide you with some practice prime number questions and examples.

What is a prime number?

A prime number is a number greater than 1 with only two factors – themselves and 1.

A prime number cannot be divided by any other numbers without leaving a remainder.

An example of a prime number is 13. It can only be divided by 1 and 13. Dividing a prime number by another number results in numbers left over e.g. 13 ÷ 6 = 2 remainder 1.

15 is not an example of a prime number because it can be divided by 5 and 3 as well as by itself and 1.

15 is an example of a composite number because it has more than two factors.

PHP Program for Check if a number is prime

<?php

// PHP code to check whether a number is prime or Not

// function to check the number is Prime or Not

function primeCheck($number){

if ($number == 1) 

return 0;

for ($i = 2; $i <= $number/2; $i++){

if ($number % $i == 0)

return 0;

}

return 1;

}

// Driver Code

$number = 31;

$flag = primeCheck($number);

if ($flag == 1)

echo "Prime";

else

echo "Not Prime"

?>


PHP Sessions

Session handling is a key concept in PHP that enables user information to be persisted across all the pages of a website or app. In  other words . An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Before using any session variable make sure you have setup this path.

When a session is started following things happen .

PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.

A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string.

A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_  ie sess_3c7foj34c3jj973hjkop2fc937e3443.

When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.

A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session

 The first step is to start up a session. After a session is started, session variables can be created to store information. The PHP session_start() function is used to begin a new session.It als creates a new session ID for the user. Below is the PHP code to start a new session.

<?php

session_start();

?>

Storing Session Data

Session data in key-value pairs using the $_SESSION[] superglobal array.The stored data can be accessed during lifetime of a session.

Below is the PHP code to store a session with two session variables Rollnumber and Name.

<?php

session_start();

$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";

?>

Accessing Session Data

Data stored in sessions can be easily accessed by firstly calling session_start() and then by passing the corresponding key to the $_SESSION associative array.
The PHP code to access a session data with two session variables Rollnumber and Name is shown below.

<?php

session_start();

echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>';
echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>';

?>

Output - 

The Name of the student is :Ajay 
The Roll number of the student is :11

Destroying Certain Session Data

To delete only a certain session data,the unset feature can be used with the corresponding session variable in the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the associative session array.

<?php

session_start();

if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
}

?>

Destroying Complete Session

The session_destroy() function is used to completely destroy a session. The session_destroy() function does not require any argument.

<?php

session_start();
session_destroy();

?>

Key Points

The session IDs are randomly generated by the PHP engine .
The session data is stored on the server therefore it doesn’t have to be sent with every browser request.
The session_start() function needs to be called at the beginning of the page, before any output is generated by the script in the browser.


PHP Cookies

 Cookie is a small piece of information stored as a file in the user's browser by the web server. Once created, cookie is sent to the web server as header information with every HTTP request.

You can use cookie to save any data but it should not exceed 1K(1024 bytes) in size.

The web works based on the HTTP protocol. The HTTP protocol is stateless.

When the web browser requests a page from a web server, the web server responds with the page content. Later, the same web browser requests the same page again, the web server has no information that the request is from the same web browser.

Cookies solve this stateless challenge.

A cookie is a piece of data that a web server sends to the web browser. The web browser may store it and send it back in the subsequent requests to the same web server. By using the same cookie, the web server knows that two requests come from the same web browser.

Cookies are also known as web cookies, HTTP cookies, or browser cookies. We’ll use the cookies to make it short.

How Cookie works

First, the web browser sends a request to the web server. The web server doesn’t have any information about the web browser. The web server creates a cookie with a name return and a value 1 and attaches the cookie to the HTTP response header. To create a cookie, you’ll use the setcookie() function.

Second, the web browser stores the cookie.

Third, the web browser sends the second request with the stored cookie in the header of the HTTP request to the web server. On the web server, PHP can access the cookie via the $_COOKIE superglobal variable and do something accordingly.

Finally, the web server responds with the content of the request. Typically, it responds to the web browser with the content based on the value of the cookie.

A web browser can store a cookie with a maximum size of 4KB. However, it’s different between web browsers.

A cookie has an expiration date. Typically, web browsers store cookies for a specific duration. And the web server can specify the expired time for a cookie.

A cookie also stores the web address (URL) that indicates where it comes from. And the web browser only sends back the cookie that was originally set by the same web address. In other words, a website won’t be able to read a cookie set by other websites.

Most modern web browsers allow users to choose to accept cookies. Therefore, you should not completely rely on cookies for storing critical data.

Types of Cookies

There are two types of cookies, they are:

Session Cookie: This type of cookies are temporary and are expire as soon as the session ends or the browser is closed.

Persistent Cookie: To make a cookie persistent we must provide it with an expiration time. Then the cookie will only expire after the given expiration time, until then it will be a valid cookie.

Creating a Cookie in PHP

In PHP we can create/set a cookie using the setcookie() function.

Below we have the syntax for the function,

setcookie(name, value, expire, path, domain, secure)

The first argument which defines the name of the cookie is mandatory, rest all are optional arguments. Let's understand what are the available arguments that we can supply to the setcookie() function to set a cookie.

name - Used to specify the name of the cookie. It is a mandatory argument. Name of the cookie must be a string.

value - Used to store any value in the cookie. It is generally saved as a pair with name. For example, name is userid and value is 7007, the userid for any user.

expire - Used to set the expiration time for a cookie. if you do not provide any value, the cookie will be treated as a session cookie and will expire when the browser is closed.

path - Used to set a web URL in the cookie. If set, the cookie will be accessible only from that URL. To make a cookie accessible through a domain, set '/' as cookie path.

domain - The domain of your web application. It can be used to limit access of cookie for sub-domains. For example, if you set the domain value as wwww.blogger.com, then the cookie will be inaccessible from wartalab.blogspot.com.

secure - If you set this to 1, then the cookie will be available and sent only over HTTPS connection.

So if we want to create a cookie to store the name of the user who visited your website, and set an expiration time of a week, then we can do it like this,

<?php

setcookie("username", "xyz", time()+60*60*24*7);

?>

To access a stored cookie we use the $_COOKIE global variable, and can use the isset() methos to check whether the cookie is set or not.

Let's have a complete example where we will set a cookie and then retrieve it to show its value in the HTML page.

<?php

// set the cookie

setcookie("username", "iamabhishek", time()+60*60*24*7);

?>

<html>

    <body>

    <?php

    // check if the cookie exists

    if(isset($_COOKIE["username"])) {

        echo "Cookie set with value: ".$_COOKIE["username"];

    } else {

        echo "cookie not set!";

    }

    ?>

    </body>

</html>

So by providing the name of the cookie inside the square brakets with the global variable $_COOKIE[] we can access the cookie.

NOTE: setcookie() function should be placed before the starting HTML tag(<html>).

PHP Interface

 An interface allows you to specify a contract that a class must implement. To define an interface, you use the interface keyword as follows.

Interfaces allow you to specify what methods a class should implement.

Interfaces make it easy to use a variety of different classes in the same way. When one or more classes use the same interface, it is referred to as "polymorphism".

Syntax for defining PHP Interface

Like classes are defined using the keyword class, interfaces are defined using the keyword interface followed by the interface name.

<?php

    // interface declaration

    interface NameOfInterface {  

    }

?>

And a class uses the implements keyword to inherit from an interface and implement the methods declared in the interface.

<?php

    // class declaration

    class SomeClass implements NameOfInterface {

    }

?>

An interface consists of methods that contain no implementation. In other words, all methods of the interface are abstract methods. An interface can also include constants. For example-

<?php

interface MyInterface {

const CONSTANT_NAME = 1;

public function methodName();

}

?>

When you define a class (child class) that reuses properties and methods of another class (parent class), the child class extends the parent class.

However, for interfaces, we say that a class implements an interface. 

A class can inherit from one class only. However, it can implement multiple interfaces.

To define a class that implements an interface, you use the implements keyword as follows:

<?php

interface MyInterface {

const CONSTANT_NAME = 1;

public function methodName();

}

class MyClass implements MyInterface {

public function methodName() {

// ...

}

}

?>

When a class implements an interface, it’s called a concrete class. The concrete class needs to implement all the methods of the interface.

Like a class, an interface can extend another interface using the extends keyword. The following example shows how the Document interface extends the Readable interface.

interface Readable {

public function read();

}

interface Document extends Readable {

public function getContents();

}

Following are the reasons for using interfaces:

By implementing an interface, the object’s caller needs to care only about the object’s interface, not implementations of the object’s methods. Therefore you can change the implementations without affecting the caller of the interface.

An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy.

An interface enables you to model multiple inheritances because a class can implement more than one interface.



PHP Abstract Class and Methods

Abstract classes are the classes in which at least one method is abstract. Unlike C++ abstract classes in PHP are declared with the help of abstract keyword. Use of abstract classes are that all base classes implementing this class should give implementation of abstract methods declared in parent class. An abstract class can contain abstract as well as non abstract methods.

Following are some important points about abstract class and method.

1 - An abstract class can have methods and properties just like any other normal class.

2 - An abstract class cannot be instantiated, hence we need to create a child class which extends it, then we can create object of the child class.

3 - If a class has even a single abstract method then the class should also be abstract.

4 - An abstract method is just the declaration, where we provide name of the method and argument, while the body part is empty.

Don't worry if its too much for you to understand. We will cover all the points step by step with examples, lets start by understanding how we create an abstract class.

Creating an abstract Class

To declare a class abstract, we need to use the abstract keyword before the name of the class.

 Example - 

<?php

    // abstract class

    abstract class Vehicle {

        // abstract function mileage

        abstract public function mileage() {

        }

    } 

?>

In the example above, our class Vehicle is an abstract class, which has an abstract method.

The idea behind creating abstract class is to bound developers to follow a set of guidelines, for example, if you want to create a new class which extends our class Vehicle then you will have to provide definition for the abstract method mileage(), else the child class should also be abstract. Hence, it is mandatory for all the child classes to provide definition for the method mileage().

Non Abstract Method in Abstract Class

Any class with even a single abstract method must be declared abstract. But an abstract class can have non-abstract methods as well, which can be accessed and used directly by the child classes, without overriding them.

Let's extend the example above, and include a non-abstract method in our class Vehicle.

<?php

    // abstract class

    abstract class Vehicle {

        // protected variable

        protected $name;

        // non-abstract public function start

        public function start() {

            echo $this->name. " - Engine start...<br/>";

        }

        // non-abstract public function stop

        public function stop() {

            echo $this->name. " - Engine stop...<br/>";

        }

        // non-abstract public function setName

        public function setName($name) {

            $this->name = $name;

        }

        // abstract function mileage

        abstract public function mileage() {

        }

    }

?>

In the code above, we have added three non-abstract methods namely start(), stop() and setName() to our abstract Vehicle class.

Inheriting Abstract Classes

Just like any other class, we can create classes extending abstract classes too.

The only difference here is that the child class must provide definition for the abstract method declared in the abstract parent class.

If the child class doesn't provide definition for the abstract method, then it should also be defined as an abstract class.

Let's create two child classes inheriting the class Vehicle and which will have definition for the abstract method mileage():

<?php

    // child class

    class Car extends Vehicle {

        public function mileage() {

            echo "I am " . $this->name . "<br/>";

            echo "My mileage range is - 15 to 22 Km/L";

        }

    }

?>

We can have as many child classes as we want, lets have another class.

<?php

    // child class

    class Motorcycle extends Vehicle {

        public function mileage() {

            echo "I am " . $this->name . "<br/>";

            echo "My mileage range is - 35 to 47 Km/L";

        }

    }

?>

As mentioned above that an abstract class cannot have any object, once we have proper child classes defined, we can create object for them.

<?php

    $car = new Car();

    $car->setName("BMW X1");

    $car->mileage();

?>

Output - 

I am BMW X1

My mileage range is - 15 to 22 Km/L






What is Constructor and Destructor

 Constructor is a special type of function which will be called automatically whenever there is any object created from a class.

Destructor is a special type of function which will be called automatically whenever any object is deleted or goes out of scope.

Syntax: 

__construct(): 


function __construct() {

       // initialize the object and its properties by assigning 

       //values

       }


__destruct(): 

function __destruct()  {

       // destroying the object or clean up resources here 

       }

Note: The constructor is defined in the public section of the Class. Even the values to properties of the class are set by Constructors.

Constructor types

Default Constructor:It has no parameters, but the values to the default constructor can be passed dynamically.

Parameterized Constructor: It takes the parameters, and also you can pass different values to the data members.

Copy Constructor: It accepts the address of the other objects as a parameter.

Example

<?PHP

class Tree

{

function Tree()

{

echo "Its a User-defined Constructor of the class Tree";

}


function __construct()

{

echo "Its a Pre-defined Constructor of the class Tree";

}

}


$obj= new Tree();

?>

Output: 

Its a Pre-defined Constructor of the class Tree

Parameterized Constructor: The constructor of the class accepts arguments or parameters. 

The -> operator is used to set value for the variables. In the constructor method, you can assign values to the variables during object creation.

Example -

<?php


class Employee {

Public $name;

Public $position;

function __construct($name,$position) {

// This is initializing the class properties

$this->name=$name;

$this->profile=$position;

}

function show_details() {

echo $this->name." : ";

echo "Your position is ".$this->profile."\n";

}

}

$employee_obj= new Employee("Rakesh","developer");

$employee_obj->show_details();

$employee2= new Employee("Vikas","Manager");

$employee2->show_details();

?>

Output -

Rakesh : Your position is developer

Vikas : Your position is Manager


Constructors start with two underscores and generally look like normal PHP functions. Sometimes these constructors are called as magic functions starting with two underscores and with some extra functionality than normal methods. After creating an object of some class that includes constructor, the content of constructor will be automatically executed.

Note: If the PHP Class has a constructor, then at the time of object creation, the constructor of the class is called. The constructors have no Return Type, so they do not return anything not even void.

Advantages of using Constructors

Constructors provides the ability to pass parameters which are helpful in automatic initialization of the member variables during creation time .
The Constructors can have as many parameters as required and they can be defined with the default arguments.
They encourage re-usability avoiding re-initializing whenever instance of the class is created .
You can start session in constructor method so that you don’t have to start in all the functions everytime.
They can call class member methods and functions.
They can call other Constructors even from Parent class.

Destructor: Destructor is also a special member function which is exactly the reverse of constructor method and is called when an instance of the class is deleted from the memory. Destructors (__destruct ( void): void) are methods which are called when there is no reference to any object of the class or goes out of scope or about to release explicitly. 
They don’t have any types or return value. It is just called before de-allocating memory for an object or during the finish of execution of PHP scripts or as soon as the execution control leaves the block. 
Global objects are destroyed when the full script or code terminates. Cleaning up of resources before memory release or closing of files takes place in the destructor method, whenever they are no longer needed in the code. The automatic destruction of class objects is handled by PHP Garbage Collector.

Note: The destructor method is called when the PHP code is executed completely by its last line by using PHP exit() or die() functions.

Example - 

<?php

class SomeClass {
 
function __construct()
{
echo "In constructor, ";
$this->name = "Class object! ";
}

function __destruct() {
echo "destroying " . $this->name . "\n";
}
}
$obj = new Someclass();

?>

Output -

In constructor, destroying Class object! 

Note: In the case of inheritance, and if both the child and parent Class have destructors then, the destructor of the derived class is called first, and then the destructor of the parent class. 

Advantages of destructors
 
Destructors give chance to objects to free up memory allocation , so that enough space is available for new objects or free up resources for other tasks.
It effectively makes programs run more efficiently and are very useful as they carry out clean up tasks.
 

What is the relation between Classes and Objects

 They look very much same but are not same.

    A class is a definition, while an object is an instance of the class.

    A class is a blueprint while objects are actual objects existing in the real world.

Suppose we have a class Person which has attributes and methods like name, age, height, weight, color etc.

Class Person is just a prototype, now we can create real-time objects of class Person.


#Example: Ali is real time object of class Person, which have name=Ali, age=23, height=170cm, weight=60kg and color=black etc.

Class

A way to bind data and associated functions together.

Class have many objects.

Class is a template for creating objects.

It is logical existence.

Memory space is not allocated, when it is created.

Definition (Declaration) is created once.

Class is declared using "class" keyword.

Object

Basic runtime entity in object oriented environment.

Object belongs to only class.

Object are a implementation of class.

It is physical existence.

Memory space is allocated when it is created.

It is created many times as you required.

Object is the instance or variable of class.

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal theme

 Define all of your CSS and Javascript file or libraries in a *.libraries.yml file in your theme folder. If your theme is named custom, the file name should be custom.libraries.yml. Each "library" in the file is an entry detailing CSS and JS files (assets), like this.

# custom.libraries.yml

cuddly-slider:

  version: 1.x

  css:

    theme:

      css/cuddly-slider.css: {}

  js:

    js/cuddly-slider.js: {}

In this example, the JavaScript: cuddly-slider.js and CSS cuddly-slider.css are located in the respective js and css directories of your theme.

#Including jQuery in your Library

Remember, Drupal no longer loads jQuery on all pages by default, so for example if cuddly-slider needs jQuery you must declare a dependency on the core library that contains jQuery (Drupal core provides jQuery, not a module or theme). Declare the dependency with an extension name followed by a slash, followed by the library name, in this case core/jquery. If another library required cuddly-slider it would declare:custom/cuddly-slider, the theme name, followed by the library name. You cannot declare an individual file as a dependency, only a library.

So, to make jQuery available for cuddly-slider, we update the above to.

# custom.libraries.yml

cuddly-slider:

  version: 1.x


  css:

    theme:

      css/cuddly-slider.css: {}


  js:

    js/cuddly-slider.js: {}

  dependencies:

    - core/jquery


#Declaring dependencies

To declare a dependency, the required library is declared in the form resource/library. For core libraries, the resource is core, while for others it is the module name or the theme name. So if new_library is dependent on jQuery from core, my_library declared in my_theme, and my_library declared in my_module, you would declare the dependencies as.

# custom.libraries.yml

new_library:

  js:

    js/new_library.js: {}

  dependencies:

    - core/jquery

    - my_module/my_library

    - my_theme/my_library

The module and theme names provide namespacing for libraries of the same name.

#Attaching a library to all pages

Most themes will use a global-styling asset library, for the stylesheets (CSS files) that need to be loaded on every page where the theme is active. It is also possible to do with JS via a global-scripts asset library

# custom.libraries.yml (multiple libraries can be added to a libraries.yml file, these would appear below the cuddly-slider libraries added earlier)

global-styling:

  version: 1.x

  css:

    theme:

      css/layout.css: {}

      css/style.css: {}

      css/colors.css: {}

global-scripts:

  version: 1.x

  js: 

    js/navmenu.js: {}   

To be available everywhere in the theme, the global-styling/global-scripts libraries must then be added to your theme's info.yml (in this case custom.info.yml)

#custom.info.yml

name: Custom

type: theme

description: 'Custom theme'

core: 8.x

# by adding global-styling and global-scripts here, the css/js files in the library become 

# available to every page presented by the theme

libraries:

  - custom/global-styling

  - custom/global-scripts

base theme: classy

regions:

  header: Header

  content: Content

  sidebar_first: 'Sidebar first'

  footer: Footer


#Attaching a library via a Twig template

You can attach an asset library to a Twig template using the attach_library() function in any *.html.twig, file like so:


{{ attach_library('custom/cuddly-slider') }}

<div>Some fluffy markup {{ message }}</div>

#Attaching a library to a subset of pages

function custom_preprocess_page(&$variables) {

  $variables['page']['#cache']['contexts'][] = 'route';

  $route = "entity.node.preview";

  if (\Drupal::routeMatch()->getRouteName() === $route) {

    $variables['#attached']['library'][] = 'custom/node-preview';

  }

}




Drupal Theming - Use of template.php

 The template.php file contains your sub-theme's functions to manipulate Drupal's default markup. It is one of the most useful files when creating or modifying Drupal themes. 

template.php

A- It contains code that is run every time the template engine is run.

B- template.php is a collection of functions that assist in the theming of the site. It’s for all the conditional logic and data processing of the output - the place to redefine or override theme functions, or add variables that will be made available to the theme engine.

C- PHP: This file must start with a PHP opening tag and typically does not end with a PHP closing tag.

D- There will be one template.php file for a theme, and this one file will define any needed variables.

E- You can add new variables and template suggestions.

With template.php you ca do the following things.

1 - Modify any theme hooks variables or add your own variables, using preprocess or process functions.

2 - Override any theme function. That is, replace a module's default theme function with one you write.

3 - Call hook_*_alter() functions which allow you to alter various parts of Drupal's internals, including the render elements in forms. The most useful of which include hook_form_alter(), hook_form_FORM_ID_alter(), and hook_page_alter(). See api.drupal.org for more information about _alter functions.

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