Pages

Sunday, May 18, 2014

Check XSS script when form submit - PHP

If you want to check XSS script than please write below code:

checkMagicQuotes();
checkXssScript();

function checkMagicQuotes()
{
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
function stripslashes_deep($value)
   {
       return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
   }
   $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
    $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
}

function checkXssScript()
{
function stripXss($value)
{
$tags = array(
    '@<script[^>]*?>.*?</script>@si',
    '@&#(\d+);@e',
    '@\[\[(.*?)\]\]@si',
    '@\[!(.*?)!\]@si',
    '@\[\~(.*?)\~\]@si',
    '@\[\((.*?)\)\]@si',
    '@{{(.*?)}}@si',
    '@\[\*(.*?)\*\]@si'
   );
   return is_array($value) ? array_map('stripXss', $value) : preg_replace($tags, '', $value);
}
$_POST    = array_map('stripXss', $_POST);
$_GET     = array_map('stripXss', $_GET);
$_COOKIE  = array_map('stripXss', $_COOKIE);
$_REQUEST = array_map('stripXss', $_REQUEST);
}

Monday, May 12, 2014

convert PHP Array to XML with attributes - [resolved]

If you want to convert array to XML in PHP than please use below class:

$xml = Array2XML::createXML('OrderLists', $orderXML);

class Array2XML {

    private static $xml = null;
private static $encoding = 'UTF-8';

    /**
     * Initialize the root XML node [optional]
     * @param $version
     * @param $encoding
     * @param $format_output
     */
    public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
        self::$xml = new DomDocument($version, $encoding);
        self::$xml->formatOutput = $format_output;
self::$encoding = $encoding;
    }

    /**
     * Convert an Array to XML
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DomDocument
     */
    public static function &createXML($node_name, $arr=array()) {
        $xml = self::getXMLRoot();
        $xml->appendChild(self::convert($node_name, $arr));

        self::$xml = null;    // clear the xml node in the class for 2nd time use.
        return $xml;
    }

    /**
     * Convert an Array to XML
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DOMNode
     */
    private static function &convert($node_name, $arr=array()) {

        //print_arr($node_name);
        $xml = self::getXMLRoot();
        $node = $xml->createElement($node_name);

        if(is_array($arr)){
            // get the attributes first.;
            if(isset($arr['@attributes'])) {
                foreach($arr['@attributes'] as $key => $value) {
                    if(!self::isValidTagName($key)) {
                        throw new Exception('[Array2XML] Illegal character in attribute name. attribute: '.$key.' in node: '.$node_name);
                    }
                    $node->setAttribute($key, self::bool2str($value));
                }
                unset($arr['@attributes']); //remove the key from the array once done.
            }

            // check if it has a value stored in @value, if yes store the value and return
            // else check if its directly stored as string
            if(isset($arr['@value'])) {
                $node->appendChild($xml->createTextNode(self::bool2str($arr['@value'])));
                unset($arr['@value']);    //remove the key from the array once done.
                //return from recursion, as a note with value cannot have child nodes.
                return $node;
            } else if(isset($arr['@cdata'])) {
                $node->appendChild($xml->createCDATASection(self::bool2str($arr['@cdata'])));
                unset($arr['@cdata']);    //remove the key from the array once done.
                //return from recursion, as a note with cdata cannot have child nodes.
                return $node;
            }
        }

        //create subnodes using recursion
        if(is_array($arr)){
            // recurse to get the node for that key
            foreach($arr as $key=>$value){
                if(!self::isValidTagName($key)) {
                    throw new Exception('[Array2XML] Illegal character in tag name. tag: '.$key.' in node: '.$node_name);
                }
                if(is_array($value) && is_numeric(key($value))) {
                    // MORE THAN ONE NODE OF ITS KIND;
                    // if the new array is numeric index, means it is array of nodes of the same kind
                    // it should follow the parent key name
                    foreach($value as $k=>$v){
                        $node->appendChild(self::convert($key, $v));
                    }
                } else {
                    // ONLY ONE NODE OF ITS KIND
                    $node->appendChild(self::convert($key, $value));
                }
                unset($arr[$key]); //remove the key from the array once done.
            }
        }

        // after we are done with all the keys in the array (if it is one)
        // we check if it has any text value, if yes, append it.
        if(!is_array($arr)) {
            $node->appendChild($xml->createTextNode(self::bool2str($arr)));
        }

        return $node;
    }

    /*
     * Get the root XML node, if there isn't one, create it.
     */
    private static function getXMLRoot(){
        if(empty(self::$xml)) {
            self::init();
        }
        return self::$xml;
    }

    /*
     * Get string representation of boolean value
     */
    private static function bool2str($v){
        //convert boolean to text value.
        $v = $v === true ? 'true' : $v;
        $v = $v === false ? 'false' : $v;
        return $v;
    }

    /*
     * Check if the tag name or attribute name contains illegal characters
     * Ref: http://www.w3.org/TR/xml/#sec-common-syn
     */
    private static function isValidTagName($tag){
        $pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i';
        return preg_match($pattern, $tag, $matches) && $matches[0] == $tag;
    }
}


