Wednesday, September 5, 2012

ups, fedex and USPS shipping integration with joomla easily

download here source code
step-1-> create a fedex10.php under /administrator/components/com_virtuemart/classes/shipping
---------------------------------------------------------------------------------------------
<?php
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
/* You must fill in the "Service Logins
/* values below for the example to work   
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/

/*********** Shipping Services ************/
/* Here's an array of all the standard
/* shipping rates. You'll probably want to
/* comment out the ones you don't want
/******************************************/
// UPS
//$services['ups']['14'] = 'Next Day Air Early AM';
//$services['ups']['01'] = 'Next Day Air';
$services['ups']['65'] = 'Saver';
//$services['ups']['59'] = '2nd Day Air Early AM';
$services['ups']['02'] = '2nd Day Air';
$services['ups']['12'] = '3 Day Select';
$services['ups']['03'] = 'Ground';
/*$services['ups']['11'] = 'Standard';
$services['ups']['07'] = 'Worldwide Express';
$services['ups']['54'] = 'Worldwide Express Plus';
$services['ups']['08'] = 'Worldwide Expedited';*/


// FedEx
$services['fedex']['FEDEXGROUND'] = 'Ground';
$services['fedex']['PRIORITYOVERNIGHT'] = 'Priority Overnight';
$services['fedex']['STANDARDOVERNIGHT'] = 'Standard Overnight';
//$services['fedex']['FIRSTOVERNIGHT'] = 'First Overnight';
//$services['fedex']['FEDEX2DAY'] = '2 Day';
$services['fedex']['FEDEXEXPRESSSAVER'] = 'Express Saver';

/*$services['fedex']['FEDEX1DAYFREIGHT'] = 'Overnight Day Freight';
$services['fedex']['FEDEX2DAYFREIGHT'] = '2 Day Freight';
$services['fedex']['FEDEX3DAYFREIGHT'] = '3 Day Freight';
$services['fedex']['GROUNDHOMEDELIVERY'] = 'Home Delivery';
$services['fedex']['INTERNATIONALECONOMY'] = 'International Economy';
$services['fedex']['INTERNATIONALFIRST'] = 'International First';
$services['fedex']['INTERNATIONALPRIORITY'] = 'International Priority';*/

 $dbu = new ps_DB; // user data
        $dbv = new ps_DB; // vendor data
        $dbc = new ps_DB; // country data

        // get user info
        $q  = "SELECT * FROM #__{vm}_user_info, #__{vm}_country WHERE user_info_id='" . @$_REQUEST["ship_to_info_id"]."' AND ( country=country_2_code OR country=country_3_code)";
        $dbu->query($q);
        if ($dbu->num_rows()==0) {
            $vmLogger->debug("Fedex::__construct() no user information returned from database where \$_REQUEST[\"ship_to_info_id\"]==".@$vars["ship_to_info_id"]);

            // missing ship_to_info_id. probably a shop set up with no "choose a shipping address" step
            // let's choose the first ST address we can find
            $q="SELECT * FROM #__{vm}_user_info, #__{vm}_country WHERE user_id='". $_SESSION['auth']['user_id'] ."' AND address_type='ST' AND ( country=country_2_code OR country=country_3_code)";
            $dbu->query($q);
            if ($dbu->num_rows()==0) {
                // or default to BT address.
                $vmLogger->debug("Fedex::__construct() - Using first BT address found.");
                $q="SELECT * FROM #__{vm}_user_info, #__{vm}_country WHERE user_id='". $_SESSION['auth']['user_id'] ."' AND address_type='BT' AND ( country=country_2_code OR country=country_3_code)";
                $dbu->query($q);

                // ups module will fail if none of these queries return results.
            } else {
                $vmLogger->debug("Fedex::__construct() - Using first ST address found.");
            }
        }
        $dbu->next_record();
       
        // destination country
        $dbu->f("country_2_code");
        // destination state code
        // TODO: Make sure this works for Non-US countries
        $dbu->f('state');       
        //destination ZIP
        trim($dbu->f("zip"));       
        // Get a list of vendor data (including shipping address)
        $q  = "SELECT * FROM #__{vm}_vendor WHERE vendor_id='".$_SESSION['ps_vendor_id']."'";
        $dbv->query($q);
        $dbv->next_record();

        // source country
        $vendor_country_2_code;
       
       
        // source state code
        // TODO: Make sure this works for Non-US countries
        $dbv->f('vendor_state');
       
        // Source ZIP
       
         trim($dbv->f("vendor_zip"));

// Config
global $weight_total;
//echo $weight_total."<br>";
$formarweight=number_format($weight_total,2);
//echo $formarweight."<br>";
$arrayweight=explode('.',$formarweight);
//print_r($arrayweight)."<br>";
$extract_weight=$arrayweight[0].'.'.intval($arrayweight[1]);
//echo $extract_weight;
$config = array(
    // Services
    'services' => $services,
    // Weight
    'weight' =>$extract_weight, // Default = 1
    'weight_units' => 'lb', // lb (default), oz, gram, kg
    // Size
    //'size_length' => 0, // Default = 8
    //'size_width' => 6, // Default = 4
    //'size_height' => 3, // Default = 2
    //'size_units' => 'in', // in (default), feet, cm
    // From
    'from_zip' =>  trim($dbv->f("vendor_zip")),
    'from_state' =>$dbv->f('vendor_state'), // Only Required for FedEx
    'from_country' => $vendor_country_2_code,
    // To
    'to_zip' => trim($dbu->f("zip")),
    'to_state' =>$dbu->f('state'), // Only Required for FedEx
    'to_country' => $dbu->f("country_2_code"),
   
    // Service Logins
    'ups_access' => '0C2D05F55AF310D0', // UPS Access License Key
    'ups_user' => 'dwstudios', // UPS Username 
    'ups_pass' => 'dwstudios', // UPS Password 
    'ups_account' => '81476R', // UPS Account Number
    'usps_user' => '229DARKW7858', // USPS User Name
    'fedex_account' => '510087020', // FedEX Account Number
    'fedex_meter' => '100005263' // FedEx Meter Number
);

require_once(CLASSPATH ."shipping/fedex10/ShippingCalculator.php");
// Create Class (with config array)
$ship = new ShippingCalculator($config);
// Get Rates
$rates_array = $ship->calculate();



        foreach ($rates_array['fedex'] as $fedexservicename=>$fedexrate)
        {
            if($fedexrate!=""||$fedexrate!=NULL ||$fedexrate!=0)
            {
            $fedexservice_name[]=$services['fedex'][$fedexservicename];
            $fedexservice_name_key[]=$fedexservicename;
            $fedexservice_rate[] = $fedexrate;
            }
        }
       
    $cleancount=count($fedexservice_rate);
    if ($cleancount == 0)
        {
    echo '<img src="fedex.jpg" border="0"><br>';
            $vmLogger->notice("Fedex not provide the service your zip code.");
            return false;
        }
        else
        {
        $radioSelected = false;
        // iterate each service option and output information
        echo "<div style='margin-bottom:20px;'>";
          echo '<img src="fedex.jpg" border="0"><br>';
          for ($service_loop=0;$service_loop < $cleancount;$service_loop++)
            {       
            $html = "";           
            $current_service_display_name = str_replace('&lt;sup&gt;&amp;reg;&lt;/sup&gt;','',$fedexservice_name[$service_loop]);           
            $servicerate = $GLOBALS['CURRENCY']->convert( $fedexservice_rate[$service_loop], 'USD',$this->currency);
            $servicerateFormatted = $CURRENCY_DISPLAY->getFullValue($servicerate);
           
            $shipping_rate_id = urlencode("fedexv2|FEDEX|".html_entity_decode($current_service_display_name)."|".$servicerate);
           
            if (((urlencode(@$d["shipping_rate_id"])==$shipping_rate_id) || ($radioSelected==false))) {
                $checked = "checked=\"checked\"";
                $radioSelected = true;
            }else{
                $checked = "";
            }
            $html .= "\n<input type=\"radio\" name=\"shipping_rate_id\" ".$checked." value=\"$shipping_rate_id\" />\n";
            $html .= html_entity_decode($current_service_display_name)." ";
            $html .= "<strong>(" . $servicerateFormatted . ")</strong>";           
            $html .= "<br />";
            // output the html
            echo $html;
            $_SESSION[$shipping_rate_id] = 1;
           
           }
           echo "</div>";
        }

