Showing posts with label PHP security. Show all posts
Showing posts with label PHP security. Show all posts

Tuesday 7 October 2014

PHP Register Globals

PHP Register Globals

register_globals is  PHP Setting, In which it registers the GET/POST array's elements as variables.

For example, If URL is /index.php?name=php-tutorial-php, when you echo $name; It will print the value i.e php-tutorial-php (if register_globals is ON). Same applicable to POST methods also.

When register_globals is ON you need not to extract the value of GET/POST explicitly, variable values are available with the element-Name.

Example with POST Data (if register_globals is ON)
If you post following data
    [name] => php-tutorial-php
    [description] => Web Technology Experts Notes
echo $name;//php-tutorial-php
echo $description;//Web Technology Experts Notes

For Example COOKIE Data(if register_globals is ON)
$_SESSION[value] = 123;
$value = 'This is session value';
echo $_SESSION[value]; //This is session value

When register_globals=on, anything passed via $_GET / $_POST / $_SESSION / $_COOKIE automatically appears to be global variable, this can might have security consequences. Due to this register_globals has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.

If you are using lower than php5.4 version, It's highly recommended you should set off the value of register_global.

Sunday 8 June 2014

PHP Sessions and Cookie and Security

PHP Session
Session is Super global variable, that preserve certain data across multiple requests. A visitor accessing your web-site is assigned a unique id, the so-called session id. Its either stored in a cookie on the user side OR is propagated in the URL.

Why its is used
1. Get the Number of unique visitor
2. For Login functionality we need this.
3. It tell us whether user is registered OR not.

No external libraries are needed to build this extension.

Session is enabled in PHP by default. If you would not like to build your PHP with session support, you should specify the

Session configuration options
session.gc_divisor"100"PHP_INI_ALLAvailable since PHP 4.3.2.
session.cookie_secure""PHP_INI_ALLAvailable since PHP 4.0.4.
session.cookie_httponly""PHP_INI_ALLAvailable since PHP 5.2.0.
session.use_strict_mode"0"PHP_INI_ALLAvailable since PHP 5.5.2.
session.use_only_cookies"1"PHP_INI_ALLAvailable since PHP 4.3.0.
session.use_trans_sid"0"PHP_INI_ALLPHP_INI_ALL in PHP <= 4.2.3. PHP_INI_PERDIR in PHP < 5. Available since PHP 4.0.3.
session.bug_compat_42"1"PHP_INI_ALLAvailable since PHP 4.3.0. Removed in PHP 5.4.0.
session.bug_compat_warn"1"PHP_INI_ALLAvailable since PHP 4.3.0. Removed in PHP 5.4.0.
session.hash_function"0"PHP_INI_ALLAvailable since PHP 5.0.0.
session.hash_bits_per_character"4"PHP_INI_ALLAvailable since PHP 5.0.0.
url_rewriter.tags"a=href,area=href,frame=src,form=,fieldset="PHP_INI_ALLAvailable since PHP 4.0.4.
session.upload_progress.enabled"1"PHP_INI_PERDIRAvailable since PHP 5.4.0.
session.upload_progress.cleanup"1"PHP_INI_PERDIRAvailable since PHP 5.4.0.
session.upload_progress.prefix"upload_progress_"PHP_INI_PERDIRAvailable since PHP 5.4.0."PHP_SESSION_UPLOAD_PROGRESS"PHP_INI_PERDIRAvailable since PHP 5.4.0.
session.upload_progress.freq"1%"PHP_INI_PERDIRAvailable since PHP 5.4.0.
session.upload_progress.min_freq"1"PHP_INI_PERDIRAvailable since PHP 5.4.0.

How to set the Cookie?
bool setcookie ($name, $value);//set the cookie
bool setcookie ($name, $value,time()+3600); //set the cookie with expire 1 hour
bool setcookie ($name, $value, $expire = 0, $path, $domain, $secure = false, $httponly = false );//all parameter of set cookie
bool setrawcookie ($name, $value, $expire = 0, $path, $domain, $secure = false, $httponly = false );//Send a cookie without urlencoding the cookie value
Parameter of set_cookie function
name: The name of the cookie.
value: The value of the cookie. This value is stored on the clients computer; do not store sensitive information.
expire: The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoc. If set to 0, or omitted, the cookie will expire when the browser closes.
path: The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain.
domain: The domain that the cookie is available to.
secure: Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. 
httponly: When TRUE the cookie will be made accessible only through the HTTP protocol. 

