Saturday, March 21, 2015

Popular Security Libraries for PHP Developers

Today, PHP is one of the most popular web programming language for creating dynamic websites. There is bunches of data on the web that PHP developers make utilization of. On the other hand, few of them are obsolete and can manage anybody to compose "awful code.

In this post, we have introduced to popular PHP security libraries that will help them to create security interfaces for web applications. If you have any suggestion regarding PHP Security Libraries please write in comment box. Thanks

Popular Security Libraries for PHP Developers


HTML Purifier

HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive whitelist, it will also make sure your documents are standards compliant, something only achievable with a comprehensive knowledge of W3C’s specifications.

URLcrypt

URLcrypt makes it easy to securely transmit short pieces of binary data in a URL. Use it to securely store things like user IDs, download expiration dates, and more. URLcrypt uses 256-bit AES symmetric encryption to securely encrypt data, and encodes and decodes Base 32 strings that can be used directly in URLs.

PHP Intrusion Detection System

PHPIDS (PHP-Intrusion Detection System) is a simple to use, well structured, fast and state-of-the-art security layer for your PHP based web application. The IDS neither strips, sanitizes nor filters any malicious input, it simply recognizes when an attacker tries to break your site and reacts in exactly the way you want it to. Based on a set of approved and heavily tested filter rules any attack is given a numerical impact rating which makes it easy to decide what kind of action should follow the hacking attempt. This could range from simple logging to sending out an emergency mail to the development team, displaying a warning message for the attacker or even ending the user’s session.

TCrypto

TCrypto is a simple and flexible PHP 5.3+ in-memory key-value storage library. By default, a cookie will be used as a storage backend. TCrypto has been designed from the ground up with security in mind. Safe algorithms and modes. Automatic and safe initialization vector creation. Encryption and authentication key creation (Keytool) using strong randomness. Key rotation (versioned keys). TCrypto can be used as a scalable “session handler”. Especially scalable, if cookies are used as a storage backend. This is a bit like Ruby on Rails sessions.

PHP Password Lib

PHP-PasswordLib aims to be an all-inclusive cryptographic library for all cryptographic needs. It is meant to be easy to install and use, yet extensible and powerful enough for even the most experienced developer.

PHPSecLib

phpseclib is designed to be ultra-compatible. It works on PHP4+ (PHP4, assuming the use ofPHP_Compat) and doesn’t require any extensions. For purposes of speed, mcrypt is used if it’s available as is gmp or bcmath (in that order), but they are not required.

Hybrid Auth

HybridAuth is an open source PHP library for authenticating through multiple social services and ID providers. The services supported include OpenID,Facebook, LinkedIn, Google,Twitter, Windows Live, Foursquare, Vimeo, Yahoo, PayPal and more. It can be integrated easily into existing websites by inserting a file and few lines to the sign-in/up pages.

Security Check – Sensiolabs

This tool is almost essential to both beginners and experienced PHP coders. The way it works is quite simple, you upload your .lockfile and it does the rest for you. If you look at the stats, the numbers of vulnerabilities found is quite staggering, don’t be surprised if your own projects might output some nasty stuff that you have missed.

SecurityMultiTool

A multitool library offering access to recommended security related libraries, standardised implementations of security defences, and secure implementations of commonly performed tasks. The purpose of the library is to serve as both a useful set of utilities and to act as a set of reference implementations which can be learned from. It may be used by applications regardless of whether they are web application framework based or not. The use of a web application framework does not guarantee your security.

What is contrast in the middle of MYISAM and InnoDB?


What is contrast in the middle of MYISAM and InnoDB?

In this post, I am explaining to each one of PHP developer to understand the difference between MYISAM and INNODB

MYISAM
1. MYISAM supports Table-level Locking
2. MyISAM designed for need of speed
3. MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
4. MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
5. MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.

INNODB
1. InnoDB supports Row-level Locking
2. InnoDB designed for maximum performance when processing high volume of data
3. InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS
4. InnoDB stores its tables and indexes in a tablespace
5. InnoDB supports transaction. You can commit and rollback with InnoDB

Friday, December 19, 2014

Parse Website with PHP

Parse Website with PHP

Parsing website pages is always a challenge for PHP Developers. Parsing is using for retrieving images, scraping websites, crawling, error detection websites, and many other useful purposes. But PHP Simple HTML DOM Parser is a awesome or can say dream library for developer that work with both PHP and the DOM element using PHP.


You can get the Simple HTML DOM Parser from here and save file to any directory of your choice. First in a basic example we’ll include the class, and get all hyperlinks on the http://4evertutorials.blogspot.com .

<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

// Include the parser library
include('simple_html_dom.php');

// Retrieve the DOM from a given URL
$html_dom = file_get_html('http://4evertutorials.blogspot.com/');