Source From: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes/

Mapping multiple domains to wordpress

If you want to mapping multiple domains to one blog than you have to follow below procedure:

1. Point all domains nameserver(DNS) from domain account settings.
2. Than write below code in "wp-config.php" file after "table_prefix" code:

- define('WP_SITEURL','http://'.$_SERVER['HTTP_HOST']);
- define('WP_HOME','http://'.$_SERVER['HTTP_HOST']);

- Now, go to the wordpress admin panel >> General >> Settings. Here, you can see "WordPress Address (URL)" and "Site Address (URL)" both are disabled. It means your wordpress is ready for multiple domains.

Thursday, May 8, 2014

MySQL Update Query using a join

If you want to update any records with join of two tables than please write below code:

Update wp_posts as p
LEFT JOIN wp_postmeta as pm on pm.post_id = p.ID
set p.post_title = "changed title" where pm.meta_key = 'test_post_meta' AND pm.meta_value = '123345346'

Tuesday, May 6, 2014

jQuery multiple radio fields validation of groups

- I have below options for input radio fields:

<input type="radio"  name="option1" value="1" />
<input type="radio"  name="option1" value="2" />
<input type="radio"  name="option1" value="3" />
<input type="radio"  name="option1" value="4" />
                                           
<input type="radio"  name="option2" value="5" />
<input type="radio"  name="option2" value="6" />
<input type="radio"  name="option2" value="7" />
<input type="radio"  name="option2" value="8" />

<input type="radio"  name="option3" value="9"  />
<input type="radio"  name="option3" value="10" />
<input type="radio"  name="option3" value="11" />
<input type="radio"  name="option3" value="12" />

<input type="radio"  name="option4" value="13" />
<input type="radio"  name="option4" value="14" />
<input type="radio"  name="option4" value="15" />
<input type="radio"  name="option4" value="16" />


- Please write below jQuery for all radio fields:

var radioNames = []
    $('input[type="radio"]').each(function () {
        var radioName = $(this).attr('name');
        if ($.inArray(radioName, radioNames) == -1) radioNames.push(radioName);
    });

    // validation for each radio group
    $.each(radioNames, function (i, fieldName) {
        if ($('input[name="' + fieldName + '"]:checked').length == 0) {
            console.log('Please check ' + fieldName);
        }
    });

Creating "Hello World" Magento Module

To start with a new Magento module, you have to create a module code folder under an appropriate code pool.
Lets create "Hello World" module module.

Step 1:

- Please create ".xml" file for module as below:
\app\etc\modules\Demomodule_Helloworld.xml

<?xml version="1.0"?>
<config>
<modules>
<Demomodule_Helloworld>
<active>true</active>
<codePool>local</codePool>
</Demomodule_Helloworld>
</modules>
</config>


Step 2:

Now, you have to create config file for module setup as below:

\app\code\local\Demomodule\Helloworld\etc\config.xml

<?xml version="1.0"?>
<config>
<modules>
<Demomodule_Helloworld>
<version>1.0.0</version>
</Demomodule_Helloworld>
</modules>
<frontend>
        <routers>
            <helloworld>
                <use>standard</use>
                <args>
                    <module>Demomodule_Helloworld</module>
                    <frontName>helloworld</frontName>
                </args>
            </helloworld>
        </routers>
        <layout>
            <updates>
                <helloworld>
                    <file>helloworld.xml</file>
                </helloworld>
            </updates>
        </layout>
    </frontend>
</config>


Step 3: 

Please create controller file with below information.

\app\code\local\Demomodule\Helloworld\controllers\IndexController.php

<?php
class Demomodule_Helloworld_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
$this->loadLayout();     
$this->renderLayout();
    }
}

Step 4:

Please create ".xml" file for plugin "Block" setup as below:

\app\design\frontend\default\default\layout\helloworld.xml

<?xml version="1.0"?>
    <layout version="0.1.0">
<helloworld_index_index>
<reference name="content">
<block type="core/template" name="helloworldpage" template="helloworld/content.phtml"/>
</reference>
</helloworld_index_index>

</layout>


Step 5:

Now, you have to create new ".phtml" file for your content as below:

\app\design\frontend\default\default\template\helloworld\content.phtml

<div class="banner-left box">
<?php echo $this->__('This is the demo "Hello World" module.');?>
</div>

Thursday, May 1, 2014

Contact Form 7 Create Custom validation for all fields - [resolved]

If you want to add custom validation for contact form 7 input fields than please write below code:

add_filter('wpcf7_validate_FIELDNAME','cf7_custom_form_validation', 10, 2); // wpcf7_validate_email or wpcf7_validate_email*

function cf7_custom_form_validation($result,$tag) {
    /*
        Here you can write your custom code for validation
    */
}

Contact Form 7 customize response message - [resolved]

If you want to change response message by code for contact form 7 than please write below code:

add_action("wpcf7_ajax_json_echo", "cf7_change_response_message",10,2);

function cf7_change_response_message($items, $result){
    /*
        Here you can write your custom code for response message
    */
}