//start ups shipping
  foreach ($rates_array['ups'] as $upsservicename=>$upsrate)
              {
                if($upsrate!=""||$upsrate!=NULL ||$upsrate!=0)
                {
                $upsservice_name[]=$services['ups'][$upsservicename];
                $upsservice_name_key[]=$upsservicename;
                $upsservice_rate[] = $upsrate;
                }
              }
             $cleancount=count($upsservice_rate);

             if ($cleancount == 0)
                {
                   echo    '<img src="ups_logo.jpg" border="0"><br>';
                   $vmLogger->notice("UPS not provide the service your zip code.");
                   return false;
                 }else
                 {
                     $radioSelected = false;
                   // iterate each service option and output information
                   echo "<div style='margin-bottom:20px;'>";
                   echo '<img src="ups_logo.jpg" border="0"><br>';
                   for ($service_loop=0;$service_loop < $cleancount;$service_loop++)
                   {
                        $html = "";           
                        $current_service_display_name = str_replace('&lt;sup&gt;&amp;reg;&lt;/sup&gt;','',$upsservice_name[$service_loop]);           
                        $servicerate = $GLOBALS['CURRENCY']->convert( $upsservice_rate[$service_loop], 'USD',$this->currency);
                        $servicerateFormatted = $CURRENCY_DISPLAY->getFullValue($servicerate);               
                        $shipping_rate_id = urlencode("ups|UPS|".html_entity_decode($current_service_display_name)."|".$servicerate);           
                    if (((urlencode(@$d["shipping_rate_id"])==$shipping_rate_id) || ($radioSelected==false)))
                       {
                         $checked = "checked=\"checked\"";
                         $radioSelected = true;
                       }else
                       {
                        $checked = "";
                       }
                        $html .= "\n<input type=\"radio\" name=\"shipping_rate_id\" value=\"$shipping_rate_id\" />\n";
                        $html .= html_entity_decode($current_service_display_name)." ";
                        $html .= "<strong>(" . $servicerateFormatted . ")</strong>";               
                        $html .= "<br />";
                       // output the html
                        echo $html;
                        $_SESSION[$shipping_rate_id] = 1;
               
                     }
                                echo "</div>";
                   }


?>
---------------------------------------------End shipping class------------------------------------------
2 step-> create fedex10.ini under /administrator/components/com_virtuemart/classes/shipping

# $Id: fedex10.ini 617 2007-01-04 12:43:08 -0700 (Thu, 04 Jan 2012) soeren_nb $
[General]
name = FedEXdc
version = 10.02
creationDate = September 2005
author

= AJay
authorEmail = bikash@techwave.com
authorUrl = www.techwave.com.com/
copyright = (c) 2012 Vermonster LLC
license = GNU/GPL
description = The FedEX

Shipping module by bikash ranjan nayak.

[File]
filename = fedex10.php
-------------------------------------------End ini file-------------------------------------------------------

step 3-> create to ShippingCalculator.php under administrator/components/com_virtuemart/classes/shipping/fedex10
---------------------------------------------------------------------------------------------------
<?php
class ShippingCalculator  {
    // Defaults
    var $weight = 1;
    var $weight_unit = "lb";
    var $size_length = 4;
    var $size_width = 8;
    var $size_height = 2;
    var $size_unit = "in";
    var $debug = false; // Change to true to see XML sent and recieved
   
    // Batch (get all rates in one go, saves lots of time)
    var $batch_ups = false; // Currently Unavailable
    var $batch_usps = true;
    var $batch_fedex = false; // Currently Unavailable
   
    // Config (you can either set these here or send them in a config array when creating an instance of the class)
    var $services;
    var $from_zip;
    var $from_state;
    var $from_country;
    var $to_zip;
    var $to_stat;
    var $to_country;
    var $ups_access;
    var $ups_user;
    var $ups_pass;
    var $ups_account;
    var $usps_user;
    var $fedex_account;
    var $fedex_meter;
   
    // Results
    var $rates;
   
    // Setup Class with Config Options
    function ShippingCalculator($config) {
        if($config) {
            foreach($config as $k => $v) $this->$k = $v;
        }
    }
   
    // Calculate
    function calculate($company = NULL,$code = NULL) {
        $this->rates = NULL;
        $services = $this->services;
        if($company and $code) $services[$company][$code] = 1;
        foreach($services as $company => $codes) {
            foreach($codes as $code => $name) {
                switch($company) {
                    case "ups":
                        /*if($this->batch_ups == true) $batch[] = $code; // Batch calculation currently unavaiable
                        else*/ $this->rates[$company][$code] = $this->calculate_ups($code);
                        break;
                    case "usps":
                        if($this->batch_usps == true) $batch[] = $code;
                        else $this->rates[$company][$code] = $this->calculate_usps($code);
                        break;
                    case "fedex":
                        /*if($this->batch_fedex == true) $batch[] = $code; // Batch calculation currently unavaiable
                        else*/ $this->rates[$company][$code] = $this->calculate_fedex($code);
                        break;
                }
            }
            // Batch Rates
            //if($company == "ups" and $this->batch_ups == true and count($batch) > 0) $this->rates[$company] = $this->calculate_ups($batch);
            if($company == "usps" and $this->batch_usps == true and count($batch) > 0) $this->rates[$company] = $this->calculate_usps($batch);
            //if($company == "fedex" and $this->batch_fedex == true and count($batch) > 0) $this->rates[$company] = $this->calculate_fedex($batch);
        }
       
        return $this->rates;
    }
   
