Thursday, July 31, 2014

redirect with HTTP status code in php

PHP redirect script with all http status code. For further details please look at following code:

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

function movePage($num,$url){
   static $http = array (
       100 => "HTTP/1.1 100 Continue",
       101 => "HTTP/1.1 101 Switching Protocols",
       200 => "HTTP/1.1 200 OK",
       201 => "HTTP/1.1 201 Created",
       202 => "HTTP/1.1 202 Accepted",
       203 => "HTTP/1.1 203 Non-Authoritative Information",
       204 => "HTTP/1.1 204 No Content",
       205 => "HTTP/1.1 205 Reset Content",
       206 => "HTTP/1.1 206 Partial Content",
       300 => "HTTP/1.1 300 Multiple Choices",
       301 => "HTTP/1.1 301 Moved Permanently",
       302 => "HTTP/1.1 302 Found",
       303 => "HTTP/1.1 303 See Other",
       304 => "HTTP/1.1 304 Not Modified",
       305 => "HTTP/1.1 305 Use Proxy",
       307 => "HTTP/1.1 307 Temporary Redirect",
       400 => "HTTP/1.1 400 Bad Request",
       401 => "HTTP/1.1 401 Unauthorized",
       402 => "HTTP/1.1 402 Payment Required",
       403 => "HTTP/1.1 403 Forbidden",
       404 => "HTTP/1.1 404 Not Found",
       405 => "HTTP/1.1 405 Method Not Allowed",
       406 => "HTTP/1.1 406 Not Acceptable",
       407 => "HTTP/1.1 407 Proxy Authentication Required",
       408 => "HTTP/1.1 408 Request Time-out",
       409 => "HTTP/1.1 409 Conflict",
       410 => "HTTP/1.1 410 Gone",
       411 => "HTTP/1.1 411 Length Required",
       412 => "HTTP/1.1 412 Precondition Failed",
       413 => "HTTP/1.1 413 Request Entity Too Large",
       414 => "HTTP/1.1 414 Request-URI Too Large",
       415 => "HTTP/1.1 415 Unsupported Media Type",
       416 => "HTTP/1.1 416 Requested range not satisfiable",
       417 => "HTTP/1.1 417 Expectation Failed",
       500 => "HTTP/1.1 500 Internal Server Error",
       501 => "HTTP/1.1 501 Not Implemented",
       502 => "HTTP/1.1 502 Bad Gateway",
       503 => "HTTP/1.1 503 Service Unavailable",
       504 => "HTTP/1.1 504 Gateway Time-out"
   );
   header($http[$num]);
   header ("Location: $url");
   exit(0);
}



 
/* Move page with 301 http status code*/
movePage(301,"http://4evertutorials.blogspot.com/");



?>

Tuesday, July 22, 2014

grab image color php

This PHP class can extract the colors of a given image file. It can read an image in the GIF, JPEG or PNG format and extracts the list of colors that are used in the pixels of the image. The class takes in account a similarity factor to consider very similar colors as if they are the same. It returns an array with the colors used in the picture sorted by the frequency of the pixels that use each color.


Save following php code as a "colorextractor.class.php" without double quotes.

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