// scan for all hyperlinks and print
foreach ($html_dom->find('a') as $element) {
       print $element->href;
}

?>
Below are few basic uses of PHP Simple HTML DOM Parser.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

// Include the parser library
include('simple_html_dom.php');

// Retrieve the DOM from a given URL
$html = file_get_html('http://4evertutorials.blogspot.com/');

// Find all anchor tags and print their HREFs
foreach($html->find('a') as $e) 
    echo $e->href;

// Retrieve all images and print their SRCs
foreach($html->find('img') as $e)
    echo $e->src;

// Find all images, print their text with the "<>" included
foreach($html->find('img') as $e)
    echo $e->outertext;

// Find all SPAN tags that have a class of "SpanClass"
foreach($html->find('span.SpanClass') as $e)
    echo $e->outertext;

// Find all TD tags with "align=center"
foreach($html->find('td[align=center]') as $e)
    echo $e->innertext;

// Extract all text from a given cell
echo $html->find('td[align="center"]', 1)->plaintext;

// Find the DIV tag with an id of "DivId"
foreach($html->find('div#DivId') as $e)
    echo $e->innertext;


?>

Thursday, October 16, 2014

Install CodeIgniter Framework


In this post we will cover how to install codeigniter framework and we will view the most common steps to install codeigniter framework. CodeIgniter is one of the most popular PHP frameworks around. It uses the Model-View-Controller Architectural design pattern and it’s considered by lots of PHP developers as one of the best framework solution for small to medium projects.

How to Install

The installation itself is such a simple process. First of all, you need to download the CodeIgniter zipped file, upload it to your server and extract it into your home directory. You can download it from https://ellislab.com/codeigniter/user-guide/installation/downloads.html.

Configuring CodeIgniter

Congratulations, now you have CodeIgniter installed on your server. Now it’s time for configuration. Open the application/config/config.php file with your preferred editor and set your base URL. If you intend to use encryption or sessions, set your encryption key. For the database configuration, open the application/config/database.php file with your preferred editor and set your database host, name, user, password and other values that you think it will help you connect to your database. You will find array variables with comments to know the role of each value.

Configuration files

By editing the two previously mentioned files, you are ready to start coding your first web application but CodeIgniter contains more files that enable more configuration and customization abilities. The configuration files can be found in the application/config/ directory. The following is a quick description of what you can do by editing some of the most commonly used configuration files:

autoload.php : specifies which systems (Packages, Libraries, Helper files, Custom config files, Language files and Models) should be loaded by default.

config.php : contains all website configuration.

constants.php : contains defined constants which are used when checking and setting modes when working with the file system.

database.php : contains the settings needed to access your database.

email.php : This file is not created by default. But you can create it and set the default values for the email class. Like: mailtype, charset, newline, protocol, smtp_host, etc.

hooks.php : lets you define “hooks” to extend CI without editing the core files.

mime.php : contains an array of mime types. It is used by the upload class to help identify allowed file type.

routes.php : lets you re-map URI requests to specific controller functions.

smileys.php
: contains an array of smileys for use with the emoticon helper.

upload.php : This file is not created by default. But you can create it and set the default values for the upload class. Like: upload_path, allowed_types, max_size, max_width, max_height, etc.

user_agents.php : contains four arrays of user agent data. It is used by the User Agent Class to help identify browser, platform, robot, and mobile device data. The array keys are used to identify the device and the array values are used to set the actual name of the item.

Monday, October 6, 2014

php To PDF

php To PDF is an API based solution. We are a web service providing you the easiest way to generate PDF files from PHP Code.

Our server does the heavy lifting and generates the PDFs for you. The generated PDF files will be returned and stored on your server in the specified directory with your specified file name, or you can set them to be created and displayed or downloaded by a user on the fly.

You do not need any special packages or permissions. It works on any server running PHP!

We have simplified our API so that you just need to download the phpToPDF.php file from your account and include it in your code. It's that simple.

Get started :: PHP to PDF generation steps
Sign up to access our API   
2  FREE!
Download and include phpToPDF.php

Sample Code

Use the phptopdf() function for creating a PDF using a URL



<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/


    require('phpToPDF.php');

    //Set Your Options -- see documentation for all options
    $pdf_options = array(
          "source_type" => 'url',
          "source" => 'http://google.com',
          "action" => 'save');

    //Code to generate PDF file from options above
    phptopdf($pdf_options);
 

?>



Alternatively, you can use the phptopdf() function to pass a varible that holds html code for your PDF.

<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

    require('phpToPDF.php');

    //Your HTML in a variable
    $my_html="

PDF from HTML using phpToPDF

"; //Set Your Options -- we are saving the PDF as 'my_filename.pdf' to a 'my_pdfs' folder $pdf_options = array( "source_type" => 'html', "source" => $my_html, "action" => 'save', "save_directory" => 'my_pdfs', "file_name" => 'my_filename.pdf'); //Code to generate PDF file from options above phptopdf($pdf_options); ?>