How to get cookie?
echo $_COOKIE["cookieName"];

How to print all cookie?

How to delete a cookie?
setcookie ("cookieName", "", time() - 60);

How to set Array Cookie?
setcookie("cookieName[one]", "c_1");
setcookie("cookieName[three]", "c_2");
setcookie("cookieName[two]", "c_3");

How to get Array cookie?

Monday 19 May 2014

PHP Check Mime Type of File - Return Information About A File

PHP Check Mime Type of File - Return Information About A File

Now a days, we are uploading files like Profile images, Video files OR excel files in our web application. 
With uploading these files there are chances some user upload the .exe file (Virus) by renaming the .exe into .jpg, which can damage website.

You might have added the extension check from javaScript as well as PHP. But this is not enough from security end because someone can upload the file after changing the extension of file( ".exe" to ".png"). In this case your security check will be failed.

What to do.
Answer is  check the Mime of file before get uploaded in your web server.

How to do this
"fileinfo" is extension which must be enabled in your php.ini. (for existence you can check  in phpinfo)
If this extension is not enabled ask your server admin, he will do this for you OR you can also do this your self (

After installing the fileinfo extension, use following code to get the mime type of file before get uploaded in web server.
if (function_exists("finfo_file")) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);    

    //file which you want to check the mime of the file
    $file = $_SERVER['DOCUMENT_ROOT'] . '/images/feedback.png';    //file which is going to get uploaded in web server
    try {
        $type = finfo_file($finfo,$file);        
        echo "File Type: ".$type;
    } catch (Exception $e) {
        echo $e->getMessage();
} else {
    echo "'finfo_file' is Not installed";

When you execute above code, if will get the mime-type of file. This is directly checking the mime type of already uploaded file.
You can use $type = finfo_file($finfo,$file); for checking the file type, before using move_uploaded_file function.

Friday 14 March 2014

Improve Ajax Performance

Improve Ajax Performance

Following are few steps to Improve Ajax Performance
  1. First try to Reduce the Number of Ajax Call
  2. If same call send again, abort the previous call
  3. If ajax call is executing, and user go for another link, then cancel the previous one.
  4. Use GET Method, As its Fast but less secure
  5. Reduce the Amount of data transmitted
    a. Only Required parameter in Ajax Request
    b. Only Required Response in Ajax Request
  6. Optimize your Server  

Wednesday 12 March 2014

PHP Captcha Code Example Code Snippets

CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a type of challenging-response test used in computer field to determine whether user is Human OR robot program. Captcha is used in website to confirm that your website is accessing by a human being not machine. We can add captcha in multiple form/pages of website.

It reduce the risk of hacking/damage of website. It also help to secure the web server.

Follow Simple Steps to add captcha in your website.

1. Copy the following code and put in createCaptch.php
//Let's generate a totally random string using md5
$md5_hash_no = md5(rand(0, 999));
//We don't need a 32 character long string so we trim it down to 5
$security_code = substr($md5_hash_no, 15, 5);
$_SESSION['captcha'] = $security_code;

//Set the image width and height
$width = 148;
$height = 37;

//Create the image resource
$image = ImageCreate($width, $height);

//We are making three colors, white, black and gray
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$grey = ImageColorAllocate($image, 204, 204, 204);

//Make the background black
ImageFill($image, 0, 0, $grey);

//Add randomly generated string in white to the image
ImageString($image, 8, 50, 10, $security_code, $black);

//$font = 'font1.ttf';
//imagettftext($image, 18, 0, 15, 28, $black, $font, $security_code);
//Throw in some lines to make it a little bit harder for any bots to break
ImageRectangle($image, 0, 0, $width - 1, $height - 1, $grey);

// prevent client side  caching
header("Expires: Wed, 1 Jan 1997 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

//Tell the browser what kind of file is come in
header("Content-Type: image/jpeg");

//Output the newly created image in jpeg format

2. In the Form add following

<input name="ccode" type="text" /> <img src="createCaptch.php" title="Captcha Code" />

. Validate the captcha

Thursday 6 March 2014

PHP - Secure Ajax Call from Hackers - Example

PHP - Secure Ajax Call from Hackers - Example

Today, In all web application we use Ajax call to get the server data without refresh the full page. In this cases, we get required data from server without refresh the page.

For Example
In Registration Page, We want to validate the unique email address of user

Following the Simple Steps to do more Secure your Ajax Call.

1. Ajax Check - Ajax url must give Response when request is from ajax.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&  strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
echo "Ajax Call";
} else{
echo "No Ajax Call";

2. Domain Check - Ajax url must give response, when request from your own server.
if(!empty($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="")
 //Request from my server

3. Always use post Method 

4. Token System
 a) Create a token and encrypt  the data.
 b) Send with Ajax
 c) Before giving the result check the request with de-crypt

