Subscribe For Free Updates!

We'll not spam mate! We promise.

Showing posts with label Programmings. Show all posts
Showing posts with label Programmings. Show all posts

May 10, 2013

php to remove last two characters from string



php remove last two characters from string

 The following code is used to remove character from the last of the string. here "substr()" function is used.
this function is used to get substring from original string.

<?php
echo substr('abcdef', 1);     // bcdef
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// Accessing single characters in a string
// can also be achieved using "square brackets"
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f

?>

May 9, 2013

Check String Contain Specific words - PHP



Check String Contain Specific words - PHP

The following code is used to find the specific words or char from a string by using php.
here "strpos()" is used. This function is used to get string position from the original string. here i just get true or false result if the original string contains the specific word or character,

if (strpos($a,'are') !== false) 
{
    echo 'true';
}
else
{
    echo 'false';
}

May 7, 2013

Get URL from address bar - PHP


Get URL from address bar - PHP

 The following code is used to get full url address by using php.

<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;
?>

Notes:
 Here we are using 2 functions in php to get full url from address bar.
1. $_SERVER['HTTP_HOST']
2. $_SERVER['REQUEST_URI']
$_SERVER['HTTP_HOST'] - This function will show only server name.
$_SERVER['REQUEST_URI'] - This function will show you the path to file of your url.

 When you run $_SERVER['HTTP_HOST'];  for this website you'll get result "www.techniqzone.blogspot.in" only, no "http://" no "/Get URL from address bar - PHP"

<?php 
$server=$_SERVER['HTTP_HOST'];
echo $server;
?>

Output is "www.techniqzone.blogspot.in".

This script "$_SERVER['REQUEST_URI']" display the result like below.
no "http://" and no "www.techniqzone.blogspot.in

Example:

<?php
$request_url=$_SERVER['REQUEST_URI'];
echo $request_url;
?>

Output of $_SERVER['REQUEST_URI'] is "/Get URL from address bar - PHP"

If you want to get full URL from this site you, we have to use (.) to connect 2 functions together and create http:// by yourself.

<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;
?>

May 1, 2013

Find Browser and Platform Details Using JavaScript


Find Browser and Platform Details Using JavaScript:

The following code is used to find the Browser and Platform details. This script displays browser code name, browser name, browser version, cookies enabled disabled details, platform details and user agent header details.


<script>
"Browser CodeName: " + navigator.appCodeName + "";
"Browser Name: " + navigator.appName + "";
"Browser Version: " + navigator.appVersion + "";
"Cookies Enabled: " + navigator.cookieEnabled + "";
"Platform: " + navigator.platform + "";
"User-agent header: " + navigator.userAgent + "";
</script>


Apr 7, 2013

PHP - To get IP address


The following code is used to get ip address by using PHP

get_ip_address()
(Custom function by John)

get_ip_address -- Retrieves Ip adres from user and checks for proxy server.

Description
(string) get_ip_address()

This simple function checkes whether the uses is behind a (transparent) proxy, and returns the found IP adres.

Function

function get_ip_address()
    {
        if (isset($_SERVER)) {
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && ip2long($_SERVER["HTTP_X_FORWARDED_FOR"]) !== false) {
                $ipadres = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } elseif (isset($_SERVER["HTTP_CLIENT_IP"])  && ip2long($_SERVER["HTTP_CLIENT_IP"]) !== false) {
                $ipadres = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $ipadres = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR') && ip2long(getenv('HTTP_X_FORWARDED_FOR')) !== false) {
                $ipadres = getenv('HTTP_X_FORWARDED_FOR');
            } elseif (getenv('HTTP_CLIENT_IP') && ip2long(getenv('HTTP_CLIENT_IP')) !== false) {
                $ipadres = getenv('HTTP_CLIENT_IP');
            } else {
                $ipadres = getenv('REMOTE_ADDR');
            }
        }
        return $ipadres;
    }
?>


PHP simple Memcache implementation


Description:
You can use this class to simply cache your data with Memcache in PHP.
Requirements
- PHP 5.3 or higher (you can change "__construct" to "cache" to make it work in older versions)
- Memcache extention installed (how to install the Memcached extention?)
- Memcached installed on a server (how to install Memcached?)

