Tag Archives: PHP

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

Awesome Symfony2 Bundles

A list of awesome Symfony 2 bundles, utilities and resources.

User Management

* FOSUserBundle – Adds support for a database-backed user system.
* HWIOAuthBundle – OAuth client integration. Supports both OAuth1.0a and OAuth2.
* JMSSecurityExtraBundle – Enhances the Security Component with several new features.

Web Services

* FOSRestBundle – Provides various tools to rapidly develop RESTful API’s & applications.
* FOSOAuthServerBundle – A server side OAuth2 bundle.
* JMSSerializerBundle – Easily serialize, and deserialize data of any complexity.
* NelmioApiDocBundle – Generates documentation for your REST API from annotations.
* RequestLimitBundle – With this bundle you can easy limit requests to your application.
* RateLimitBundle – Add rate limits to your controllers/actions easily through annotations.
* BazingaHateoasBundle – Integration of the Hateoas library.
* KnpJsonSchemaBundle – Provide a service which allow you to generate json schema based on validation metadata.
* LexikJWTAuthenticationBundle – This bundle provides JWT (Json Web Token) authentication for your REST API using the namshi/jose library.
* ResourceBundle – Bundle that helps in developing REST APIs.
* SerializedResponseBundle – A simple bundle to provide an easy way to send out json/xml/yaml responses of serialized objects with annotations.

Template Engine

* UcoTwigExtensionsBundle – Provides some filters.
* TwigExtraBundle – Twig Extra Tools Extensions.
* twig-inflection – Apply inflection.
* KnpTimeBundle – Provides helpers for time manipulation.
* GravatarBundle – Simple wrapper to gravatar API.
* CgKintBundle – This bundle lets you use the Kint library in your Twig templates.
* TwigJackBundle – Handy additional features for Twig.

Database

* DoctrineFixturesBundle – Integrates the Doctrine2 Data Fixtures library.
* DoctrineMigrationsBundle – Integrates the Doctrine2 Migrations library.
* RelationBundle – Bundle to manage relations between models/entities.
* PasswordStrengthBundle – Validator for ensuring strong passwords.
* StofDoctrineExtensionsBundle – This bundle provides integration for DoctrineExtensions.
* DoctrineEncryptBundle – Bundle allows you to create doctrine entities with fields that will be protected by encryption algorithms such as AES.
* WizadDoctrineDocBundle – Allows you to generate a decent documentation for your doctrine model schema.
* doctrine-routing-bundle – Dynamic database routing.
* FeedBundle – A bundle to build RSS feeds from your entities.
* FPNTagBundle – This bundle adds tagging, with the ability to associate tags with any number of different entities.
* DoctrineEnumBundle – Provides support of MySQL ENUM type for Doctrine2.
* MysqlDoctrineFunctions – MySQL Function for Doctrine : RAND(), ROUND() DATE(), DATE_FORMAT().
* VichGeographicalBundle – A bundle which provides geographical features for ORM and ODM entities and object oriented javascript maps rendering.

Validation

* dms-filter-bundle – Provides a FilterService to allow users to implement input filtering in entities using Annotations.

Forms

* CaptchaBundle – Bundle implementing a “captcha” form type.
* FilterFormBundle – Filter form bundle.
* CraueFormFlowBundle – Multi-step forms.
* InfiniteFormBundle – A collection of useful form types and extensions.
* IvoryOrderedFormBundle – Provides a form ordering support.
* FormBundle – Provides the “entity_id” type.

Service Container

* JMSDiExtraBundle – Provides Advanced Dependency Injection Features.
* PHP-DI – The dependency injection container for humans.

Development

* TwigReflectionBundle – Displays what’s in Twig.
* WebProfilerExtraBundle – Adding routing, container, assetic & twig information in the web profiler.
* JMSDebuggingBundle – Provides advanced debugging tools.
* LiipCodeBundle – A set of Symfony2 console commands to help developers deal with the various ways of identifying classes, templates, bundles, services, etc.
* ListenersDebugCommandBundle – A console command to debug listeners.
* PUGXGeneratorBundle – An enhancement of SensioGeneratorBundle.
* XhprofBundle – XHProf bundle.

Assets Management

* FkrCssURLRewriteBundle – A small assetic filter to fix all url paths at css documents to correct urls.
* JmikolaJsAssetsHelperBundle – Exposes the AssetsHelper service from Symfony2’s templating component to JavaScript, allowing relative or absolute asset URI’s to be generated client-side.
* IgorwFileServeBundle – Bundle for serving protected files.
* KachkaevAssetsVersionBundle – Automates the process of updating assets version.
* SpritesBundle – Bundle for the Sprites library.
* ZakharovviHumansTxtBundle – Generate humans.txt file from git repository.
* SalvaJshrinkBundle – This bundle integrate jshrink library as Assetic filter and twig extension.
* AsseticMinifierBundle – An assetic minifier in pure PHP for CSS and JS files.
* assetic-extra-bundle – Asset Directory filter for Assetic.

