Friday, June 21, 2013

Cookies and Session in PHP

Cookies and Session are use in terms of data storage in programming language.

But how ?
What is the preferable?,
When use session?, 
When use cookie?, 

there are some question which arise in the mind at the time of of store data temp. as well as permanent.

There are differences between the two that will make each favorable in their own circumstance.

Cookies can be set to a long lifespan, which means that data stored in a cookie can be stored for months if not years. Cookies, having their data stored on the client machine, work smoothly when you have a cluster of web servers, whereas sessions are stored on the server, meaning if one of your web servers handles the first request, the other web servers in your cluster will not have the stored information.

Sessions are stored on the server, which means clients do not have access to the information you store about them – this is particularly important if you store shopping baskets or other information you do not want your visitors to be able to edit by hand by hacking their cookies. Session data, being stored on your server, does not need to be transmitted with each page; clients just need to send an ID and the data is loaded from the local file. Finally, sessions can be any size you want because they are held on your server, whereas many web browsers have a limit on how big cookies can be to stop rogue web sites chewing up gigabytes of data with meaningless cookie information.

So, as you can see, each have their own advantages, but at the end of the day it usually comes down to one choice: 

Do you want your data to work when you visitor comes back the next day?

If so, then your only choice is cookies – if you have any particularly sensitive information, your best bet is to store it in a database, then use the cookie to store an ID number to reference the data. If you do not need semi-permanent data, then sessions are generally preferred, as they are a little easier to use, do not require their data to be sent in entirety with each page, and are also cleaned up as soon as your visitor closes their web browser.

Wednesday, May 22, 2013

Google translator code php

Use Google translator code  in your  php script, Code send a HTTP request to the Google Translate website to translate a given string between an origin language and target language. Code show the translation results




googletranslate.php

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

class translate { 


    var $translate_from; 
    var $translate_into; 
    var $debug; 




    function __construct($from , $to){ 

        $this->debug = 0; 


        ini_set("display_errors",$this->debug); 


        if(!$from){ 

            $this->translate_from = "en"; 

        }else{ 

            $this->translate_from = $from; 

        } 
         
        if(!$to){ 

            $this->translate_into = "it"; 


        }else{ 
             
            $this->translate_into = $to; 

        } 

    } 


    function TranslateUrl($word){ 


        if(!$word){ 

            die("you need to adda a translate word"); 
        } 


        $word = urlencode($word); 

        $url = "http://translate.google.com/?sl=". $this->translate_from ."&tl=". $this->translate_into ."&js=n&prev=_t&hl=it&ie=UTF-8&eotf=1&text=". $word .""; 


        return $url; 

    } 

    function get($word){ 


        $dom  = new DOMDocument(); 
         
        $html =  $this->curl_download($this->TranslateUrl($word)); 

        $dom->loadHTML($html); 

        $xpath = new DOMXPath($dom); 
         
        $tags = $xpath->query('//*[@id="result_box"]'); 

        foreach ($tags as $tag) { 
             
            $var = trim($tag->nodeValue); 

            if(!$var){ 
                $this->sendEmail(); 
            }else{ 

                return ($var); 

            } 
             
                   
        } 

    } 

   

    function curl_download($Url){ 
      
        
        if (!function_exists('curl_init')){ 
            
            if (function_exists('file_get_contents')){ 

                return file_get_contents($Url); 

            }else{ 

                die("Your server dosen't support curl or file get contents"); 

            } 

        } 
      
        
        $ch = curl_init(); 

        curl_setopt($ch, CURLOPT_URL, $Url); 
      
        
        curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0"); 
      
        curl_setopt($ch, CURLOPT_HEADER, 0); 
      
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
      
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
      
        $output = curl_exec($ch); 
      
        curl_close($ch); 
      
        return $output; 
    } 


} 



?>
usage of script
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

require_once("googletranslate.php"); 


 $translate_from = "en"; #language from what we translate 
 $translate_into = "it"; #language in what we want to translate 

$var = new translate($translate_from,$translate_into); 
echo $var->get("hello"); // replace your text with "hello"



?>

Supported languages

