My Google+ Profile

Thursday, 6 December 2012

PHP mysql_real_escape_string() Function to prevent MySQL - SQL Injection Prevention

What is SQL Injection

SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

SQL Injection Example

Below is a sample string that has been gathered from a normal user and a bad user trying to use SQL Injection. We asked the users for their login, which will be used to run a SELECT statement to get their information.

MySQL & PHP Code:

// a good user's name
$name = "timmy"; 
$query = "SELECT * FROM customers WHERE username = '$name'";
echo "Normal: " . $query . "<br />";

// user input that uses SQL Injection
$name_bad = "' OR 1'"; 

// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

// display what the new query will look like, with injection
echo "Injection: " . $query_bad;

Display:

Normal: SELECT * FROM customers WHERE username = 'timmy'
Injection: SELECT * FROM customers WHERE username = '' OR 1''



The normal query is no problem, as our MySQL statement will just select everything from customers that has a username equal to timmy.
However, the injection attack has actually made our query behave differently than we intended. By using a single quote (') they have ended the string part of our MySQL query
  • username = ' '
and then added on to our WHERE statement with an OR clause of 1 (always true).
  • username = ' ' OR 1
This OR clause of 1 will always be true and so every single entry in the "customers" table would be selected by this statement!


More Serious SQL Injection Attacks


Although the above example displayed a situation where an attacker could possibly get access to a lot of information they shouldn't have, the attacks can be a lot worse. For example an attacker could empty out a table by executing a DELETE statement.

MySQL & PHP Code:

$name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; 

// our MySQL query builder really should check for injection
$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";

// the new evil injection query would include a DELETE statement
echo "Injection: " . $query_evil;

Display:

SELECT * FROM customers WHERE username = ' '; DELETE FROM customers WHERE 1 or username = ' ' 

If you were run this query, then the injected DELETE statement would completely empty your "customers" table. Now that you know this is a problem, how can you prevent it?

Injection Prevention - mysql_real_escape_string()

Lucky for you, this problem has been known for a while and PHP has a specially-made function to prevent these attacks. All you need to do is use the mouthful of a function mysql_real_escape_string.
What mysql_real_escape_string does is take a string that is going to be used in a MySQL query and return the same string with all SQL Injection attempts safely escaped. Basically, it will replace those troublesome quotes(') a user might enter with a MySQL-safe substitute, an escaped quote \'.
Lets try out this function on our two previous injection attacks and see how it works.

MySQL & PHP Code:

//NOTE: you must be connected to the database to use this function!
// connect to MySQL

$name_bad = "' OR 1'"; 

$name_bad = mysql_real_escape_string($name_bad);

$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";
echo "Escaped Bad Injection: <br />" . $query_bad . "<br />";


$name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; 

$name_evil = mysql_real_escape_string($name_evil);

$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";
echo "Escaped Evil Injection: <br />" . $query_evil;

Display:

Escaped Bad Injection:
SELECT * FROM customers WHERE username = '\' OR 1\''

Escaped Evil Injection:
SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1 or username = \''

Notice that those evil quotes have been escaped with a backslash \, preventing the injection attack. Now all these queries will do is try to find a username that is just completely ridiculous:
  • Bad: \' OR 1\'
  • Evil: \'; DELETE FROM customers WHERE 1 or username = \'
And I don't think we have to worry about those silly usernames getting access to our MySQL database. So please do use the handy mysql_real_escape_string() function to help prevent SQL Injection attacks on your websites. You have no excuse not to use it after reading this lesson!



Monday, 3 December 2012

Search functionality on an index page

Here's how to implement simple and easy search functionality on an index page:

1. Let's say your controller looks like this:
public function actionIndex()
{
  $dataProvider=new CActiveDataProvider('Model');
  $this->render('index',array(
  'dataProvider'=>$dataProvider,
  ));
}
2. Change it to this:
public function actionIndex()
{
    $criteria = new CDbCriteria();

    if(isset($_GET['q']))
    {
      $q = $_GET['q'];
      $criteria->compare('attribute1', $q, true, 'OR');
      $criteria->compare('attribute2', $q, true, 'OR');
    }

    $dataProvider=new CActiveDataProvider
            ("Model", array('criteria'=>$criteria));

    $this->render('index',array(
      'dataProvider'=>$dataProvider,
    ));
}
The above will read in the "q" (for query) parameter, and use the compare function to create the sql to search a few attributes for that value. Note the use of the 'OR' operator.

3. In your index view, add this:
<form method="get">
<input type="search" placeholder="search" name="q" 
value="<?=isset($_GET['q']) ? CHtml::encode($_GET['q']) : '' ; 
?>" />
<input type="submit" value="search" />
</form>
The above creates a form that will submit to itself using the querystring. It displays a search input box, which is a text input box with a "cancel" command. It works in most browsers and defaults to a text field in the rest. When the user hits the search button, the form is submitted and the data is filtered by the search value.

Snapshot:

Get all sunday date of current Year Using PHP

Following function return array of list of Sunday's Date of the Current Year in PHP.

<?php

function getDateForSpecificDayBetweenDates($startDate, $endDate, $weekdayNumber)
{
    $startDate = strtotime($startDate);
    $endDate = strtotime($endDate);

    $dateArr = array();

    do
    {
        if(date("w", $startDate) != $weekdayNumber)
        {
            $startDate += (24 * 3600); // add 1 day
        }
    } while(date("w", $startDate) != $weekdayNumber);


    while($startDate <= $endDate)
    {
        $dateArr[] = date('Y-m-d', $startDate);
        $startDate += (7 * 24 * 3600); // add 7 days
    }

    return($dateArr);
}

$year   = date("Y");

$dateArr = getDateForSpecificDayBetweenDates($year.'-01-01', $year.'-12-31', 0);

print "<pre>";
print_r($dateArr);

?>

And if you want to get any other day of  week then just change value of weekday. I have pass 0 value into the function to get all Sunday of the current year.

Note : Pass weekdays value between 0  to 6. 

Tuesday, 27 November 2012

6 Steps to Create a Successful Website

Creating website is very important and responsible task. You need to take into account all the main moments to make it user-friendly and informative. We want to share with you stages cover website design and development processes.


Background Information

First of all, you need to know for sure the purpose of your website. Very often people think they defined with a choice when at the last moment generate new idea for new site. There are the main moments to be considered:
  • know the main purpose of your website: service promotion, providing information to visitors, products selling, etc.;
  • define what you are going to gain from the site and what you want to accomplish: your goals (make money, share information);
  • detect the target audience: try to imagine the “ideal” person who will visit your site (age, sex, interests); this will help you when you’ll be choosing content for your site.

 

Make a Plan

This is a second but very important stage. It’s time for writing site map (a list that includes the main topics and sub-topics). Designers and developers select the main tools that will be used for building your site depending on its purpose and target customers.

 

Design Process

Designers of your website are preparing images of layout, interface, etc. and send you possible variants to choose the most suitable one. On this step specialists are guided by the idea of “ideal” visitor. For example, if your website will provide information for women it should have an appropriate template, maybe something in pink colors, feminine, glamour and light; in case if you aim to make something for businesses try minimalist style with classic elements, etc. Don’t forget about company logo to identify it on the site.

 

Development Process

This is a time for implementation of chosen techniques on practice and finally development of the website. Usually everything starts with creation of the Home Page. Developers follow the main navigational structure for the site – the shell for interior. On this stage you still can make and corrections or additional changes.

 

Testing and Delivering Processes

This is very important, but unfortunately often overlooked step. Before launching your website you need to be sure everything works as intended. For this purpose experts make functional, usability and other types of testing, examine the codes to prevent any risks associated with vulnerabilities. Web designers use FTP or CMS to upload files into the website, index it and ensure that site operates correctly and users can visit it through the various browsers.

 

Maintenance

Creation and launching the website is only beginning. Whether you ordered development of the website or made it by yourself you need to update the content frequently, add some information or make corrects. Most of designers will be happy to continue work with your site. If you aim to increase the search engine ranking you better hire SEO-optimizer, copywriter, etc.
So, what useful information you can extract from this article? There are the main 6 steps of website creation. It is not easy to put it on practice, you need to figure out many aspects before starting to provide the project with succeed implementation.

Saturday, 24 November 2012

Date validation in Yii

The date validator CDateValidator was added to Yii in release 1.1.7 and provides an easy method to validate that a field contains a date, time or datetime, with the following parameters.

format - option enables you to specify the date format or a list of date formats in an array.

allowEmpty - whether to allow empty or null values

for example:

public function rules()
{
return array(
           // multiple formats specified to allow for 01/02/20012 and 1/02/2012
           array('experience_from, experience_to ', 'date', 'format'=>array('dd/MM/yyyy','d/MM/yyyy'), 'allowEmpty'=>true),
           array('created_dt, last_updated, ', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss', 'allowEmpty'=>false),
  );
}


So now we can be sure that the user has input valid date formats – what about date ranges.

If we wanted to check that the experience_to is greater than the experience_from we could perhaps use the compare validator for date ranges as follows:

  array('experience_to','compare','compareAttribute'=>'experience_from','operator'=>'>', 'allowEmpty'=>true,'message'=>'{attribute} must be greater than "{compareValue}".')


So, wouldn’t life be nice and easy if this code worked …. but it doesn’t!

The date comparison validator uses datetimestamps.  It does not convert textual dates into timestamps.  Therefore the date in the format “dd/mm/yyyy” of 16/01/2012 is greater than 10/02/2012.

It looks as though we will still need to build a custom function to convert these dates to datetimestamps first and then do the comparison test.

So here is date function to do that validation.

        public function dateCompare($attribute,$params) {

            if (empty($params['compareAttribute']) || empty($params['operator']))
               $this->addError($attribute, 'Invalid Parameters to dateCompare');

            $compareTo=$this->$params['compareAttribute'];

            if($params['allowEmpty'] && (empty($this->$attribute) || empty($compareTo)))
        return;

            //set default format if not specified
            $format=(!empty($params['format']))? $params['format'] : 'dd/MM/yyyy';
            //default operator to >
            $compare=(!empty($params['operator'])? $params['operator'] : ">";

            $start=CDateTimeParser::parse($this->$attribute,$format);
            $end=CDateTimeParser::parse($compareTo,$format);
            //a little php trick - safe than eval and easier than a big switch statement
            if (version_compare($start,$end,$compare)) {
                    return;
            } else {
                    $this->addError($attribute, "start date is not $compare end date");
            }
        }

and then we can change the validation rules as follows:

{
return array(
           array('experience_from, experience_to ', 'date', 'format'=>array('dd/MM/yyyy','d/MM/yyyy'), 'allowEmpty'=>true),
           array('created_dt, last_updated, ', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss', 'allowEmpty'=>false),
           array('experience_to','dateCompare','compareAttribute'=>experience_from','operator'=>'>', 'allowEmpty'=>true),
  );
}

Thanks.

Export to excel CGridview filtered/shorted record in Yii.



Recently, i have find an issue to export CGridview filtered record in excel in my Yii application. I have searching out lot many thigs but i did not get exact solution which i want. In all reference tutorial, i can export CGridview record without filtered or shorted record.

Finally i got one solution to export filtered CGridview record to excel using session and toexcel extension of Yii. You can see in following search method, I have stored filtered record in session variable and return it. So whenever i will search any record details it will store in session variable. And later, i will use that session variable to export action.

    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('nationality_id',$this->nationality_id);
        $criteria->compare('nationality_name',$this->nationality_name,true);
        $criteria->compare('nationality_organization_id',$this->nationality_organization_id);
        $criteria->compare('nationality_created_by',$this->nationality_created_by);
        $criteria->compare('nationality_created_date',$this->nationality_created_date,true);

        $nationality_data = new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
        ));
       
        $_SESSION['nationality_records'] = $nationality_data;
        return $nationality_data;
    }

Here, Assign CActiveDataProvider data to session variable.

    public function actionNationalityExportToExcel()
    {
        $this->toExcel($_SESSION['nationality_records'],
        array(
            //'nationality_id::SN',
            'nationality_name',
            'Rel_user.user_organization_email_id',
            'Rel_org.organization_name',
       
        ),
        'Nationality',
        array(
            'creator' => 'RudraSoftech',
        ),
        'Excel2007'
        );
    }

Note : Also go throw the toexcel extension and put require class file in extension folder directory.

Using this extension you can export data in excel in multiple excel version format like 2005 and 2007.

Static Radio Button List in Yii

Generate RadioButtonList

The following code:

echo CHtml::RadioButtonList('id', '', array('student'=>'Student','employee'=>'Employee'));

will generate:

<input value="student" id="id_0" type="radio" name="id">
<label for="id_0">Student</label>
<br>
<input value="employee" id="id_1" type="radio" name="id">
<label for="id_1">Employee</label>

Other tricks:

Display them inline without '<br>' separator:


echo CHtml::RadioButtonList('id', '', array('student'=>'Student','employee'=>'Employee'), 
array('labelOptions'=>array('style'=>'display:inline'), separator'=>''));