    // Calculate UPS
    function calculate_ups($code) {
        $url = "https://www.ups.com/ups.app/xml/Rate";
        $data = '<?xml version="1.0"?> 
<AccessRequest xml:lang="en-US"> 
    <AccessLicenseNumber>'.$this->ups_access.'</AccessLicenseNumber> 
    <UserId>'.$this->ups_user.'</UserId> 
    <Password>'.$this->ups_pass.'</Password> 
</AccessRequest> 
<?xml version="1.0"?> 
<RatingServiceSelectionRequest xml:lang="en-US"> 
    <Request> 
        <TransactionReference> 
            <CustomerContext>Bare Bones Rate Request</CustomerContext> 
            <XpciVersion>1.0001</XpciVersion> 
        </TransactionReference> 
        <RequestAction>Rate</RequestAction> 
        <RequestOption>Rate</RequestOption> 
    </Request> 
    <PickupType> 
        <Code>01</Code> 
    </PickupType> 
    <Shipment> 
        <Shipper> 
            <Address> 
                <PostalCode>'.$this->from_zip.'</PostalCode> 
                <CountryCode>'.$this->from_country.'</CountryCode> 
            </Address> 
        <ShipperNumber>'.$this->ups_account.'</ShipperNumber> 
        </Shipper> 
        <ShipTo> 
            <Address> 
                <PostalCode>'.$this->to_zip.'</PostalCode> 
                <CountryCode>'.$this->to_country.'</CountryCode> 
            <ResidentialAddressIndicator/> 
            </Address> 
        </ShipTo> 
        <ShipFrom> 
            <Address> 
                <PostalCode>'.$this->from_zip.'</PostalCode> 
                <CountryCode>'.$this->from_country.'</CountryCode> 
            </Address> 
        </ShipFrom> 
        <Service> 
            <Code>'.$code.'</Code> 
        </Service> 
        <Package> 
            <PackagingType> 
                <Code>02</Code> 
            </PackagingType> 
            <Dimensions> 
                <UnitOfMeasurement> 
                    <Code>IN</Code> 
                </UnitOfMeasurement> 
                <Length>'.($this->size_unit != "in" ? $this->convert_sze($this->size_length,$this->size_unit,"in") : $this->size_length).'</Length> 
                <Width>'.($this->size_unit != "in" ? $this->convert_sze($this->size_width,$this->size_unit,"in") : $this->size_width).'</Width> 
                <Height>'.($this->size_unit != "in" ? $this->convert_sze($this->size_height,$this->size_unit,"in") : $this->size_height).'</Height> 
            </Dimensions> 
            <PackageWeight> 
                <UnitOfMeasurement> 
                    <Code>LBS</Code> 
                </UnitOfMeasurement> 
                <Weight>'.($this->weight_unit != "lb" ? $this->convert_weight($this->weight,$this->weight_unit,"lb") : $this->weight).'</Weight> 
            </PackageWeight> 
        </Package> 
    </Shipment> 
</RatingServiceSelectionRequest>';
       
        // Curl
        $results = $this->curl($url,$data);
       
        // Debug
        if($this->debug == true) {
            print "<xmp>".$data."</xmp><br />";
            print "<xmp>".$results."</xmp><br />";
        }
       
        // Match Rate
        preg_match('/<MonetaryValue>(.*?)<\/MonetaryValue>/',$results,$rate);
       
        return $rate[1];
    }
   
    // Calculate USPS
    function calculate_usps($code) {
        // Weight (in lbs)
        if($this->weight_unit != 'lb') $weight = $this->convert_weight($weight,$this->weight_unit,'lb');
        else $weight = $this->weight;
        // Split into Lbs and Ozs
        $lbs = floor($weight);
        $ozs = ($weight - $lbs)  * 16;
        if($lbs == 0 and $ozs < 1) $ozs = 1;
        // Code(s)
        $array = true;
        if(!is_array($code)) {
            $array = false;
            $code = array($code);
        }
       
        $url = "http://Production.ShippingAPIs.com/ShippingAPI.dll";
        $data = 'API=RateV2&XML=<RateV2Request USERID="'.$this->usps_user.'">';
        foreach($code as $x => $c) $data .= '<Package ID="'.$x.'"><Service>'.$c.'</Service><ZipOrigination>'.$this->from_zip.'</ZipOrigination><ZipDestination>'.$this->to_zip.'</ZipDestination><Pounds>'.$lbs.'</Pounds><Ounces>'.$ozs.'</Ounces><Size>REGULAR</Size><Machinable>TRUE</Machinable></Package>';
        $data .= '</RateV2Request>';
       
        // Curl
        $results = $this->curl($url,$data);
       
        // Debug
        if($this->debug == true) {
            print "<xmp>".$data."</xmp><br />";
            print "<xmp>".$results."</xmp><br />";
        }
       
        // Match Rate(s)
        preg_match_all('/<Package ID="([0-9]{1,3})">(.+?)<\/Package>/',$results,$packages);
        foreach($packages[1] as $x => $package) {
            preg_match('/<Rate>(.+?)<\/Rate>/',$packages[2][$x],$rate);
            $rates[$code[$package]] = $rate[1];
        }
        if($array == true) return $rates;
        else return $rate[1];
    }
   
    // Calculate FedEX
    function calculate_fedex($code) {
        $url = "https://gatewaybeta.fedex.com/GatewayDC";
        $data = '<?xml version="1.0" encoding="UTF-8" ?>
<FDXRateRequest xmlns:api="http://www.fedex.com/fsmapi" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FDXRateRequest.xsd">
    <RequestHeader>
        <CustomerTransactionIdentifier>Express Rate</CustomerTransactionIdentifier>
        <AccountNumber>'.$this->fedex_account.'</AccountNumber>
        <MeterNumber>'.$this->fedex_meter.'</MeterNumber>
        <CarrierCode>'.(in_array($code,array('FEDEXGROUND','GROUNDHOMEDELIVERY')) ? 'FDXG' : 'FDXE').'</CarrierCode>
    </RequestHeader>
    <DropoffType>REGULARPICKUP</DropoffType>
    <Service>'.$code.'</Service>
    <Packaging>YOURPACKAGING</Packaging>
    <WeightUnits>LBS</WeightUnits>
    <Weight>'.number_format(($this->weight_unit != 'lb' ? convert_weight($this->weight,$this->weight_unit,'lb') : $this->weight), 1, '.', '').'</Weight>
    <OriginAddress>
        <StateOrProvinceCode>'.$this->from_state.'</StateOrProvinceCode>
        <PostalCode>'.$this->from_zip.'</PostalCode>
        <CountryCode>'.$this->from_country.'</CountryCode>
    </OriginAddress>
    <DestinationAddress>
        <StateOrProvinceCode>'.$this->to_state.'</StateOrProvinceCode>
        <PostalCode>'.$this->to_zip.'</PostalCode>
        <CountryCode>'.$this->to_country.'</CountryCode>
    </DestinationAddress>
    <Payment>
        <PayorType>SENDER</PayorType>
    </Payment>
    <PackageCount>1</PackageCount>
</FDXRateRequest>';
       
        // Curl
        $results = $this->curl($url,$data);
       
        // Debug
        if($this->debug == true) {
            print "<xmp>".$data."</xmp><br />";
            print "<xmp>".$results."</xmp><br />";
        }
   
        // Match Rate
        preg_match('/<NetCharge>(.*?)<\/NetCharge>/',$results,$rate);
       
        return $rate[1];
    }
   
    // Curl
    function curl($url,$data = NULL) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        if($data) {
            curl_setopt($ch, CURLOPT_POST,1); 
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        } 
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        $contents = curl_exec ($ch);
       
        return $contents;
       
        curl_close ($ch);
    }
   
    // Convert Weight
    function convert_weight($weight,$old_unit,$new_unit) {
        $units['oz'] = 1;
        $units['lb'] = 0.0625;
        $units['gram'] = 28.3495231;
        $units['kg'] = 0.0283495231;
       
        // Convert to Ounces (if not already)
        if($old_unit != "oz") $weight = $weight / $units[$old_unit];
       
        // Convert to New Unit
        $weight = $weight * $units[$new_unit];
       
        // Minimum Weight
        if($weight < .1) $weight = .1;
       
        // Return New Weight
        return round($weight,2);
    }
   
    // Convert Size
    function convert_size($size,$old_unit,$new_unit) {
        $units['in'] = 1;
        $units['cm'] = 2.54;
        $units['feet'] = 0.083333;
       
        // Convert to Inches (if not already)
        if($old_unit != "in") $size = $size / $units[$old_unit];
       
        // Convert to New Unit
        $size = $size * $units[$new_unit];
       
        // Minimum Size
        if($size < .1) $size = .1;
       
        // Return New Size
        return round($size,2);
    }
   
    // Set Value
    function set_value($k,$v) {
        $this->$k = $v;
    }