Afrikaans (AF)
Albanian (SQ)
English (EN)
Arabic (AR)
Azerbaijani (AZ)
Bengali (BN)
Belarusian (BE)
Bulgarian (BG)
Croatian (HR)
Czech (CS)
Danish (DA)
Esperanto (EO)
Estonian (ET)
Filipino (TL)
Finnish (FI)
French (FR)
Galician (GL)
Greek (EL)
Georgian (KA)
Gujarati (GU)
Hebrew (IW)
Hindi (HI)
Spanish (ES)
Dutch (NL)
Indonesian (ID)
Irish (GA)
Iceland (IS)
Japanese (JA)
Yiddish (YI)
Kannada (KN)
Catalan (CA)
Khmer (KM)
Korean (KO)
Haitan (HT)
Lao (LO)
Lithuanian (LT)
Latin (LA)
Latvian (LV)
Macedonian (MK)
Malay (MS)
Maltese (MT)
German (DE)
Norwegian (NO)
Armenian (HY)
Persian (FA)
Polish (PL)
Portuguese (PT)
Russian (RU)
Romanian (RO)
Serbian (SR)
Slovak (SK)
Slovenian (SL)
Swahili (SW)
Swedish (SV)
Thai (TH)
Tamil (TA)
Telugu (TE)
Turkish (TR)
Ukrainian (UK)
Urdu (UR)
Welsh (CY)
Hungarian (HU)
Vietnamese (VI)
Italian (IT)

Saturday, May 18, 2013

Compute difference between two dates in php

This php script explain you , how you can calculates the difference of time between them in years, months, days.


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

$date_1 = "2007-03-24";
$date_2 = "2013-06-01";