Saturday 22 February 2014

htaccess code snippets example

htaccess code snippets example

.htaccess file is used for configuration on File Level/Directory Level and its supported by all webserver. Today all types of websites use htaccess technology.

Following are Benefits of .htaccess
  • Mange Error Pages for Better SEO
  • Set PHP Config variable
  • Set Environment variable
  • Password protection for File/Directory
  • Allow/Deny visitors by IP Address
  • Detect OS (like Mobile/Laptop/Ios/Android)
  • Redirection pages 
  • Optimize Performance of website
  • Improve Site Security

Following are Few Example of .htaccess

Redirect Home page to Another Website
Redirect /

Redirect Home page to Another another Directory(i.e newdir)
Redirect / /newdir

Redirect about.html to Another another Directory(i.e /pages/about)
Redirect /about.html /pages/about

Redirect old file to New Path
Redirect /oldfile.html /newfile.html

Set PHP Environment
SetEnv APPLICATION_ENV development

Set max_filesize in php
php_value upload_max_filesize 32M

Set off error in PHP
php_flag display_errors off
php_flag display_startup_errors off

Dedect mobile/laptop and redirect to mobile site
RewriteCond %{HTTP_USER_AGENT} android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|ipad|ipod|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ (ce|phone)|xda|xiino [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a\ wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r\ |s\ )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1\ u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(\ i|ip)|hs\-c|ht(c(\-|\ |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(\ |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(\ |\/)|klon|kpt\ |kwc\-|kyo(c|k)|le(no|xi)|lg(\ g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-|\ |o|v)|zz)|mt(50|p1|v\ )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v\ )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|\ )|webc|whit|wi(g\ |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-) [NC]
RewriteRule ^$ [R,L]

Block IP Address
order allow,deny
deny from #specify a specific address
deny from #specify a subnet range
deny from* #specify an IP address wildcard
allow from all

Allow IP Address
order allow,deny
allow from #specify a specific address
allow from #specify a subnet range
allow from* #specify an IP address wildcard
allow from all

Redirect to 400.html, If 400 error comes
ErrorDocument 400 /errorpages/400.html

Redirect to 403.html, If 403 error comes
ErrorDocument 403 /errorpages/403.html

Redirect to 404.html, If 404 error comes
ErrorDocument 404 /errorpages/404.html

Redirect to 500.html, If 500 error comes
ErrorDocument 500 /errorpages/500.html

Disable Directory Listing
Options ExecCGI Includes IncludesNOEXEC SymLinksIfOwnerMatch -Indexes

Enable Directory Listing
 Options All +Indexes

Password Protection
AuthName "Authentication Section"
AuthType Basic
AuthUserFile /home/username/.htpasswds #Here your password will be stored
#htpasswds file format username:password
Require valid-user

Password Protection but Google can Crawl
AuthName "Under Development"
AuthUserFile /home/website/.htpasswd
AuthType basic
Require valid-user
Order deny,allow
Deny from all
Allow from
Satisfy Any

Set Timezone of the Server
SetEnv TZ America/Indianapolis

301 Redirect Old File
Redirect 301 /old/file.html

301 Redirect Entire Directory
Redirect 301 /old/ /new/

301 redirect https to http
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

301 redirect https to http://www
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