?>
--------------------------------end---------------------------------------------------
i hope enjoy and save the time
-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

Tuesday, September 4, 2012

What is cloud computing?


Cloud computing changes the way we think about technology. Cloud is a
computing model providing web-based software, middleware and
computing resources on demand.
By deploying technology as a service, you give users access only to the
resources they need for a particular task. This prevents you from paying
for idle computing resources. Cloud computing can also go beyond cost
savings by allowing your users to access the latest software and
infrastructure offerings to foster business innovation.

Cloud computing consists of hardware and software resources made available on the Internet as managed third-party services. These services typically provide access to advanced software applications and high-end networks of server computers.

Types of Cloud Computing

Service providers create cloud computing systems to serve common business or research needs. Examples of cloud computing services include:
  • virtual IT - configure and utilize remote, third-party servers as extensions to a company's local IT network

  • software - utilize commercial software applications, or develop and remotely host custom built applications

  • network storage - back up or archive data across the Internet to a provider without needing to know the physical location of storage
Cloud computing systems all generally are designed for scalability to support large numbers of customers and surges in demand.

Examples of Cloud Computing Services

These examples illustrate the different types of cloud computing services available today: Some providers offer cloud computing services for free while others require a paid subscription.

Cloud Computing Pros and Cons

Service providers are responsible for installing and maintaining core technology within the cloud. Some customers prefer this model because it limits their own manageability burden. However, customers cannot directly control system stability in this model and are highly dependent on the provider instead. Cloud computing systems are normally designed to closely track all system resources, which enables providers to charge customers according to the resources each consumes. Some customers will prefer this so-called metered billing approach to save money, while others will prefer a flat-rate subscription to ensure predictable monthly or yearly costs.
Using a cloud computing environment generally requires you to send data over the Internet and store it on a third-party system. The privacy and security risks associated with this model must be weighed against alternatives.

Friday, August 31, 2012

how to clean link using php

function clickable_link($var)
{
$text = $var;
$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
$ret = ' ' . $text;
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1\\2", $ret);
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1\\2", $ret);
$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1\\2@\\3", $ret);
$ret = substr($ret, 1);
return $ret;
}

-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

how to check ban-word user in put using php

function banned_words_chk($phrase)
{
global $conn, $config;
$query = "SELECT word from bans_words";
$executequery = $conn->Execute($query);
$bwords = $executequery->getarray();
$found = 0;
$words = explode(" ", $phrase);
foreach($words as $word)
{
foreach($bwords as $bword)
{
if($word == $bword[0])
{
$found++;
}
else
{
$pos2 = strpos($word, $bword[0]);
if($pos2 !== false)
{
$found++;
}
}
}
}
if($found > 0)
{
return true;
}
else
{
return false;
}
}
-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

how to send mail html using php with example

function mailme($sendto,$sendername,$from,$subject,$sendmailbody,$bcc="")
{
global $SERVER_NAME;
$subject = nl2br($subject);
$sendmailbody = nl2br($sendmailbody);
$sendto = $sendto;
if($bcc!="")
{
$headers = "Bcc: ".$bcc."\n";
}
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "X-Priority: 3\n";
$headers .= "X-MSMail-Priority: Normal\n";
$headers .= "X-Mailer: PHP/"."MIME-Version: 1.0\n";
$headers .= "From: " . $from . "\n";
$headers .= "Content-Type: text/html\n";
mail("$sendto","$subject","$sendmailbody","$headers");
}
-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

how to get htmlenties tag value in joomla

//in controller page

function store()
{
$row =& $this->getTable();
$data = JRequest::get( 'post');
/* Get proper HTML-code for your HTML-encoded field now by using JREQUEST_ALLOWHTML*/
$data['fielsd']=JRequest::getVar( 'fielsd', '', 'post', 'string', JREQUEST_ALLOWHTML );
/* now proceed as suggested */
$row->bind($data);
-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

you tube url parsing uisng php and play on web page


/*
* YoutubeParser() PHP class
* @author: takien
* @version: 1.0
* @date: June 16, 2012
* URL: http://takien.com/864/php-how-to-parse-youtube-url-to-get-video-id-thumbnail-image-or-embed-code.php
*
* @param string $source content source to be parsed, eg: a string or page contains youtube links or videos.
* @param boolean $unique whether the return should be unique (duplicate result will be removed)
* @param boolean $suggested whether show suggested video after finished playing
* @param boolean $https whether use https or http, default false ( http )
* @param string $width width of embeded video, default 420
* @param string $height height of embeded video, default 315
* @param boolean $privacy whether to use 'privacy enhanced mode or not',
* if true then the returned Youtube domain would be youtube-nocookie.com
*/
class YoutubeParser{
var $source = '';
var $unique = false;
var $suggested = false;
var $https = false;
var $privacy = false;
var $width = 354;
var $height = 234;
function __construct(){
}
function set($key,$val){
return $this->$key = $val;
}
function getall(){
$return = Array();
$domain = 'http'.($this->https?'s':'').'://www.youtube'.($this->privacy?'-nocookie':'').'.com';
$size = 'width="'.$this->width.'" height="'.$this->height.'"';
preg_match_all('/(youtu.be\/|\/watch\?v=|\/embed\/)([a-z0-9\-_]+)/i',$this->source,$matches);
if(isset($matches[2])){
if($this->unique){
$matches[2] = array_values(array_unique($matches[2]));
}
foreach($matches[2] as $key=>$id) {
$return[$key]['id'] = $id;
$return[$key]['embedold'] = '<img class="mceItemMedia mceItemFlash" data-mce-json="{'video':{},'params':{'movie':null,'allowFullScreen':'true','allowscriptaccess':'flase','src':null},'object_html':'suggested?\'\':\'&amp;amp;rel=0\').\'\&quot;&amp;gt;suggested?\'\':\'&amp;amp;rel=0\').\'\&quot; type=\&quot;application/x-shockwave-flash\&quot; \'.$size.\' allowscriptaccess=\&quot;always\&quot; allowfullscreen=\&quot;true\&quot;&amp;gt;'}" height="240" src="http://bikashnayak.blog.com/wp-includes/js/tinymce/themes/advanced/img/trans.gif" width="320" />';<br />
}<br />
}
return $return[$key]['embedold'];
}
}
$youtube = new YoutubeParser;
$youtube->set('source','http://www.youtube.com/watch?v=R55e-uHQna0&feature=topvideos');
echo'
';
print_r($youtube->getall());
echo'
';
-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

Thursday, August 30, 2012

mvc explanation simply

1).  Model: The model object knows about all the data that need to be displayed. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application. The model represents enterprise data and the business rules that govern access to and updates of this data. Model is not aware about the presentation data and how that data will be displayed to the browser.  
2). View : The view represents the presentation of the application. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it. The view is not dependent on the application logic. It remains same if there is any modification in the business logic. In other words, we can say that it is the responsibility of the of the view's to maintain the consistency in its presentation when the model changes.
3). Controller:  Whenever the user sends a request for something then it always go through the controller. The controller is responsible for intercepting the requests from view and passes it to the model for the appropriate action. After the action has been taken on the data, the controller is responsible for directing the appropriate view to the user. In  GUIs, the views and the controllers often work very closely together.