$diff = abs(strtotime($date_2) - strtotime($date_1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days);


?>

Wednesday, May 15, 2013

get the geographic location of a IP address

This post explains you, how to get the geographic location of a IP address from http://freegeoip.net API

geoIPLocation.php

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

class geoIPLocation{ 
    public $Ip = '0.0.0.0'; 
    public $CountryCode = ''; 
    public $CountryName = ''; 
    public $RegionCode = ''; 
    public $RegionName = ''; 
    public $City = ''; 
    public $ZipCode = ''; 
    public $Latitude = ''; 
    public $Longitude = ''; 
    public $MetroCode = ''; 
    public $AreaCode = ''; 
     
    public function getgeoIPLocation($ip = 0){ 
        if($ip){ 
            $url = 'http://freegeoip.net/xml/'.$ip; 
        } else { 
            $url = 'http://freegeoip.net/xml/'; 
        } 
        $postdata = http_build_query( 
            // just incase we later need to post parameters 
        );         

        $opts = array('http' => 
            array( 
                'method' => 'POST', 
                'header' => 'Content-type: application/x-www-form-urlencoded', 
                'content' => $postdata 
            )         
        ); 

        try{ 
            $context = stream_context_create($opts); 
            $result = file_get_contents($url, false, $context); 
            if(!$result){ 
                throw new Exception('Could not get a response from freegeoip.net'); 
                return false; 
            } else { 
                self::pickDataFromXML($result); 
            } 
        } 
        catch (Exception $e){ 
            echo 'Caught exception: '. $e->getMessage(); 
        }     
        return true; 
    }     
     
    public function pickDataFromXML($file){ 
        $HisVurderingNum = 0;     
        $SalgsPriserNum = 0; 
        $XMLFile = ''; 
        $success = 0; 
        try{         
            $XMLFile = simplexml_load_string($file); 
            if(!$XMLFile){ 
                throw new Exception('Could not load XML file!'); 
            } else { 
                $this->Ip = $XMLFile->Ip; 
                $this->CountryCode = $XMLFile->CountryCode; 
                $this->CountryName = $XMLFile->CountryName; 
                $this->RegionCode = $XMLFile->RegionCode; 
                $this->RegionName = $XMLFile->RegionName; 
                $this->City = $XMLFile->City; 
                $this->ZipCode = $XMLFile->ZipCode; 
                $this->Latitude = $XMLFile->Latitude; 
                $this->Longitude = $XMLFile->Longitude; 
                $this->MetroCode = $XMLFile->MetroCode; 
                $this->AreaCode = $XMLFile->AreaCode; 

                $success = 1; 
                unlink($XMLFile); 
            } 
        } 
        catch (Exception $e){ 
            echo 'Caught exception: '. $e->getMessage(); 
        } 
        return $success; 
    }     
}  


?>





usage of script

example 1 : Using your local IP 


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

include("geoIPLocation.php");
$geoIPLocation = new geoIPLocation(); 
$geoIPLocation->getgeoIPLocation($_SERVER['REMOTE_ADDR']); 
echo $geoIPLocation->Ip.'
'; 
echo $geoIPLocation->CountryCode.'
'; 
echo $geoIPLocation->CountryName.'
'; 
echo $geoIPLocation->RegionCode.'
'; 
echo $geoIPLocation->RegionName.'
'; 
echo $geoIPLocation->City.'
'; 
echo $geoIPLocation->ZipCode.'
'; 
echo $geoIPLocation->Latitude.'
'; 
echo $geoIPLocation->Longitude.'
'; 
echo $geoIPLocation->MetroCode.'
'; 
echo $geoIPLocation->AreaCode.'
'; 

?>





example 2 : Find the proper IP

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

include("geoIPLocation.php");
$geoIPLocation->getgeoIPLocation(); 
echo $geoIPLocation->Ip.'
'; 
echo $geoIPLocation->CountryCode.'
'; 
echo $geoIPLocation->CountryName.'
'; 
echo $geoIPLocation->RegionCode.'
'; 
echo $geoIPLocation->RegionName.'
'; 
echo $geoIPLocation->City.'
'; 
echo $geoIPLocation->ZipCode.'
'; 
echo $geoIPLocation->Latitude.'
'; 
echo $geoIPLocation->Longitude.'
'; 
echo $geoIPLocation->MetroCode.'
'; 
echo $geoIPLocation->AreaCode.'
'; 


?>


Monday, May 13, 2013

SEO Friendly URL function in PHP

This post explains you, how to Convert simple url to SEO friendly URL using a simple PHP function. Pass your url to SEOURL funtion which is convert your url as a seo friendly url
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


function SEOURL($_string)
{

  return strtolower(str_replace(array('  ', ' '), '-', preg_replace('/[^a-zA-Z0-9 s]/', '', trim($_string))));

}


// usage

SEOURL($simple_url);


?>

Wednesday, May 1, 2013

Redirect page after certain time PHP

This is the simple php function to redirect page after certain time.

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

/*
* Redirects to specified $page 
*/ 
function REDIRECT($page, $seconds=4)
{ 

        // redirect specific $page within $seconds seconds
        header("Refresh: " . $seconds . "; URL=" . $page);
        exit(); 

}


?>

Secure login with MySQLi Extension php

In this post,  we create new code secure login script with MySQLi Extension (MySQL Improved) in php. may be useful for you

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


function LOGIN($username, $password)
{
               // Connect to database
            
                 $db = new mysqli('localhost', 'user', 'pass', 'demo');


               // Hash password with md5
                
                    $password = md5($password);
               
               // Construct SQL statement for query & execute 
                    
                    $tablename = "admin";
                    
                    $_Query = "SELECT username, password FROM ".$tablename." WHERE username = ? AND password = ? LIMIT 1";
                    
                    $stmt = $db->prepare($_Query) or die("Fatal Error !!");

                    $stmt->bind_param("ss", $username, $password);

                    $stmt->execute();
                    
                    $stmt->store_result();

               // bind variables to prepared statement 
    
                    $stmt->bind_result($col1, $col2); 
                    
                    $stmt->num_rows; 

               // fetch values 

                    $stmt->fetch();

               // If one row is returned, username and password are valid 
              
                    if (is_object($stmt) && $stmt->num_rows == 1)
                    { 
                            // Set session variable for login status to true 
                    
                            $_SESSION['logged_in_@d#i^'] = true; 
                            
                            $stmt->close(); // close statement

                            $db->close(); // close connection

                            header("secure-page.php?msg=welcome");

                    
                    } else { 

                            // If number of rows returned is not one, redirect back to login screen 
                            
                            $stmt->close(); // close statement

                            $db->close(); // close connection
                      
                            header("login.php");
                    
                    } 

               
}

?>

 

© 2014 4everTutorials. All rights resevered.

Back To Top