301 redirect non www to www with htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Set Caching for javascript/image/css
ExpiresActive On
ExpiresByType application/javascript "now plus 3 day"
ExpiresByType application/x-javascript "now plus 3 day"
ExpiresByType image/jpg "now plus 1 week"
ExpiresByType image/jpeg "now plus 1 week"
ExpiresByType image/png "now plus 1 week"
ExpiresByType image/pjpeg "now plus 1 week"
ExpiresByType image/gif "now plus 1 week"
ExpiresByType text/css "now plus 3 day"

Error Codes - Defination
301 - Permanent movement(redirection)
302 - Temporary movement(redirection)
400 - Bad request
401 - Authorization Required
403 - Forbidden
404 - Page Not Found
500 - Internal Server Error

Wednesday 22 January 2014

Manage Cron Job with PHP - SSH2 Connection

Manage Cron Job with PHP - SSH2 Connection

Today, Cron play very vital role in our website. It reduce the lots of manual work like update the record, Caching the pages, Remove not-required data etc.

Following are use of Cron Job
  1. Update Database records
  2. Copy/Move data from one server to another server
  3. Caching the data for enhance the website performance
  4. Remove the Redundancy data
  5. Remove the un-necessary data.

If there are too-many cron jobs in our web application that its hard to manage the cron jobs through crontabs. Also sometimes Compmay Owner/Manger wants to mange the cron jobs through the Admin Panel.  

Here is sample code with use of which you can mange the cron jobs from PHP. Now you can add/update/delete the cron job from PHP.

        /** check ssh2 connection**/
        if (!function_exists("ssh2_connect")){
            die('ssh2 is not installed');
        /** check ssh2 connection**/
        if (!($con = ssh2_connect("", 22))) {
            echo "Domain Not exist";
        } else {
            // try to authenticate with username root, password secretpassword
            if (!ssh2_auth_password($con, "username", "password")) {
                echo "credentials is In-Correct";
            } else {
                // execute a command
                if (!($stream = ssh2_exec($con, "ls -al"))) {
                    echo "Execution Failed";
                } else {
                    /** Read output */
                    stream_set_blocking($stream, true);
                    $data = "";
                    while ($buf = fread($stream, 4096)) {
                        $data .= $buf;
                    echo $data;
                     /** Read output */

Wednesday 22 May 2013

Spoofed Forms - Stop Spoofed Form Submissions

Spoofed Forms - Stop Spoofed Form Submissions

It is method in which attacker create a copy of html form of another website, fill the data whatever he want to sent and submit the form.

There are various ways to spoof forms, the easiest of which is to simply copy a target form and
execute it from a different location. Spoofing a form makes it possible for an attacker
to remove all client-side validations/restrictions imposed upon the form in order to submit the form.


See in above form, here form's action is of another website.

How to Protect your website from spoofed forms

  • Add client side and server side validation
  • Use token system
  • Use captcha

Thursday 4 October 2012

Session Fixation

Session Fixation

In this an attacker explicitly sets the session identifier of a session for a user. Typically in PHP it's done by giving them a url like Once the attacker gives the url to the client, the attack is the same as a session hijacking attack.
Default session_name is PHPSESSID
session_id is a unique string  and it is in the range a-z A-Z 0-9 , (comma) and - (minus)!

The most crucial piece of information for an attacker is the session identifier, because this is required for any impersonation attack. There are three common methods used to obtain a valid session identifier:

  1.     Prediction: Guessing a valid session identifier. With PHP's native session mechanism, the session identifier is extremely random, and this is unlikely to be the weakest point.
  2.     Capture: Capturing a valid session identifier is the most common type of session attack, and there are numerous approaches for capturing session_id,  because session identifiers are typically propagated in cookies or as GET variables.
  3.     Fixation:  Fixation is the simplest method of obtaining a valid session identifier by using session_id() after session_start()

What to do
By default session_name is PHPSESSID, so this session name either from php.ini file OR  with use of php function session_name. For example session_name('new_session_name')
Set session.use_trans_sid = 0 in your php.ini file. This will tell PHP not to include the identifier in the URL, and not to read the URL for identifiers.
Set session.use_only_cookies = 1 in your php.ini file. This will tell PHP to never use URLs with session identifiers.
Regenerate the session ID anytime the session's status changes. That means any of the following:
User authentication
  • Storing sensitive info in the session
  • Changing anything about the session