class ColorExtractor {
    private function RGBtoHEX($rgb) {
        $rgb = $rgb . ",";
        preg_match("/(.*?)\,(.*?)\,(.*?)\,/", $rgb, $colors);
        $r   = $colors[1];
        $g   = $colors[2];
        $b   = $colors[3];
        $hex = "#";
        $hex .= str_pad(dechex($r), 2, "0", STR_PAD_LEFT);
        $hex .= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);
        $hex .= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);
        return $hex;
    }
    public function getColors($img, $num, $precision, $type) {
        $allArray  = array();
        $retArray  = array();
        $maxWidth  = 200;
        $maxHeight = 200;
        $cw        = 240;
        $num       = preg_replace('/[^0-9]/', '', $num);
        $precision = preg_replace('/[^0-9]/', '', $precision);
        if ($num == "") {
            $num = 5;
        }
        if ($precision == "") {
            $precision = 5;
        }
        if ($type != "rgb" && $type != "hex"){
            $type = "rgb";
        }
        $det = GetImageSize($img);
        if (!$det) {
            return "Enter a valid Image";
        }
        $imgWidth  = $det[0];
        $imgHeight = $det[1];
        if ($imgWidth > $maxWidth || $imgHeight > $maxHeight) {
            if ($imgWidth > $imgHeight) {
                $newWidth  = $maxWidth;
                $diff      = round($imgWidth / $maxWidth);
                $newHeight = round($imgHeight / $diff);
            } else {
                $newHeight = $maxHeight;
                $diff      = round($imgHeight / $maxHeight);
                $newWidth  = round($imgWidth / $diff);
            }
        }
        if ($det[2] == 1) {
            $origImage = imagecreatefromgif($img);
        } else if ($det[2] == 2) {
            $origImage = imagecreatefromjpeg($img);
        } else if ($det[2] == 3) {
            $origImage = imagecreatefrompng($img);
        }
        $newImage = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($newImage, $origImage, 0, 0, 0, 0, $newWidth, $newHeight, $imgWidth, $imgHeight);
        for ($x = 0; $x < $newWidth; $x++) {
            for ($y = 0; $y < $newHeight; $y++) {
                $colors = imagecolorsforindex($newImage, imagecolorat($newImage, $x, $y));
                $r      = $colors['red'];
                $g      = $colors['green'];
                $b      = $colors['blue'];
                $a      = $colors['alpha'];
                if (!($r > $cw && $g > $cw && $b > $cw)) {
                    if (!($r == 0 && $g == 0 && $b == 0)) {
                        $rgb = $r . "," . $g . "," . $b;
                        array_push($allArray, $rgb);
                    }
                }
            }
        }
        $count = array_count_values($allArray);
        arsort($count);
        $keys = array_keys($count);
        for ($s = 0; $s < $num; $s++) {
            $first = $keys[$s] . ",";
            preg_match("/(.*?)\,(.*?)\,(.*?)\,/", $first, $colors2);
            $r  = $colors2[1];
            $g  = $colors2[2];
            $b  = $colors2[3];
            $iS = $s + 1;
            for ($i = $iS; $i < count($keys); $i++) {
                $next = $keys[$i] . ",";
                preg_match("/(.*?)\,(.*?)\,(.*?)\,/", $next, $colors2);
                $r2 = $colors2[1];
                $g2 = $colors2[2];
                $b2 = $colors2[3];
                if (abs($r2 - $r) < $precision || abs($g2 - $g) < $precision || abs($g2 - $g) < $precision) {
                    unset($keys[$i]);
                }
            }
            $keys = array_values($keys);
        }
        if ($type == "hex") {
            for ($j = 0; $j < $num; $j++) {
                $color = $this->RGBtoHEX($keys[$j]);
                array_push($retArray, $color);
            }
        } else if ($type == "rgb"){
            for ($j = 0; $j < $num; $j++) {
                array_push($retArray, $keys[$j]);
            }
        }
        return $retArray;
    }
}

?>
Usage of class: <?php //Require the ColorExtractor Class require("colorextractor.class.php"); $img = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRveQ2t7dRmKi1aq54eHUEto2OfDyxmfIZn--lVvye_Hxc2eJ59"; $ce = new ColorExtractor; /* Call the function getColors, this function gets the main colors from the image getColors(Link to Image, Number of colors to return, minumum difference between each color, Type of return "rgb" or "hex"); */ $colorArray = $ce->getColors($img, 5, 11, "rgb"); ?> <img src="<?php echo $img; ?>"> <br /><br /> <table width="200px" border="1"> <?php foreach ($colorArray as $color) {     echo '<tr>';     if (substr($color, 0, 1) == "#") {         echo '<td width="50%" align="center">' . $color . '</td><td width="50%" align="center"><div style="background-color:' . $color . '; width:50px; height:50px;"></div></td>';     } else {         echo '<td width="50%" align="center">' . $color . '</td><td width="50%" align="center"><div style="background-color:rgb(' . $color . '); width:50px; height:50px;"></div></td>';     }     echo '</tr>'; } ?>
</table>

Friday, July 4, 2014

resize image using php

PHP script can easily allow you to resize image using php class. If you’re looking to resize uploaded images or would want to generate thumbnails from uploaded images, then just try this php class once. It also works on transparent PNG and GIF images.

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

class ResizeImage {
 
   var $image;
   var $image_type;
 
