All posts by bhaktaraz

Web enthusiastic, Nature lover...

GDPR Guide For Developers

GDPR (General Data Protection Regulation) Study

Development Aspects

– the right to erasure (the right to be forgotten/deleted from the system)

 

– right to restriction of processing (you still keep the data, but mark it as “restricted” and don’t touch it without further consent by the user)

 

– the right to data portability (the ability to export one’s data in a machine-readable format)

 

– the right to rectification (the ability to get personal data fixed)

 

– the right to be informed (getting human-readable information, rather than long terms and conditions)

 

– the right of access (the user should be able to see all the data you have about them)

 

– data minimization (one should not collect more data than necessary)

 

– integrity and confidentiality (all security measures to protect data that you can think of + measures to guarantee that the data has not been inappropriately modified)

 

Operations Aspect

 

– Encrypt the data in transit

 

– Encrypt the data at rest

 

– Encrypt your backups

 

Overall, the purpose of the regulation is to make you take conscious decisions when processing personal data. It imposes best practices in a legal way.

 

Reference sites

https://gdpr-info.eu/

https://www.eugdpr.org

Symfony – Manipulating Database Sessions

The default Symfony session storage writes the session information to files. Most medium to large websites use a database to store the session values instead of files, because databases are easier to use and scale in a multiple web server environment.

Symfony has a built-in solution for database session storage called PdoSessionHandler.

You can read the article here to Use PdoSessionHandler to Store Sessions in the Database Here.

 

AccessUsers in Session Data

You can also decode, access and modify user session data easily, since it’s now stored in the database. This means you could get stats from logged in users, queue notifications for users, check certain types of history.. stuff like that.

Here’s an example command which prints out a list and count of users who have been active in the last 10 minutes:

<?php

// src/Your/Bundle/Command/SessionsCheckCommand.php
namespace Your\Bundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SessionsCheckCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
          ->setName('sessions:check')
          ->setDescription('Checks user activity for the past couple of minutes and prints out some stats');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $threshold = 600; // Maximum seconds for last activity
        $limit = time() - $threshold;

        $em = $this->getContainer()->get('doctrine.orm.entity_manager');

        $dql = 'select s from YourBundle:Session s
            where s.sessionTime >= ?1
            order by s.sessionTime desc';
        $query = $em->createQuery($dql);
        $query->setParameter(1, $limit);
        $sessions = $query->getResult();

        $active_users = array();                // Names of active users
        $total_active_count = count($sessions); // Total active users
        $total_active_auth_count = 0;           // Total active logged in users

        foreach ($sessions as $session) {
            $data =$session->getSessionValue();
            $data = str_replace('_sf2_attributes|', '', $data);
            $data = unserialize($data);

            // If this is a session belonging to an anonymous user, do nothing
            if (!array_key_exists('_security_main', $data)) continue;

            // User is logged in, increment counter
            $total_active_auth_count++;

            // Grab security data
            $data = $data['_security_main'];
            $data = unserialize($data);

            // Add username to activity list
            $active_users[] = $data->getUser()->getUsername();
        }

        $output->writeln('The following users were active in the past few minutes:');
        $output->writeln(join(', ', $active_users));

        $output->writeln(sprintf(
            '%s user(s) were active, and %s of them was/were logged in.',
            $total_active_count,
            $total_active_auth_count
        ));
    }
}

PHP – Introduction

What is PHP?

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft’s ASP.

  • Serverside scripting language
  • Used for web development
  • Generate dynamic web pages

Requirements

What you will need?

  • Computer with PHP installed
  • Text editing application
  • A web browser

What would be helpful?

  • Understanding of HTML
  • Understanding of programming concept
  • Understanding how web server works

Terminologies 

Hypertext

Hypertext is text that links to other information. By clicking on a link in a hypertext document, a user can quickly jump to different content.

Preprocessor

In computer science, a preprocessor is a program that processes its input data to produce output that is used as input to another program. The output is said to be a preprocessed form of the input data, which is often used by some subsequent programs like compilers.

Serverside Scripting Language

Those scripts were executed by the operating system, and the results were served back by the web server. Many modern web servers can directly execute on-line scripting languages such as ASP, JSP, Perl, PHP and Ruby either by the web server itself or via extension modules (e.g. mod_perl or mod_php) to the web server.

HTML

HyperText Markup Language (HTML) is the standard markup language for creating web pages and web applications. With Cascading Style Sheets (CSS), and JavaScript, it forms a triad of cornerstone technologies for the World Wide Web.

HTTP

A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Webpages to users, in response to their requests, which are forwarded by their computers’ HTTP clients.

Web Development

Web development broadly refers to the tasks associated with developing websites for hosting via intranet or Internet. The Web development process includes Webdesign, Web content development, client-side/server-side scripting and network security configuration, among other tasks.

Dynamic Webpage

A dynamic web page is a web page that displays different content each time it’s viewed. For example, the page may change with the time of day, the user that accesses the webpage, or the type of user interaction.

 

web server working
web server working

 

Common uses of PHP

  • PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
  • PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user.
  • You add, delete, modify elements within your database through PHP.
  • Access cookies variables and set cookies.
  • Using PHP, you can restrict users to access some pages of your website.
  • It can encrypt data.

Characteristics of PHP
Five important characteristics make PHP’s practical nature possible −

  1. Simplicity
  2. Efficiency
  3. Security
  4. Flexibility
  5. Familiarity