-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

How to URL rewrite in open cart [SOLVED]

How to configure URL rewrite configuration in Open cart CMS, Please follow below refer step.

step -1->root index.php comment the default (common/seo_url)
example below
//$controller->addPreAction(new Action('common/seo_url')); 


Change to the below code:

Step -2 Create a automatic_seo_url.php file under catalog/controller/common/automatic_seo_url.php

Step3->
Paste the class code into automatic_seo_url.php

-----------------------------------------------------------------------------
<?php
class ControllerCommonAutomaticSeoUrl extends Controller {

    var $_products;
    var    $_categories;
    var $_tmp_cat_path = array();
    var    $_manufacturers;
    var    $_infos;
    var $product_identifier = 'p';
    var $category_identifier = 'c';
    var $manufacturer_identifier = 'm';
    var $info_identifier = 'i';
    var $route_identifier = 'r';
    var $_sep = '-';
    var $_url_ext = ''; // .html, .php etc.
   
    public function index() {
        global $request;
        // Add rewrite to url class
        if ($this->config->get('config_seo_url')) {
            $this->url->addRewrite($this);
        }

        // Decode URL
        if (isset($this->request->get['_route_'])) {
            //decode url
            $parts = explode('/', $this->request->get['_route_']);
            if(count($parts)>=0){
                switch($parts[0]){
                    case $this->product_identifier:
                        // product page
                        // FORMAT = 'p/(int)product_id[/c/(string)path/(string)category_names_can_have_slashes]/product_name'
                        $this->request->get['route'] = 'product/product';
                        $this->request->get['product_id'] = (int) $parts[1];
                        if(isset($parts[2]) && $parts[2] == $this->category_identifier){
                            $this->request->get['path'] = $parts[3];
                        }
                        break;
                    case $this->category_identifier:
                        // category page
                        // FORMAT = 'c/(string)path/category_names_can_have_slashes'
                        $this->request->get['route'] = 'product/category';
                        $this->request->get['path'] = $parts[1];
                        break;
                    case $this->manufacturer_identifier:
                        // manufacturer page
                        // FORMAT = 'm/(int)manufacturer_id/manufacturer_name'
                        $this->request->get['route'] = 'product/manufacturer/product';
                        $this->request->get['manufacturer_id'] = (int) $parts[1];
                        break;
                    case $this->info_identifier:
                        // information page
                        // FORMAT = 'i/(int)information_id/information_name'
                        $this->request->get['route'] = 'information/information';
                        $this->request->get['information_id'] = (int) $parts[1];
                        break;
                    case $this->route_identifier:
                        // other route pages
                        // FORMAT = 'r/(string)route_with_slashes'
                        unset($parts[0]);
                        $this->request->get['route'] = implode('/',$parts);
                        break;
                    default:
                        return $this->index_standard();
                        break;
                }
            }
            if (isset($this->request->get['route'])) {
                return $this->forward($this->request->get['route']);
            }
        }
      
    }

    public function rewrite($link){
   
        $_link = $this->rewrite_standard($link);
        if($_link != $link)return $_link;
      
        if($this->config->get('config_seo_url')){
            $url_data = parse_url(str_replace('&amp;', '&', $link));
            if(!isset($url_data['query']))return $link;
            $url = '';
            $data = array();
            parse_str($url_data['query'], $data);
            if(isset($data['route'])){
                switch($data['route']){
                    case 'product/product':
                        $this->_get_products();
                        $pid = ($data['product_id']) ? $data['product_id'] : 0;
                        unset($data['product_id']);
                        $url .= '/'.$this->product_identifier.'/'.$pid;
                        if(isset($data['path'])){
                            unset($data['path']);
                        }
                        if(isset($this->_products[$pid])){
                            $url .= $this->_traverse_categories($this->_products[$pid]['category_id']);
                            $url .= $this->_products[$pid]['name'];
                        }
                        break;
                    case 'product/category':
                        $data['path'] = isset($data['path']) ? $data['path'] : 0;
                        $ppath = array_reverse(explode('_',$data['path']));
                        $url .= $this->_traverse_categories($ppath[0]);
                        unset($data['path']);
                        break;
                    case 'product/manufacturer/product':
                        $data['manufacturer_id'] = isset($data['manufacturer_id']) ? $data['manufacturer_id'] : 0;
                        $url .= '/'.$this->manufacturer_identifier.'/'.$data['manufacturer_id'];
                        $this->_get_manufacturers();
                        if(isset($this->_manufacturers[$data['manufacturer_id']]))
                            $url .= '/'.$this->_manufacturers[$data['manufacturer_id']];
                        unset($data['manufacturer_id']);
                        break;
                    case 'information/information':
                        $data['information_id'] = isset($data['information_id']) ? $data['information_id'] : 0;
                        $url .= '/'.$this->info_identifier.'/'.$data['information_id'];
                        $this->_get_infos();
                        if(isset($this->_infos[$data['information_id']]))
                            $url .= '/'.$this->_infos[$data['information_id']];
                        unset($data['information_id']);
                        break;
                    case 'common/home':
                        break;
                    default:
                        $url .= '/'.$data['route'];
                        //$url .= '/'.$this->route_identifier.'/'.$data['route'];
                        //return $link;
                        break;
                }
                unset($data['route']);
                $query = '';
                if ($data) {
                    foreach ($data as $key => $value)
                        $query .= '&' . $key . '=' . $value;
                  
                    if ($query)
                        $query = '?' . trim($query, '&');
                }
                return     $url_data['scheme'].'://'.$url_data['host'].(isset($url_data['port']) ? ':'.$url_data['port'] : '').str_replace('/index.php', '', $url_data['path']).rtrim($url,'/').$this->_url_ext.$query;
            }else{
                return $link;
            }
        }else{
            return $link;
        }
    }