   function load($filename) {
 
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {
 
         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
 
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
 
         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image,$filename);
      }
      if( $permissions != null) {
 
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image);
      }
   }
   function getWidth() {
 
      return imagesx($this->image);
   }
   function getHeight() {
 
      return imagesy($this->image);
   }
   function resizeToHeight($height) {
 
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
 
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
 
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }
 
   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }

   function resizeTransparentImage($width,$height) {
    $new_image = imagecreatetruecolor($width, $height);
    if( $this->image_type == IMAGETYPE_GIF || $this->image_type == IMAGETYPE_PNG ) {
        $current_transparent = imagecolortransparent($this->image);
        if($current_transparent != -1) {
            $transparent_color = imagecolorsforindex($this->image, $current_transparent);
            $current_transparent = imagecolorallocate($new_image, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
            imagefill($new_image, 0, 0, $current_transparent);
            imagecolortransparent($new_image, $current_transparent);
        } elseif( $this->image_type == IMAGETYPE_PNG) {
            imagealphablending($new_image, false);
            $color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
            imagefill($new_image, 0, 0, $color);
            imagesavealpha($new_image, true);
        }
    }
    imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
    $this->image = $new_image; 
  }
 
}

?>

Usage 1 :

The first example below will load a file named picture.jpg resize it to 250 pixels wide and 400 pixels high and resave it as picture2.jpg
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

   $file_location = '/var/www/yourwebsite/uploads/'; # Image folder Path
  $image = new ResizeImage();
   $image->load($file_location.$file_location.'picture.jpg');
   $image->resize(250,400);
   $image->save('picture2.jpg');
?>

Usage 2 :

If you want to resize to a specifed width but keep the dimensions ratio the same then the script can work out the required height for you, just use the resizeToWidth function.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
   $file_location = '/var/www/yourwebsite/uploads/'; # Image folder Path
  $image = new ResizeImage();
   $image->load($file_location.'picture.jpg');
   $image->resizeToWidth(250);
   $image->save('picture2.jpg');
?>

Usage 3 :

You may wish to scale an image to a specified percentage like the following which will resize the image to 50% of its original width and height
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
   $file_location = '/var/www/yourwebsite/uploads/'; # Image folder Path
  $image = new ResizeImage();
   $image->load($file_location.'picture.jpg');
   $image->scale(50);
   $image->save('picture2.jpg');
?>

Usage 4 :

You can of course do more than one thing at once. The following example will create two new images with heights of 200 pixels and 500 pixels
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
   $file_location = '/var/www/yourwebsite/uploads/'; # Image folder Path
  $image = new ResizeImage();
   $image->load($file_location.'picture.jpg');
   $image->resizeToHeight(500);
   $image->save('picture2.jpg');
   $image->resizeToHeight(200);
   $image->save('picture3.jpg');
?>

Usage 5 :

The output function lets you output the image straight to the browser without having to save the file. Its useful for on the fly thumbnail generation
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
   header('Content-Type: image/jpeg');
   $file_location = '/var/www/yourwebsite/uploads/'; # Image folder Path
  $image = new ResizeImage();
   $image->load($file_location.'picture.jpg');
   $image->resizeToWidth(150);
   $image->output();
?>

Usage 6 :

Resize Transparent gif OR png images
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
   $file_location = '/var/www/yourwebsite/uploads/'; # Image folder Path
  $image = new ResizeImage();
   $image->load($file_location.'picture.jpg');
   $image->resizeTransparentImage(250,400);
   $image->save('picture2.jpg');
?>

Usage 7 :

The following example will resize and save an image which has been uploaded via a form