Queues

* RabbitMqBundle – RabbitMQ bundle.
* JMSJobQueueBundle – Allows to schedule console commands as jobs.
* GearmanBundle – A bundle intended to provide an easy way to support developers who need to use job queues.
* LeezyPheanstalkBundle – Bundle for Pheanstalk, PHP client for beanstalkd queue.
* qpush-bundle – The QPush Bundle relies on the Push Queue model of Message Queues to provide asynchronous processing in your application.

Payments Management

* JMSPaymentCoreBundle – This bundle provides the foundation for various payment plugins.
* JMSPaymentPaypalBundle – Payment Bundle providing access to the PayPal API.
* CartBundle – High quality cart for developers.

Best High Ranking PHP Frameworks for Web Developers

Today I’m going to share the most high ranking PHP frameworks for web developers to achieve the high performance. Based on research in many web sites and my experience I’m sharing this information.

1. Symfony

Symfony created in 2005 a very powerful MVC Framework, Drupal the most popular Open-Source CMS uses Symfony components.

Faster and less greedy
Unlimited flexiblity
Ease of use
Stable and sustainable
A driver of innovation
Interoperable

More Info

2. Zend

Zend Framework is based on simplicity, object-oriented best practices, leading provider of software and services for developing, deploying and managing business-critical applications in PHP.

Agile Design
Continuous Delivery
Cloud Scale

More Info

3. Laravel

Larvael is very fast growing PHP Framework and very easy to learn and use.

RESTful Routing
Command Your Data
Beautiful Templating
Proven Foundation

More Info

4. Cake PHP

CakePHP is a rapid development framework for PHP which uses commonly known design patterns like ActiveRecord, Association Data Mapping, Front Controller and MVC.

Build Quickly
No Configuration
Friendly License
Batteries Included
Clean MVC Conventions
Secure

More Info

5. YII

Yii is the most popular PHP framework and its last updated 1.1.14 version on 11th August 2013.

Fast

loads the features that you need
Powerful caching support
Explicitly designed to work efficiently with AJAX

Secure

Input validation
Output filtering
SQL injection and Cross-site scripting prevention

Professional

Helps you develop clean and reusable code
Follows the MVC pattern
Ensuring a clear separation of logic and presentation

More Info

6. CodeIgniter

CodeIgniter comes 2nd in our ranking and its very powerful framework in PHP simple and elegant toolkit to create full-featured web applications.

Exceptional performance.
Nearly zero configuration.
Clear, thorough documentation.
Framework with a small footprint.
Simple solutions to complexity.

More Info

Backup Your MySQL Database Using PHP

Here is the script to backup MySql database using php. Cheers!



‹?php  
// Check via PhpMyAdmin to see what character database is using
mysql_query('SET NAMES utf8');
mysql_query('SET CHARACTER SET utf8');
$tables = '*';
//get all of the tables
if($tables == '*')
{
    $tables = array();
    $result = mysql_query('SHOW TABLES');
    while($row = mysql_fetch_row($result)) {
    $tables[] = $row[0];
}
}
else
{
    $tables = is_array($tables) ? $tables : explode(',',$tables);
}
//cycle through
foreach($tables as $table)
{
    $result = mysql_query('SELECT * FROM '.$table);
    $num_fields = mysql_num_fields($result);
    $return.= 'DROP TABLE '.$table.';';
    $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
    $return.= "\n\n".$row2[1].";\n\n";
    for ($i = 0; $i < $num_fields; $i++)
    {
        while($row = mysql_fetch_row($result))
        {
            $return.= 'INSERT INTO '.$table.' VALUES('; for($j=0; $j<$num_fields; $j++) { $row[$j] =             addslashes($row[$j]);
            $row[$j] = ereg_replace("\n","\\n",$row[$j]);
            if (isset($row[$j]))
            {
                $return.= '"'.$row[$j].'"' ;
            }
            else
            {
                $return.= '""';
            }
            if ($j<($num_fields-1))
            {
                $return.= ',';
            }
        }  
        $return.= ");\n";
    }
}
$return.="\n\n\n";
}
//save file
$handle = fopen('backups/db-backup-'.date('Y-m-d H:i:s').'-'.(md5(implode(',',$tables))).'.sql','w+'); fwrite($handle,$return); fclose($handle); if($handle)
{
    echo "database is successfully stored in backups directory.";
}
else
{
    echo "database backup unsuccessfuly.";
}