    private function get_language(){
        if(!isset($this->_language)){
            $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "language");
            $this->_language = array();
        }
    }

    private function _get_products(){
        if(!isset($this->_product)){
            $this->_products = array();
            $query = $this->db->query("
                SELECT p.product_id, pd.name, pc.category_id FROM " . DB_PREFIX . "product AS p
                LEFT JOIN " . DB_PREFIX . "product_description AS pd ON pd.product_id = p.product_id
                LEFT JOIN " . DB_PREFIX . "product_to_category AS pc ON pc.product_id = p.product_id
                WHERE pd.language_id = ".(int)$this->config->get('config_language_id')." AND p.status = 1");

            foreach($query->rows as $prod)
                $this->_products[$prod['product_id']] = array(
                                                            'name'=>$this->clean_name($prod['name']),
                                                            'category_id'=>$prod['category_id']
                                                            );
        }
    }

    private function _get_categories(){
   
        if(!isset($this->_categories)){
            $this->_categories = array();
            $query = $this->db->query("
                SELECT c.category_id, c.parent_id, cd.name FROM " . DB_PREFIX . "category AS c
                LEFT JOIN " . DB_PREFIX . "category_description AS cd ON cd.category_id = c.category_id
                WHERE cd.category_id = c.category_id AND cd.language_id = ".(int)$this->config->get('config_language_id')." AND c.status = 1");

            foreach($query->rows as $cat){
                $this->_categories[$cat['category_id']] = array(
                                                            'name'=>$this->clean_name($cat['name']),
                                                            'parent'=>$cat['parent_id']
                                                            );
            }
        }
    }

    private function _traverse_categories($catId){
        if(!in_array($catId,$this->_tmp_cat_path))
            $this->_tmp_cat_path[] = $catId;
        $this->_get_categories();
        if(isset($this->_categories[$catId])){
            if($this->_categories[$catId]['parent'] == 0){
                $return = '/'.$this->category_identifier.'/'.implode('_',array_reverse($this->_tmp_cat_path)).'/'
                        .$this->_categories[$catId]['name'].'/';
                $this->_tmp_cat_path = array();
            }else{
                $return = $this->_traverse_categories($this->_categories[$catId]['parent']).$this->_categories[$catId]['name'].'/';
            }
        }else{
            $return = '';
        }

        return $return;
    }

    private function _get_manufacturers(){
        if(!isset($this->_manufacturers)){
            $this->_manufacturers = array();
            $query = $this->db->query("SELECT manufacturer_id, name FROM " . DB_PREFIX . "manufacturer");

            foreach($query->rows as $man)
                $this->_manufacturers[$man['manufacturer_id']] = $this->clean_name($man['name']);
        }
    }

    private function _get_infos(){
   
        if(!isset($this->_infos)){
            $this->_infos = array();
            $query = $this->db->query("SELECT i.information_id, id.title FROM " . DB_PREFIX . "information AS i LEFT JOIN " . DB_PREFIX . "information_description AS id ON id.information_id = i.information_id WHERE id.information_id = i.information_id AND id.language_id = ".(int)$this->config->get('config_language_id')." AND i.status = 1");

            foreach($query->rows as $infos)
                $this->_infos[$infos['information_id']] = $this->clean_name($infos['title']);

        }
    }

    private function clean_name($name){
        $name = htmlspecialchars_decode($name);
        $bad_array = array("сква",
                       "À","à","Á","á","Â","â","Ã","ã","Ä","ä","Å","å","Ā","ā","Ă","ă","Ą","ą","Ǟ","ǟ","Ǻ","ǻ","Α","α",
                       "Æ", "æ", "Ǽ", "ǽ",
                       "Ḃ","ḃ","Б","б",
                       "Ć","ć","Ç","ç","Č","č","Ĉ","ĉ","Ċ","ċ","Ч","ч","Χ","χ",
                       "Ḑ","ḑ","Ď","ď","Ḋ","ḋ","Đ","đ","Ð","ð","Д","д","Δ","δ",
                       "DZ",  "Dz","dz", "DŽ", "Dž", "dž",
                       "È","è","É","é","Ě","ě","Ê","ê","Ë","ë","Ē","ē","Ĕ","ĕ","Ę","ę","Ė","ė","Ʒ","ʒ","Ǯ","ǯ","Е","е","Э","э","Ε","ε",
                       "Ḟ","ḟ","ƒ","Ф","ф","Φ","φ",
                       "fi", "fl",
                       "Ǵ","ǵ","Ģ","ģ","Ǧ","ǧ","Ĝ","ĝ","Ğ","ğ","Ġ","ġ","Ǥ","ǥ","Г","г","Γ","γ",
                       "Ĥ","ĥ","Ħ","ħ","Ж","ж","Х","х",
                       "Ì","ì","Í","í","Î","î","Ĩ","ĩ","Ï","ï","Ī","ī","Ĭ","ĭ","Į","į","İ","ı","И","и","Η","η","Ι","ι",
                       "IJ", "ij",
                       "Ĵ","ĵ",
                       "Ḱ","ḱ","Ķ","ķ","Ǩ","ǩ","К","к","Κ","κ",
                       "Ĺ","ĺ","Ļ","ļ","Ľ","ľ","Ŀ","ŀ","Ł","ł","Л","л","Λ","λ",
                       "LJ", "Lj", "lj",
                       "Ṁ","ṁ","М","м","Μ","μ",
                       "Ń","ń","Ņ","ņ","Ň","ň","Ñ","ñ","ʼn","Ŋ","ŋ","Н","н","Ν","ν",
                       "NJ", "Nj", "nj",
                       "Ò","ò","Ó","ó","Ô","ô","Õ","õ","Ö","ö","Ō","ō","Ŏ","ŏ","Ø","ø","Ő","ő","Ǿ","ǿ","О","о","Ο","ο","Ω","ω",
                       "Œ", "œ",
                       "Ṗ","ṗ","П","п","Π","π",
                       "Ŕ","ŕ","Ŗ","ŗ","Ř","ř","Р","р","Ρ","ρ","Ψ","ψ",
                       "Ś","ś","Ş","ş","Š","š","Ŝ","ŝ","Ṡ","ṡ","ſ","ß","С","с","Ш","ш","Щ","щ","Σ","σ","ς",
                       "Ţ","ţ","Ť","ť","Ṫ","ṫ","Ŧ","ŧ","Þ","þ","Т","т","Ц","ц","Θ","θ","Τ","τ",
                       "Ù","ù","Ú","ú","Û","û","Ũ","ũ","Ü","ü","Ů","ů","Ū","ū","Ŭ","ŭ","Ų","ų","Ű","ű","У","у",
                       "В","в","Β","β",
                       "Ẁ","ẁ","Ẃ","ẃ","Ŵ","ŵ","Ẅ","ẅ",
                       "Ξ","ξ",
                       "Ỳ","ỳ","Ý","ý","Ŷ","ŷ","Ÿ","ÿ","Й","й","Ы","ы","Ю","ю","Я","я","Υ","υ",
                       "Ź","ź","Ž","ž","Ż","ż","З","з","Ζ","ζ",
                       "Ь","ь",'Ъ',"ъ","^","&");

    $good_array= array("scow",
                       "A","a","A","a","A","a","A","a","A","a","A","a","A","a","A","a","A","a","A","a","A","a","A","a",
                       "AE","ae","AE","ae",
                       "B","b","B","b",
                       "C","c","C","c","C","c","C","c","C","c","CH","ch","CH","ch",
                       "D","d","D","d","D","d","D","d","D","d","D","d","D","d",
                       "DZ","Dz","dz","DZ","Dz","dz",
                       "E","e","E","e","E","e","E","e","E","e","E","e","E","e","E","e","E","e","E","e","E","e","Ye","ye","E","e","E","e",
                       "F","f","f","F","f","F","f",
                       "fi","fl",
                       "G","g","G","g","G","g","G","g","G","g","G","g","G","g","G","g","G","g",
                       "H","h","H","h","ZH","zh","H","h",
                       "I","i","I","i","I","i","I","i","I","i","I","i","I","i","I","i","I","i","I","i","I","i","I","i",
                       "IJ","ij",
                       "J","j",
                       "K","k","K","k","K","k","K","k","K","k",
                       "L","l","L","l","L","l","L","l","L","l","L","l","L","l",
                       "LJ","Lj","lj",
                       "M","m","M","m","M","m",
                       "N","n","N","n","N","n","N","n","n","N","n","N","n","N","n",
                       "NJ","Nj","nj",
                       "O","o","O","o","O","o","O","o","O","o","O","o","O","o","O","o","O","o","O","o","O","o","O","o","O","o",
                       "OE","oe",
                       "P","p","P","p","P","p","PS","ps",
                       "R","r","R","r","R","r","R","r","R","r",
                       "S","s","S","s","S","s","S","s","S","s","s","ss","S","s","SH","sh","SHCH","shch","S","s","s",
                       "T","t","T","t","T","t","T","t","T","t","T","t","TS","ts","TH","th","T","t",
                       "U","u","U","u","U","u","U","u","U","u","U","u","U","u","U","u","U","u","U","u","U","u",
                       "V","v","V","v",
                       "W","w","W","w","W","w","W","w",
                       "X","x",
                       "Y","y","Y","y","Y","y","Y","y","Y","y","Y","y","YU","yu","YA","ya","Y","y",
                       "Z","z","Z","z","Z","z","Z","z","Z","z",
                       "'","'",'"','"',""," and ");
   
        $name = str_replace($bad_array,$good_array,$name);
        unset($bad_array);
        unset($good_array);
      
        $name = preg_replace("/[^a-zA-Z0-9]/",$this->_sep,$name);
      
        while(strpos($name, str_repeat($this->_sep,2))){
            $name = str_replace(str_repeat($this->_sep,2),$this->_sep,$name);
        }
        return trim($name,$this->_sep);
    }
   
   
   
    public function index_standard() {
        // Add rewrite to url class
        if ($this->config->get('config_seo_url')) {
            $this->url->addRewrite($this);
        }
      
        // Decode URL
        if (isset($this->request->get['_route_'])) {
            $parts = explode('/', $this->request->get['_route_']);
          
            foreach ($parts as $part) {
                $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($part) . "'");
              
                if ($query->num_rows) {
                    $url = explode('=', $query->row['query']);
                  
                    if ($url[0] == 'product_id') {
                        $this->request->get['product_id'] = $url[1];
                    }
                  
                    if ($url[0] == 'category_id') {
                        if (!isset($this->request->get['path'])) {
                            $this->request->get['path'] = $url[1];
                        } else {
                            $this->request->get['path'] .= '_' . $url[1];
                        }
                    }  
                  
                    if ($url[0] == 'manufacturer_id') {
                        $this->request->get['manufacturer_id'] = $url[1];
                    }
                  
                    if ($url[0] == 'information_id') {
                        $this->request->get['information_id'] = $url[1];
                    }  
                } else {
                    $this->request->get['route'] = implode('/',$parts);
                    return $this->forward($this->request->get['route']);
                    $this->request->get['route'] = 'error/not_found';  
                }
            }
          
            if (isset($this->request->get['product_id'])) {
                $this->request->get['route'] = 'product/product';
            } elseif (isset($this->request->get['path'])) {
                $this->request->get['route'] = 'product/category';
            } elseif (isset($this->request->get['manufacturer_id'])) {
                $this->request->get['route'] = 'product/manufacturer/product';
            } elseif (isset($this->request->get['information_id'])) {
                $this->request->get['route'] = 'information/information';
            }
          
            if (isset($this->request->get['route'])) {
                return $this->forward($this->request->get['route']);
            }
        }
    }
   
    public function rewrite_standard($link) {
        if ($this->config->get('config_seo_url')) {
            $url_data = parse_url(str_replace('&amp;', '&', $link));
            if(!isset($url_data['query']))return $link;
      
            $url = '';
          
            $data = array();
                      
            parse_str($url_data['query'], $data);
          
            foreach ($data as $key => $value) {
                if (isset($data['route'])) {
                    if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/product' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {
                        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");
                  
                        if ($query->num_rows) {
                            $url .= '/' . $query->row['keyword'];
                          
                            unset($data[$key]);
                        }                  
                    } elseif ($key == 'path') {
                        $categories = explode('_', $value);
                      
                        foreach ($categories as $category) {
                            $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'");
                  
                            if ($query->num_rows) {
                                $url .= '/' . $query->row['keyword'];
                            }                          
                        }
                      
                        unset($data[$key]);
                    }
                }
            }
      
            if ($url) {
                unset($data['route']);
          
                $query = '';
          
                if ($data) {
                    foreach ($data as $key => $value) {
                        $query .= '&' . $key . '=' . $value;
                    }
                  
                    if ($query) {
                        $query = '?' . trim($query, '&');
                    }
                }

                return $url_data['scheme'] . '://' . $url_data['host'] . (isset($url_data['port']) ? ':' . $url_data['port'] : '') . str_replace('/index.php', '', $url_data['path']) . $url . $query;
            } else {
                return $link;
            }
        } else {
            return $link;
        }      
    }  
}
?>
----------------------end class------------------------------------------------------
Then pass parameter  to the action at root index.php
$controller->addPreAction(new Action('common/automatic_seo_url'));