cache.php
Save the code below to a file named cache.php, and include this file in your php code (include "cache.php";)


     # Copyright 2012 John Post - StarfixIT
     # NOTE: Requires PHP version 5.3 or later with Memcache module
    class cache
        {
        
            private $host = '127.0.0.1';
            private $port = '11211';
            private $memcache;
            private $lifetime;
            private $name;

            function __construct($name = false, $lifetime = 600)
            {
              //Check if Memcache is installed
                if(!class_exists("Memcache")){
                    exit("You need to install memcache");
                } 
                //Check if allready connected to memcached
                if (isset($_GLOBALS["memcache"])) {
                    //Yes, use old connection
                    $this->memcache = $_GLOBALS["memcache"];
                } else {
                    //No, make new connection
                    $this->memcache = new Memcache;
                    $this->memcache->connect($this->host, $this->port);
                    $_GLOBALS["memcache"] = $this->memcache;
                }
                //Set global livetime
                $this->lifetime = $lifetime;
                
                //Set global name
                if ($name !== false) {
                    $this->name = $this->makeNameOk($name);
                }
            }
            
            //Public function to set the name
            public function setName($name)
            {
                $this->name = $this->makeNameOk($name);
            }
            
            //Public function to set the cache, livetime optional
            public function setCache($data, $lifetime = false)
            {
                $lifetime = $lifetime === false ? $this->lifetime : $this->lifetime;
                $this->memcache->set($this->name, $data, MEMCACHE_COMPRESSED, $lifetime);
            }
            
            //Public function to get the cache, optional name
            public function getCache($name = false)
            {
                $name = $name === false ? $this->name : $name;
                $result = $this->memcache->get($name);
                if ($result !== false) {
                    return $result;
                }
                return false;
            }
            
            //Public function to remove the data from Memcached
            public function remove( $name = false )
            {
                $name = $name === false ? $this->name : $name;
                $this->memcache->delete( $name );
            }
            
            //Function to create a clean alias
            private function makeNameOk($name)
            {
                return preg_replace('/[^A-Za-z0-9_]/', "", $name);
            }

        }

Example


//Include Cache class
include "cache.php";

//Open the class with name "myData" and 900 secs lifetime
$cache = new cache("myData", 900);

//Get the data from cache
$data = $cache->getCache();

if( $data === false ){
    //if the cache is expired, run the expensive function
    $data = very_expensive_function();
    
    //Save the data to cache
    $cache->setCache( $data );
    echo "Cache set:
";

}else{
    echo "Got data from cache:
";

}

//Output the data
echo $data;

//This is just a silly example of an expensive function (takes about 2 seconds)
function very_expensive_function(){
    $count = 19500000;
    $time_start = microtime(true);
    for($i = 0; $i < $count; ++$i);
        $i = 0; while($i < $count) ++$i;
    return number_format(microtime(true) - $time_start, 3);
}


Mar 9, 2013

PHP - Check if browser cookies are enabled


PHP - Check if browser cookies are enabled.


At first php reads the cookie data to see if there is already any data saved in them. If not, upon attempting to store some test data, the script refreshes the page. If no result has been returned; it is an obivous indication that cookies are disabled.


if (isset($_COOKIE['stuff'])) {
 echo "cookies enabled";
}
else {
 if(isset($_REQUEST['test_cookies'])) {
 echo "cookies disabled";
 }
 else {
 setcookie("stuff", "1", 0, "/");
 header("Location: $_SERVER['PHP_SELF']?test_cookies=1");
 }
}

PHP - Setting session timeout

Session timeout setting is necessary For high-security sites . Php default session timeout time is 20 minutes.

There is 2 functions for change the session timeout.


1. Sets the timeout of a current session and

2. Verifies whether the session is still valid given the specified timeout variable set in above function .


function check_login() {
@session_start();
$expiration_time = intval($_SESSION['session_expiration']);
//if session is still valid
if ($time() < $expiration_time) {
validate_session('600'); // -> make it valid for another 600 secs
return true;
}
 else {
unset($_SESSION['session_expiration']);
return false;

}
}

function validate_session($timeout) {
@session_start();
$_SESSION['session_expiration'] = time() + $timeout;
}




Mar 3, 2013

Set Time limit for a php script.


Set Time limit for a php script.
If you want to extend the execution time of the script you can use set_time_limit on the page.
The default time limit is 30 seconds


<?php
// script dies after 180 secs
set_time_limit(180);
?>

/**********************************************/
Get random values from database.


SELECT * FROM test_table ORDER BY RAND() limit 20;



This query will return values 20 rows randomly. To make more effecient the random values can be given in the server side scripting language.
/*********************************************************/