“Hello World” Script in PHP

To get a feel for PHP, first start with simple PHP scripts. Since “Hello, World!” is an essential example, first we will create a friendly little “Hello, World!” script.

As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal HTML (or XHTML if you’re cutting-edge) you’ll have PHP statements like this −

<html>
   
   <head>
      <title>Hello World</title>
   </head>
   
   <body>
      <?php echo "Hello, World!";?>
   </body>

</html>

It will produce following result −

Hello, World!

5 things you must know about PHP 7

1. THE LATEST PHP VERSION WILL BE RELEASED LATER THIS YEAR

The PHP 7 Timeline RFC was approved in a near unanimous vote, and aims to release PHP 7 in October 2015. Even if it’s delayed a bit, we’re still likely to see it before the year is out!! The final feature set for PHP 7 is almost completely finalized, and will officially close by the end of March.

2. PHP SPACE SHIPS

PHP 7 will introduce a new operator <=> conveniently similar to a TIE fighter and dubbed the Spaceship Operator. It can be used for combined comparisons – mostly when dealing with sorting.

3. DECLARATIONS & SCALER TYPE HINTS

PHP 7 will allow developers to declare what kind of return type a function is expected to have – similar to argument Type Hints.

In addition, argument type hints and the new return-type declarations now support new scalar types, allowing developers to denote that they’re expecting strings, floats, ints or bools to be passed or returned.

4. PHP 7 PERFORMANCE

PHP 7 is based on the PHPNG project (PHP Next-Gen), that was led by Zend to speed up PHP applications. The performance gains realized from PHP 7 are huge! They vary between 25% and 70% on real-world apps, and all of that just from upgrading PHP, without having to change a single line of code!

5. PHP 7 IS 2X FASTER

Since PHPNG was open sourced and later merged into PHP 7, its performance more than doubled in many cases, and we’re continuing to improve it all the time.

To put things in perspective – when PHPNG was published, the WordPress homepage required approx. 9.4 billion CPU instructions to execute. As of now – it requires only 2.6 billion – that’s 72% less!

Explore more here.

Laravel Installation – The Fastest Way

Run the following command using composer:

composer global require "laravel/installer=~1.1"

Put an alias to the freshly installed Laravel installer in your user configuration .bashrc:

nano ~/.bashrc

And place this inside the file:

alias laravel='~/.composer/vendor/bin/laravel'

And run the following to make sure your bashrc profile is reloaded:

source ~/.bashrc

Once installed, the simple laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog would create a directory named blog containing a fresh Laravel installation with all dependencies installed. This method of installation is much faster than installing via Composer:

laravel new blog

Caching Data in Symfony2

It is not too easy to enhance the performance of your application. In Symfony2 you could get benefit from caching. The most effective way to improve performance of an application is to cache the full output of a page and then bypass the application entirely on each subsequent request. The cache is the “middle-man” of the request-response communication between the client and your application. Caching data in Symfony2 with doctrine cache bundle can be implemented as described below.

Installing this bundle can be done through these simple steps:

1. Add this bundle to your project as a composer dependency:


// composer.json
{
    // ...
    require: {
        // ...
        "doctrine/doctrine-cache-bundle": "~1.0"
    }
}

2. Add this bundle in your application kernel:


// application/ApplicationKernel.php
public function registerBundles()
{
    // ...
    $bundles[] = new \Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle();

    return $bundles;
}

Usage:

Simply use doctrine_cache.providers.{provider_name} to inject it into the desired service.

Check the following sample:


$apcCache = $this->container->get('doctrine_cache.providers.my_apc_cache');
$arrayCache = $this->container->get('doctrine_cache.providers.my_array_cache');

Usage Example for MongoDb:

In Your Config File


// config.yml

doctrine_cache:
    aliases:
        cache_categories: classifiad_category_cache
    providers:
        classifiad_category_cache:
            mongodb:
                server: mongodb://%mongodb_host%:%mongodb_port%
                database_name: %mongodb_database%

In Your Controller


// Saving Cached Data
$CategoryCacheProvider = $this->container->get('doctrine_cache.providers.classifiad_category_cache');
$CategoryCacheProvider->save('cache_categories', $categories, 60 * 60);

// Fetching Cached Data
$CategoryCacheProvider = $this->container->get('doctrine_cache.providers.classifiad_category_cache');
if ($CategoryCacheProvider->fetch('cache_categories')) {
    $categories = $CategoryCacheProvider->fetch('cache_categories');
}

Singleton Design Pattern in PHP

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

The following code is a simple implementation:



class Database
{
    // A static property to hold the single instance of the class
    private static $instance;

    // The constructor is private so that outside code cannot instantiate
    private function __construct() { }

    // All code that needs to get and instance of the class should call
    // this function like so: $db = Database::getInstance();
    public function getInstance()
    {
        // If there is no instance, create one
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        return self::$instance;
    }

    // Block the clone method
    private function __clone() {}
}

// To use, call the static method to get the only instance
$db = Database::getInstance();


Pros and Cons of Singeleton Design Pattern :

pro : You know you have the same instance available at all times.
con : One and only one instance is all you get.
pro : Instantiate itself for you so all you need to do is get it.
con : Autoinstantiation diminishes flexibility of argument passing.
pro : Since it is singeleton it can replace global variable declaration.
con : Since it is singeleton it can replace global variable declaration.