Last step->
Go to the admin section ->setting->server->SEO (check true)  ; then save


web.config for IIS url rewrite
---------------------------
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
   <rewrite>
     <rules>
       <rule name="Imported Rule 1" stopProcessing="true">
         <match url="^(.*)$" ignoreCase="false" />
         <conditions>
      <add input="{HTTP_HOST}" pattern="^phptechnicalgroups.blogspot\.com$" />
         </conditions>
         <action type="Redirect" redirectType="Permanent" url="http://phptechnicalgroups.blogspot.com/{R:1}" />
       </rule>
       <rule name="Imported Rule 2" stopProcessing="true">
         <match url="^(.*)$" ignoreCase="false" />
         <conditions>
      <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
      <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
      <add input="{URL}" pattern="^/favicon.ico$" ignoreCase="false" negate="true" />
         </conditions>
         <action type="Rewrite" url="index.php?_route_={R:1}" appendQueryString="true" />
       </rule>
     </rules>
   </rewrite>
  </system.webServer>
</configuration>
----------------------------------------------------
URL re write configuration for  apache .htaccess
-------------------------------
Options +FollowSymLinks

RewriteEngine On
RewriteBase /phptechnicalgroups.blogspot.com/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ index.php?_route_=$1 [L,QSA]
-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

How to URL rewrite dynamic using htaccess for PHP?[SOLVED]


How to create a .htaccess file ?

Step : Create text file and upload into server then rename to .htaccess .
Step : Paste the below code for URL rewrite for php application 
# paste below these code to htaccess and generate url you php link
---------------------------------------------------------------------------------------------
RewriteEngine On
RewriteBase /phpapplicationfoldername/

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)\?*$ index.php?_route_=$1 [L,QSA]

Wednesday, August 29, 2012

how to clean request string in php for prevent sql injection

function cleanit($text)
{
return htmlentities(strip_tags(stripslashes($text)), ENT_COMPAT, "UTF-8");
}

how to get country name through ip using php

<?php
function countrynameFromIP($ipAddr)
{
ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : "";
$ipDetail=array(); //initialize a blank array

$xml = file_get_contents("http://api.hostip.info/?ip=".$ipAddr);
preg_match("@(\s)*(.*?)@si",$xml,$match);
$ipDetail['city']=$match[2];
preg_match("@(.*?)@si",$xml,$matches);
$ipDetail['country']=$matches[1];
//get the country name inside the node and
preg_match("@(.*?)@si",$xml,$cc_match);
$ipDetail['country_code']=$cc_match[1]; //assing the country code to array
//return the array containing city, country and country code
return $ipDetail;
}
echo $IPDetail=countrynameFromIP($_SERVER['REMOTE_ADDR']);
?>
-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

simple curl using php example

1- create post.php curl value paste below code
---------------------------------------------------------
$Curl_Session = curl_init('http://127.0.0.1/test/getvalue.php');
 curl_setopt ($Curl_Session, CURLOPT_POST, 1);
 curl_setopt ($Curl_Session, CURLOPT_POSTFIELDS, "Name=hari");
 curl_setopt ($Curl_Session, CURLOPT_FOLLOWLOCATION, 1);
 $ss=curl_exec ($Curl_Session);
 curl_close ($Curl_Session);