<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
   if( isset($_POST['submit']) ) {
      $image = new ResizeImage();
      $image->load($_FILES['uploaded_image']['tmp_name']);
      $image->resizeToWidth(150);
      $image->output();
   } else {
 

 
   echo '
'; } ?>

If you have any queries or feedback for this script then please Leave A Response below. Thank You.

Thursday, June 26, 2014

google map latitude longitude php


In this post PHP script convert an address to geocode Latitude/Longitude positioning with Google Maps. In response, you will be get the latitude and longitude details.

For same, you can use following php code.


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


$url = "http://maps.google.com/maps/api/geocode/json?address=West+Bridgford&sensor=false®ion=UK";
$result = file_get_contents($url);
$response = json_decode($result, true);

 
$latitude = $response['results'][0]['geometry']['location']['lat'];
$longitude = $response['results'][0]['geometry']['location']['lng'];
 
echo "Latitude: " . $latitude . " Longitude: " . $longitude;



?>

Thursday, May 29, 2014

generate QR code by google api php

In this post we explain you, how you can generate QR code with metadata by google api. You can generat qr code for any link, email, telephone number or text data.

For generate code, you can use following php script:


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


function google_qr_code($data, $type = "TXT", $size ='150', $ec='L', $margin='0')  {     
    $types = array("URL" => "http://", "TEL" => "TEL:", "TXT"=>"", "EMAIL" => "MAILTO:");
    if(!in_array($type,array("URL", "TEL", "TXT", "EMAIL")))
    {
        $type = "TXT";
    }
    if (!preg_match('/^'.$types[$type].'/', $data))
    {
        $data = str_replace("\\", "", $types[$type]).$data;
    }
    $ch = curl_init();
    $data = urlencode($data);
    curl_setopt($ch, CURLOPT_URL, 'http://chart.apis.google.com/chart');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'chs='.$size.'x'.$size.'&cht=qr&chld='.$ec.'|'.$margin.'&chl='.$data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($ch);

    curl_close($ch);
    return $response;
}

header("Content-type: image/png");

echo google_qr_code("4evertutorials","TXT");
//echo google_qr_code("http://4evertutorials.blogspot.com","URL");
//echo google_qr_code("4evertutorial@gmail.com","EMAIL");
//echo google_qr_code("1234567890","TEL");




?>

Tuesday, May 27, 2014

PHP Expire Session after 30 minutes

In following php script, we explain you that how you can expire session after 30 minutes. Execution a session timeout on your own is that the best answer. Use a straightforward time stamp that denotes the time of the last activity and update it with each request.
CODE USAGE


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


if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) 
{
    /* last request was more than 30 minutes ago */

    // unset $_SESSION variable for the run-time
    session_unset();     

    // destroy session data in storage
    session_destroy();   

}

// update last activity time stamp
$_SESSION['LAST_ACTIVITY'] = time(); 


// You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:

if (!isset($_SESSION['CREATED'])) 
{
    $_SESSION['CREATED'] = time();
}
else if (time() - $_SESSION['CREATED'] > 1800)
{
    /* session started more than 30 minutes ago */

    // change session ID for the current session an invalidate old session ID
    session_regenerate_id(true);

    // update creation time
    $_SESSION['CREATED'] = time();  

}

?>

Wednesday, March 26, 2014

check domain name availability with httpapi php


In this post we explain you that how you can check domain name availability using httpapi.com api with php and returns domain name availability status for the requested TLDs. It requires GET HTTP Method. You need following parameters:

auth-userid => your reseller id 
api-key or auth-password => your api code / account password
domain-name => Array of Strings -  that you need to check the availability for
tlds => Array of Strings - TLDs for which the domain name availability needs to be checked
suggest-alternative (optional) => pass "true" if domain name suggestions are required. Default value is false. 

After api call, you will be get the below details in response:

Domain Availability Status (status)

available - domain name available for registration

regthroughus - domain name currently registered through the Registrar whose connection is being used to check the availability of the domain name

regthroughothers - domain name currently registered through a Registrar other than the one whose connection is being used to check the availability of the domain name. If you wish to manage such a domain name through     your Reseller / Registrar Account, you may pass a Domain Transfer API call

unknown - returned, if for some reason, the Registry connections are not available. You should ideally re-check the domain name availability after some time.


For API Call, you can use following php function.


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




function Check_Domains()
{

 # API Url: for test=>https://test.httpapi.com , for live=>https://httpapi.com
 $api_url = 'https://test.httpapi.com'; 
 $auth_userid = ''; // reseller unique id
 $api_key = ''; // api-key or reseller password
 
 $domainname1 = 'enter any keyword without space'; // first domain name (example: google)
 $domainname2 = 'keyword2'; // second domain name (example: facebook)

 // top level domains 
 $tld1 = 'com'; 
 $tld2 = 'net';  

   $check_domains = $api_url.'/api/domains/available.json?auth-userid='.$auth_userid.'&api-key='.$api_key.'domain-name='.$domainname1.'&domain-name='.$domainname2.'&tlds='.$tld1.'&tlds='.$tld2;

   $result = @file_get_contents($check_domains);
   $response = json_decode($result, true);
            if($response)
            {   
                return $response;
            }
            else
            {
                return false;
            }


}



?>


Function USAGE

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



 
 $_details = Check_Domains();
 
    if($_details)
    {
     echo "
";
        print_r($_details);
        echo "
"; } else { echo ""; } ?>

 

© 2014 4everTutorials. All rights resevered.

Back To Top