[ More Examples ]

Thursday, September 4, 2014

New features in PHP 5.6

The PHP development team announced new release of PHP 5.6. The new release brings new features and lots of improvements, development team say, also as some backward incompatible changes.

Following are the most important changes in PHP 5.6 release:




Constant scalar expressions
It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts where PHP previously expected a static value, such as constant and property declarations and default function arguments.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

const ONE = 1;
const TWO = ONE * 2;

class C {
    const THREE = TWO + 1;
    const ONE_THIRD = ONE / self::THREE;
    const SENTENCE = 'The value of THREE is '.self::THREE;

    public function f($a = ONE + self::THREE) {
        return $a;
    }
}

echo (new C)->f()."\n";
echo C::SENTENCE;

//The above example will output:
/*
4
The value of THREE is 3
*/

?>
Improved syntax for variadic functions
Variadic functions can be declared through a new ... operator:

<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/
 
function f($req, $opt = null, ...$params) {
    // $params is an array containing the remaining arguments.
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);

// The above example will output:
/*
$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params: 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2
$req: 1; $opt: 2; number of params: 3
*/

?>
Argument unpacking via ... operator
Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ... operator. This is also known as the splat operator in other languages, including Ruby.

<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

function add($a, $b, $c) {
    return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);

// The above example will output:
/*
6
*/
?>

Exponentiation via ** operator
A right associative ** operator has been added to support exponentiation, along with a **= shorthand assignment operator.

<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

printf("2 ** 3 ==      %d\n", 2 ** 3);
printf("2 ** 3 ** 2 == %d\n", 2 ** 3 ** 2);

$a = 2;
$a **= 3;
printf("a ==           %d\n", $a);

// The above example will output:
/*
2 ** 3 ==      8
2 ** 3 ** 2 == 512
a ==           8
*/

?>


use function and use const
The use operator has been extended to support importing functions and constants in addition to classes. This is achieved via the use function and use const constructs, respectively.


<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/ 
 
namespace Name\Space {
    const FOO = 42;
    function f() { echo __FUNCTION__."\n"; }
}

namespace {
    use const Name\Space\FOO;
    use function Name\Space\f;

    echo FOO."\n";
    f();
}

// The above example will output:
/*
42
Name\Space\f
*/


?>

Now UTF-8 is Default character encoding
default_charset is now used as the default character set for the htmlentities(), html_entity_decode() and htmlspecialchars() functions. Note that if the (now deprecated) iconv and mbstring encoding settings are set, they will take precedence over default_charset for iconv and mbstring functions, respectively.

Large file uploads 
Files larger than 2 gigabytes in size are now accepted.

GMP supports operator overloading
GMP objects now support operator overloading and casting to scalar types. This allows for more expressive code using GMP:
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/ 
 
$a = gmp_init(42);
$b = gmp_init(17);

// Pre-5.6 code:
var_dump(gmp_add($a, $b));
var_dump(gmp_add($a, 17));
var_dump(gmp_add(42, $b));

// New code:
var_dump($a + $b);
var_dump($a + 17);
var_dump(42 + $b);

?>

Full list of all changes in PHP 5.6 can be additionally found in the here.

Wednesday, September 3, 2014

Using Google PageSpeed Insights API with php

In this post we learn how to analyze websites using google pagespeed insights api with PHP. First of all you need to acquire an API key: 




1) Go to the Google Developers Console

2) Select a project, or create a new one. 

3) In the sidebar on the left, expand APIs & auth. Next, click APIs. In the list of APIs, make sure the status is ON for the PageSpeed Insights API. 

4) In the sidebar on the left, select Credentials

5) This API supports two types of credentials. You need only Public API access: A request that does not provide an OAuth 2.0 token must send an API key. The key identifies your project and provides API access, quota, and reports.

To create an API key, click Create new Key and select the appropriate key type. Enter the additional information required for that key type and click Create.

Replace "API_KEY" with your ones in following php function.


<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

function checkPageSpeed($url){  
  if (function_exists('file_get_contents')) {  
    $result = @file_get_contents($url);  
  }  
  if ($result == '') {  
    $ch = curl_init();  
    $timeout = 60;  
    curl_setopt($ch, CURLOPT_URL, $url);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
    $result = curl_exec($ch);  
    curl_close($ch);  
  }  

  return $result;  
}

?>

HOW TO USE CODE
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

$myKEY = "API_KEY";
$url = "http://4evertutorials.blogspot.com";
$url_req = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&key='.$myKEY;
$results = checkPageSpeed($url_req);
echo '
';
print_r(json_decode($results,true)); 
echo '
'; ?>

 

© 2014 4everTutorials. All rights resevered.

Back To Top