---------------------------------------------------
2-create getvalue.php value paste below code
---------------------------------------------------
if(isset($_REQUEST['Name'])){
 echo $_REQUEST['Name'];
}

how to create file using php and write some thing

$filename="bikash.txt";
$fx=fopen($filename,a);
$string="heloo bikash";
fwrite($fx,$string);
fclose($fx);

how to export into csv and xml using php and mysql query

SELECT * INTO OUTFILE "D:/bikash.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM bikash_tble

http://127.0.0.1/test/test.php

<?php
$mysql=mysql_connect('localhost','root','');
mysql_select_db('test');
$select = "SELECT * FROM bikash_tbls";

$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ )
{
    $header .= mysql_field_name( $export , $i ) . "\t";
}

while( $row = mysql_fetch_row( $export ) )
{
    $line = '';
    foreach( $row as $value )
    {                                           
        if ( ( !isset( $value ) ) || ( $value == "" ) )
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . "\t";
        }
        $line .= $value;
    }
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );

if ( $data == "" )
{
    $data = "\n(0) Records Found!\n";                       
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=bikash_books.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>

Tuesday, August 28, 2012

how to find number of parameter of function in php

<?php
  function bikash_args()
 {
      echo "Number of arguments: " . func_num_args() . "<br />";
      for($i = 0 ; $i < func_num_args(); $i++) {
          echo "Argument $i = " . func_get_arg($i) . "<br />";

    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "
\n"; }
 }

  bikash_args("a1", "b2", "c3", "d4", "e5");
?>

you tube url parsing uisng php

/*
step-1 create class YoutubeParserbybikash.php and include your page this class file and create obeject  and pass your youtube url


 class YoutubeParserbybikash{
var $source = '';
var $unique = false;
var $suggested = false;
var $https = false;
var $privacy = false;
var $width = 354;
var $height = 234;
function __construct(){
}
function set($key,$val){
return $this->$key = $val;
}
function playyoutube(){
$return = Array();
$domain = 'http'.($this->https?'s':'').'://www.youtube'.($this->privacy?'-nocookie':'').'.com';
$size = 'width="'.$this->width.'" height="'.$this->height.'"';
preg_match_all('/(youtu.be\/|\/watch\?v=|\/embed\/)([a-z0-9\-_]+)/i',$this->source,$matches);
if(isset($matches[2])){
if($this->unique){
$matches[2] = array_values(array_unique($matches[2]));
}
foreach($matches[2] as $key=>$id) {
$return[$key]['id'] = $id;
$return[$key]['embedold'] = '';
}
}
return $return[$key]['embedold'];
}
}
------------------------------end class and create object to access-----------------------------------------
$youtube = new YoutubeParserbybikash;
$youtube->set('source','http://www.youtube.com/watch?v=R55e-uHQna0&feature=topvideos');
echo'
';
print_r($youtube->playyoutube());
echo'
';

how to assign ip and create user in mysql

setp 1-  > CREATE USER 'bikash'@'localhost' IDENTIFIED BY 'password';

step 2--> GRANT ALL PRIVILEGES ON demo . * TO bikash@localhost IDENTIFIED BY '123456'


GRANT ALL PRIVILEGES ON bikash_db. * TO 'bikash'@'%' IDENTIFIED BY 'tt@12345';
remote access-
GRANT ALL PRIVILEGES ON *.* TO 'bikash'@'%' IDENTIFIED BY 'tt@12345';
FLUSH PRIVILEGES;

htaccess dynamic url rewrite



root/.htaccess
profile.php?uname=bikash
it will show /bikash
------------------------------------
RewriteEngine On
RewriteBase /
RewriteRule ^confirmemail/(.*) confirmemail.php?code=$1
RewriteRule ^resetpassword/(.*) resetpassword.php?code=$1
RewriteRule ^resendconfirmation/(.*) resendconfirmation.php?userid=$1
RewriteRule ^widget$ widget.php
RewriteRule ^profile/(.*)/(.*) redirect.php?id=$1&username=$2
RewriteRule ^([^/.]+)(\/)?$ profile.php?uname=$1
# Turn off mod_security filtering.
SecFilterEngine Off
# The below probably isn't needed,
# but better safe than sorry.
SecFilterScanPOST Off
-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

how to swapping update query table row 0 to 1 and 1 to 0



mysql update query 1 to 0 and 0 to 1 single statement using query
update users set banned= case  when banned= "0"  then 1 when banned= "1"  then 0 end

Monday, August 27, 2012

Load Data while Scrolling Page Down with jQuery and PHP



click here complete source code download
<script type="text/javascript">
    var page = 1;
    function getFeedItems() {
        $('.loading').show();
        $.ajax({
            url : 'loadmore.php',
            data : 'page=' + page,
            type : 'GET',
            success: function(a) {
                if (a == '') {
                    $('#feed-list').append('<li>No more records found.</li>');
                    $(window).scroll(function() {});
                    $('.loading').hide();

                } else {
                    $('#feed-list').append(a);
                    $('.loading').hide();
                }
               
            }
        });
    }
    $(document).ready(function() {
        getFeedItems();
        $(window).scroll(function()
{
    if($(window).scrollTop() == $(document).height() - $(window).height())
    {
        page = page+1;
    getFeedItems();
    }
});

    });
</script>

<ul class="list" id="feed-list">
                        </ul>

create loadmore.php
and $_GET['page'];

paypal subscriber form with html




<form name="_xclick" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">      
                        <input type="hidden" name="cmd" value="_xclick-subscriptions">
                        <input type="hidden" name="business" value="me@mybusiness.com">
                        <input type="hidden" name="cmd" value="_xclick-subscriptions">
                        <input type="hidden" name="item_name" value="ESP 365 - Extreme. Dally" />
                        <input type="hidden" name="currency_code" value="USD">
                        <input type="hidden" name="no_shipping" value="1">
                   
                        <input type="hidden" name="a1" value="0">
                        <input type="hidden" name="p1" value="1">
                        <input type="hidden" name="t1" value="M">
                        <input type="hidden" name="a3" value="4.99">
                        <input type="hidden" name="p3" value="1">
                        <input type="hidden" name="t3" value="M">
                        <input type="hidden" name="src" value="1">
                        <input type="hidden" name="sra" value="1">
</form>
-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

Sunday, August 26, 2012

multiple retaltional query using 4 table mysql




UserID | Name
————————
1 | John
2 | Mike
3 | Tom
Teams:
TeamID | Name
——————————-
1 | FC Barcelona
2 | Real Madrid
3 | Manchester United
4 | Liverpool
Permissions:
PermissionsID | Name
——————————-
1 | Read Comments
2 | Write Comments
3 | Send Email
4 | Admin
UserTeams:
ID | UserID | TeamID | PermissionID
——————————————–
1 | 1 | 1 | 1
2 | 3 | 1 | 2
3 | 2 | 1 | 4
4 | 4 | 2 | 1
4 | 1 | 4 | 3
SELECT
p.Name AS Permission,
u.pseudo AS User_name,
t.Name AS Team,
u.id AS User_id
FROM
userteams AS ut
INNER JOIN
users AS u ON (ut.UserId = u.id)
INNER JOIN
teams AS t ON (ut.TeamId = t.TeamId)
INNER JOIN
permissions AS p ON (ut.PermissionId = p.permissionsId)
WHERE
u.id= ut.userId
-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------