Friday, December 19, 2014

Parse Website with PHP

Parse Website with PHP

Parsing website pages is always a challenge for PHP Developers. Parsing is using for retrieving images, scraping websites, crawling, error detection websites, and many other useful purposes. But PHP Simple HTML DOM Parser is a awesome or can say dream library for developer that work with both PHP and the DOM element using PHP.


You can get the Simple HTML DOM Parser from here and save file to any directory of your choice. First in a basic example we’ll include the class, and get all hyperlinks on the http://4evertutorials.blogspot.com .

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

// Include the parser library
include('simple_html_dom.php');

// Retrieve the DOM from a given URL
$html_dom = file_get_html('http://4evertutorials.blogspot.com/');

// scan for all hyperlinks and print
foreach ($html_dom->find('a') as $element) {
       print $element->href;
}

?>
Below are few basic uses of PHP Simple HTML DOM Parser.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

// Include the parser library
include('simple_html_dom.php');

// Retrieve the DOM from a given URL
$html = file_get_html('http://4evertutorials.blogspot.com/');

// Find all anchor tags and print their HREFs
foreach($html->find('a') as $e) 
    echo $e->href;

// Retrieve all images and print their SRCs
foreach($html->find('img') as $e)
    echo $e->src;

// Find all images, print their text with the "<>" included
foreach($html->find('img') as $e)
    echo $e->outertext;

// Find all SPAN tags that have a class of "SpanClass"
foreach($html->find('span.SpanClass') as $e)
    echo $e->outertext;

// Find all TD tags with "align=center"
foreach($html->find('td[align=center]') as $e)
    echo $e->innertext;

// Extract all text from a given cell
echo $html->find('td[align="center"]', 1)->plaintext;

// Find the DIV tag with an id of "DivId"
foreach($html->find('div#DivId') as $e)
    echo $e->innertext;


?>

Thursday, October 16, 2014

Install CodeIgniter Framework


In this post we will cover how to install codeigniter framework and we will view the most common steps to install codeigniter framework. CodeIgniter is one of the most popular PHP frameworks around. It uses the Model-View-Controller Architectural design pattern and it’s considered by lots of PHP developers as one of the best framework solution for small to medium projects.

How to Install

The installation itself is such a simple process. First of all, you need to download the CodeIgniter zipped file, upload it to your server and extract it into your home directory. You can download it from https://ellislab.com/codeigniter/user-guide/installation/downloads.html.

Configuring CodeIgniter

Congratulations, now you have CodeIgniter installed on your server. Now it’s time for configuration. Open the application/config/config.php file with your preferred editor and set your base URL. If you intend to use encryption or sessions, set your encryption key. For the database configuration, open the application/config/database.php file with your preferred editor and set your database host, name, user, password and other values that you think it will help you connect to your database. You will find array variables with comments to know the role of each value.

Configuration files

By editing the two previously mentioned files, you are ready to start coding your first web application but CodeIgniter contains more files that enable more configuration and customization abilities. The configuration files can be found in the application/config/ directory. The following is a quick description of what you can do by editing some of the most commonly used configuration files:

autoload.php : specifies which systems (Packages, Libraries, Helper files, Custom config files, Language files and Models) should be loaded by default.

config.php : contains all website configuration.

constants.php : contains defined constants which are used when checking and setting modes when working with the file system.

database.php : contains the settings needed to access your database.

email.php : This file is not created by default. But you can create it and set the default values for the email class. Like: mailtype, charset, newline, protocol, smtp_host, etc.

hooks.php : lets you define “hooks” to extend CI without editing the core files.

mime.php : contains an array of mime types. It is used by the upload class to help identify allowed file type.

routes.php : lets you re-map URI requests to specific controller functions.

smileys.php
: contains an array of smileys for use with the emoticon helper.

upload.php : This file is not created by default. But you can create it and set the default values for the upload class. Like: upload_path, allowed_types, max_size, max_width, max_height, etc.

user_agents.php : contains four arrays of user agent data. It is used by the User Agent Class to help identify browser, platform, robot, and mobile device data. The array keys are used to identify the device and the array values are used to set the actual name of the item.

Monday, October 6, 2014

php To PDF

php To PDF is an API based solution. We are a web service providing you the easiest way to generate PDF files from PHP Code.

Our server does the heavy lifting and generates the PDFs for you. The generated PDF files will be returned and stored on your server in the specified directory with your specified file name, or you can set them to be created and displayed or downloaded by a user on the fly.

You do not need any special packages or permissions. It works on any server running PHP!

We have simplified our API so that you just need to download the phpToPDF.php file from your account and include it in your code. It's that simple.

Get started :: PHP to PDF generation steps
Sign up to access our API   
2  FREE!
Download and include phpToPDF.php

Sample Code

Use the phptopdf() function for creating a PDF using a URL



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


    require('phpToPDF.php');

    //Set Your Options -- see documentation for all options
    $pdf_options = array(
          "source_type" => 'url',
          "source" => 'http://google.com',
          "action" => 'save');

    //Code to generate PDF file from options above
    phptopdf($pdf_options);
 

?>



Alternatively, you can use the phptopdf() function to pass a varible that holds html code for your PDF.

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

    require('phpToPDF.php');

    //Your HTML in a variable
    $my_html="

PDF from HTML using phpToPDF

"; //Set Your Options -- we are saving the PDF as 'my_filename.pdf' to a 'my_pdfs' folder $pdf_options = array( "source_type" => 'html', "source" => $my_html, "action" => 'save', "save_directory" => 'my_pdfs', "file_name" => 'my_filename.pdf'); //Code to generate PDF file from options above phptopdf($pdf_options); ?>


[ More Examples ]

Thursday, September 4, 2014

New features in PHP 5.6

The PHP development team announced new release of PHP 5.6. The new release brings new features and lots of improvements, development team say, also as some backward incompatible changes.

Following are the most important changes in PHP 5.6 release:




Constant scalar expressions
It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts where PHP previously expected a static value, such as constant and property declarations and default function arguments.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

const ONE = 1;
const TWO = ONE * 2;

class C {
    const THREE = TWO + 1;
    const ONE_THIRD = ONE / self::THREE;
    const SENTENCE = 'The value of THREE is '.self::THREE;

    public function f($a = ONE + self::THREE) {
        return $a;
    }
}

echo (new C)->f()."\n";
echo C::SENTENCE;

//The above example will output:
/*
4
The value of THREE is 3
*/

?>
Improved syntax for variadic functions
Variadic functions can be declared through a new ... operator:

<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/
 
function f($req, $opt = null, ...$params) {
    // $params is an array containing the remaining arguments.
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);

// The above example will output:
/*
$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params: 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2
$req: 1; $opt: 2; number of params: 3
*/

?>
Argument unpacking via ... operator
Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ... operator. This is also known as the splat operator in other languages, including Ruby.

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

function add($a, $b, $c) {
    return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);

// The above example will output:
/*
6
*/
?>

Exponentiation via ** operator
A right associative ** operator has been added to support exponentiation, along with a **= shorthand assignment operator.

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

printf("2 ** 3 ==      %d\n", 2 ** 3);
printf("2 ** 3 ** 2 == %d\n", 2 ** 3 ** 2);

$a = 2;
$a **= 3;
printf("a ==           %d\n", $a);

// The above example will output:
/*
2 ** 3 ==      8
2 ** 3 ** 2 == 512
a ==           8
*/

?>


use function and use const
The use operator has been extended to support importing functions and constants in addition to classes. This is achieved via the use function and use const constructs, respectively.


<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/ 
 
namespace Name\Space {
    const FOO = 42;
    function f() { echo __FUNCTION__."\n"; }
}

namespace {
    use const Name\Space\FOO;
    use function Name\Space\f;

    echo FOO."\n";
    f();
}

// The above example will output:
/*
42
Name\Space\f
*/


?>

Now UTF-8 is Default character encoding
default_charset is now used as the default character set for the htmlentities(), html_entity_decode() and htmlspecialchars() functions. Note that if the (now deprecated) iconv and mbstring encoding settings are set, they will take precedence over default_charset for iconv and mbstring functions, respectively.

Large file uploads 
Files larger than 2 gigabytes in size are now accepted.

GMP supports operator overloading
GMP objects now support operator overloading and casting to scalar types. This allows for more expressive code using GMP:
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/ 
 
$a = gmp_init(42);
$b = gmp_init(17);

// Pre-5.6 code:
var_dump(gmp_add($a, $b));
var_dump(gmp_add($a, 17));
var_dump(gmp_add(42, $b));

// New code:
var_dump($a + $b);
var_dump($a + 17);
var_dump(42 + $b);

?>

Full list of all changes in PHP 5.6 can be additionally found in the here.

Wednesday, September 3, 2014

Using Google PageSpeed Insights API with php

In this post we learn how to analyze websites using google pagespeed insights api with PHP. First of all you need to acquire an API key: 




1) Go to the Google Developers Console

2) Select a project, or create a new one. 

3) In the sidebar on the left, expand APIs & auth. Next, click APIs. In the list of APIs, make sure the status is ON for the PageSpeed Insights API. 

4) In the sidebar on the left, select Credentials

5) This API supports two types of credentials. You need only Public API access: A request that does not provide an OAuth 2.0 token must send an API key. The key identifies your project and provides API access, quota, and reports.

To create an API key, click Create new Key and select the appropriate key type. Enter the additional information required for that key type and click Create.

Replace "API_KEY" with your ones in following php function.


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

function checkPageSpeed($url){  
  if (function_exists('file_get_contents')) {  
    $result = @file_get_contents($url);  
  }  
  if ($result == '') {  
    $ch = curl_init();  
    $timeout = 60;  
    curl_setopt($ch, CURLOPT_URL, $url);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
    $result = curl_exec($ch);  
    curl_close($ch);  
  }  

  return $result;  
}

?>

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

$myKEY = "API_KEY";
$url = "http://4evertutorials.blogspot.com";
$url_req = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&key='.$myKEY;
$results = checkPageSpeed($url_req);
echo '
';
print_r(json_decode($results,true)); 
echo '
'; ?>

Friday, August 29, 2014

php linkedin company search and group search


Hello programmers, here is simple php code to extract companies and groups details which has linkedin profile. You need only pass search keyword in URL for companies or groups to get their details. It will return a JSON response with id, head line, logo url, displayname, subline, profile url

For example a search of "google" would be
http://www.linkedin.com/ta/federator?query=google&types=company,group,sitefeature

Please keep in mind linkedin API does not seem to have this feature. If you need linkedin API, please feel free to read through the documentation here.

Usage of code

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

$companies = file_get_contents('http://www.linkedin.com/ta/federator?query=google&types=company,group,sitefeature');

$results = json_decode($companies,true);

echo "
";
print_r($results);
echo "
"; ?>
Output returns
 
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

Array
(
    [company] => Array
        (
            [resultList] => Array
                (
                    [0] => Array
                        (
                            [id] => 1441
                            [headLine] => Google
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/3/000/062/2ff/080cae8.png
                            [displayName] => Google
                            [subLine] => Internet; 10,001+ employees
                            [url] => http://www.linkedin.com/company/1441
                        )

                    [1] => Array
                        (
                            [id] => 2486941
                            [headLine] => Google SEO (Page 1 Google)
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/4/000/139/37d/3d91dea.png
                            [displayName] => Google SEO (Page 1 Google)
                            [subLine] => Internet; 1-10 employees
                            [url] => http://www.linkedin.com/company/2486941
                        )

                    [2] => Array
                        (
                            [id] => 3017073
                            [headLine] => Google / Titan Aerospace
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/6/000/220/1c0/16d865f.png
                            [displayName] => Google / Titan Aerospace
                            [subLine] => Airlines/Aviation; 11-50 employees
                            [url] => http://www.linkedin.com/company/3017073
                        )

                    [3] => Array
                        (
                            [id] => 621453
                            [headLine] => Wildfire by Google
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/2/000/18f/281/144bd3b.png
                            [displayName] => Wildfire by Google
                            [subLine] => Computer Software; 201-500 employees
                            [url] => http://www.linkedin.com/company/621453
                        )

                    [4] => Array
                        (
                            [id] => 1176352
                            [headLine] => Geoambiente - Google Enterprise Partner
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/8/005/056/2ff/10d57ab.png
                            [displayName] => Geoambiente - Google Enterprise Partner
                            [subLine] => Information Technology and Services; 51-200 employees
                            [url] => http://www.linkedin.com/company/1176352
                        )

                    [5] => Array
                        (
                            [id] => 791962
                            [headLine] => Adometry by Google
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/000/18e/2ac/0e9319c.png
                            [displayName] => Adometry by Google
                            [subLine] => Marketing and Advertising; 51-200 employees
                            [url] => http://www.linkedin.com/company/791962
                        )

                    [6] => Array
                        (
                            [id] => 9863
                            [headLine] => ITA Software by Google
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/3/000/0ae/217/0b991b7.png
                            [displayName] => ITA Software by Google
                            [subLine] => Computer Software; 10,001+ employees
                            [url] => http://www.linkedin.com/company/9863
                        )

                    [7] => Array
                        (
                            [id] => 2871869
                            [headLine] => Google Account Managers
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/7/000/1e3/199/293d5b2.png
                            [displayName] => Google Account Managers
                            [subLine] => Marketing and Advertising; 1-10 employees
                            [url] => http://www.linkedin.com/company/2871869
                        )

                    [8] => Array
                        (
                            [id] => 2321528
                            [headLine] => Google AdWords Certified
                            [displayName] => Google AdWords Certified
                            [subLine] => Marketing and Advertising; Myself Only
                            [url] => http://www.linkedin.com/company/2321528
                        )

                    [9] => Array
                        (
                            [id] => 2287804
                            [headLine] => Googlelearn
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/3/000/0da/002/023b4ef.png
                            [displayName] => Googlelearn
                            [subLine] => Education Management; Myself Only
                            [url] => http://www.linkedin.com/company/2287804
                        )

                    [10] => Array
                        (
                            [id] => 3215165
                            [headLine] => Squared Online - a Google / HLC Partnership
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/6/005/056/2d9/33a677d.png
                            [displayName] => Squared Online - a Google / HLC Partnership
                            [subLine] => E-Learning; 11-50 employees
                            [url] => http://www.linkedin.com/company/3215165
                        )

                    [11] => Array
                        (
                            [id] => 2336657
                            [headLine] => Google Apps Authorized Reseller | Bmeet.it
                            [displayName] => Google Apps Authorized Reseller | Bmeet.it
                            [subLine] => Information Technology and Services; Myself Only
                            [url] => http://www.linkedin.com/company/2336657
                        )

                    [12] => Array
                        (
                            [id] => 762501
                            [headLine] => Bump Technologies (acquired by Google)
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/4/000/14c/1a4/3079095.png
                            [displayName] => Bump Technologies (acquired by Google)
                            [subLine] => Wireless; 11-50 employees
                            [url] => http://www.linkedin.com/company/762501
                        )

                    [13] => Array
                        (
                            [id] => 2093403
                            [headLine] => Video Marketing, VSEO, Google Places Optimization, Page One of Google at Cary Duke
                            [displayName] => Video Marketing, VSEO, Google Places Optimization, Page One of Google at Cary Duke
                            [subLine] => Marketing and Advertising; Myself Only
                            [url] => http://www.linkedin.com/company/2093403
                        )

                    [14] => Array
                        (
                            [id] => 2372226
                            [headLine] => Focus BC - EMEA Google Enterprise Partner
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/005/03d/3d5/1f046f8.png
                            [displayName] => Focus BC - EMEA Google Enterprise Partner
                            [subLine] => Management Consulting; 11-50 employees
                            [url] => http://www.linkedin.com/company/2372226
                        )

                    [15] => Array
                        (
                            [id] => 3489855
                            [headLine] => PANOSUR - Google Maps Business Views certified Photographer
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/005/081/09e/08920d6.png
                            [displayName] => PANOSUR - Google Maps Business Views certified Photographer
                            [subLine] => Photography; 1-10 employees
                            [url] => http://www.linkedin.com/company/3489855
                        )

                    [16] => Array
                        (
                            [id] => 3361424
                            [headLine] => Arroba System - Google Apps Authorized Reseller
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/7/005/019/37e/1933930.png
                            [displayName] => Arroba System - Google Apps Authorized Reseller
                            [subLine] => Internet; 11-50 employees
                            [url] => http://www.linkedin.com/company/3361424
                        )

                    [17] => Array
                        (
                            [id] => 978865
                            [headLine] => WIMM Labs (acquired by Google)
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/000/071/203/0b3d11a.png
                            [displayName] => WIMM Labs (acquired by Google)
                            [subLine] => Consumer Electronics; 11-50 employees
                            [url] => http://www.linkedin.com/company/978865
                        )

                    [18] => Array
                        (
                            [id] => 3081545
                            [headLine] => Google Virksomhedsbilleder: Google går indenfor i din virksomhed
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/2/000/241/1af/2f5a4b8.png
                            [displayName] => Google Virksomhedsbilleder: Google går indenfor i din virksomhed
                            [subLine] => Photography; Myself Only
                            [url] => http://www.linkedin.com/company/3081545
                        )

                    [19] => Array
                        (
                            [id] => 3200505
                            [headLine] => Google International
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/5/005/042/1fa/3d1c00e.png
                            [displayName] => Google International
                            [subLine] => Legal Services; 11-50 employees
                            [url] => http://www.linkedin.com/company/3200505
                        )

                )

        )

    [group] => Array
        (
            [resultList] => Array
                (
                    [0] => Array
                        (
                            [id] => 4248784
                            [headLine] => Google
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/3/000/128/301/196fb6a.png
                            [displayName] => Google
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=4248784&mostPopular=
                        )

                    [1] => Array
                        (
                            [id] => 4006283
                            [headLine] => GOOGLE+
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/3/000/0d7/077/064bc0b.png
                            [displayName] => GOOGLE+
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=4006283&mostPopular=
                        )

                    [2] => Array
                        (
                            [id] => 76373
                            [headLine] => Google Android
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/000/01f/3e7/2fd0a55.png
                            [displayName] => Google Android
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=76373&mostPopular=
                        )

                    [3] => Array
                        (
                            [id] => 2930475
                            [headLine] => Google Universe : Jobs, Tools, Trends and Galaxies of Ideas
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/2/000/057/1c8/2bc17fb.png
                            [displayName] => Google Universe : Jobs, Tools, Trends and Galaxies of Ideas
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=2930475&mostPopular=
                        )

                    [4] => Array
                        (
                            [id] => 1604367
                            [headLine] => Google Analytics
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/000/01f/0e8/326ef60.png
                            [displayName] => Google Analytics
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=1604367&mostPopular=
                        )

                    [5] => Array
                        (
                            [id] => 37724
                            [headLine] => Google Adwords Qualified Individuals
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/3/000/000/2fa/137b4fa.png
                            [displayName] => Google Adwords Qualified Individuals
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=37724&mostPopular=
                        )

                    [6] => Array
                        (
                            [id] => 85376
                            [headLine] => Google Apps
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/2/000/007/2c8/1b2d372.png
                            [displayName] => Google Apps
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=85376&mostPopular=
                        )

                    [7] => Array
                        (
                            [id] => 1825251
                            [headLine] => Google Professional Network
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/005/020/06c/2dedc76.png
                            [displayName] => Google Professional Network
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=1825251&mostPopular=
                        )

                    [8] => Array
                        (
                            [id] => 107462
                            [headLine] => Google APPS users
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/000/0a8/310/195dc10.png
                            [displayName] => Google APPS users
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=107462&mostPopular=
                        )

                    [9] => Array
                        (
                            [id] => 3190679
                            [headLine] => Google Adwords SEO SEM (Search Engine Optimization & Internet Marketing)
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/3/000/063/225/3d1ab3b.png
                            [displayName] => Google Adwords SEO SEM (Search Engine Optimization & Internet Marketing)
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=3190679&mostPopular=
                        )

                    [10] => Array
                        (
                            [id] => 3066064
                            [headLine] => Google Android TV
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/4/000/132/34b/148cc74.png
                            [displayName] => Google Android TV
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=3066064&mostPopular=
                        )

                    [11] => Array
                        (
                            [id] => 95911
                            [headLine] => Google Adwords
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/000/008/327/0b214eb.png
                            [displayName] => Google Adwords
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=95911&mostPopular=
                        )

                    [12] => Array
                        (
                            [id] => 36431
                            [headLine] => Google Alumni
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/000/00c/33f/0724411.png
                            [displayName] => Google Alumni
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=36431&mostPopular=
                        )

                    [13] => Array
                        (
                            [id] => 128878
                            [headLine] => Google App Engine Developers
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/000/00b/325/2709731.png
                            [displayName] => Google App Engine Developers
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=128878&mostPopular=
                        )

                    [14] => Array
                        (
                            [id] => 1840064
                            [headLine] => Google Analytics Qualified Individuals
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/2/000/01e/38e/1919a0b.png
                            [displayName] => Google Analytics Qualified Individuals
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=1840064&mostPopular=
                        )

                    [15] => Array
                        (
                            [id] => 4022728
                            [headLine] => Google Plus Marketing
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/000/0e5/2dc/34faf4e.png
                            [displayName] => Google Plus Marketing
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=4022728&mostPopular=
                        )

                    [16] => Array
                        (
                            [id] => 1873841
                            [headLine] => Google Apps Solution Providers
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/3/000/020/345/2803f2e.png
                            [displayName] => Google Apps Solution Providers
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=1873841&mostPopular=
                        )

                    [17] => Array
                        (
                            [id] => 2768916
                            [headLine] => Google+ and Google Products for Nonprofit Organizations
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/1/000/080/2fd/0d176f3.png
                            [displayName] => Google+ and Google Products for Nonprofit Organizations
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=2768916&mostPopular=
                        )

                    [18] => Array
                        (
                            [id] => 93548
                            [headLine] => Google Adwords Professional Group
                            [displayName] => Google Adwords Professional Group
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=93548&mostPopular=
                        )

                    [19] => Array
                        (
                            [id] => 1772976
                            [headLine] => Google SEO en Zoekmachine Professionals Nederland
                            [imageUrl] => http://m.c.lnkd.licdn.com/mpr/mpr/shrink_40_40/p/4/005/03b/12f/3d921f3.png
                            [displayName] => Google SEO en Zoekmachine Professionals Nederland
                            [subLine] => 
                            [url] => http://www.linkedin.com/groups?gid=1772976&mostPopular=
                        )

                )

        )

)


?>

Saturday, August 23, 2014

php capture website screenshot script

In this post we learn how to take websites screenshots very easily in PHP using Grabz.it 's API. First of all you need to create grabz.it account  to get API keys (APPLICATION KEY and APPLICATION SECRET) . Replace "APPLICATION KEY", "APPLICATION SECRET" with the values from your account. The best way to put website screenshots into your PHP application is by using our simple PHP API.
<?php

/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/
include("GrabzItClient.class.php");

$grabzIt = new GrabzItClient("APPLICATION KEY", "APPLICATION SECRET");// Replace "APPLICATION KEY", "APPLICATION SECRET" with the values from your account!

// To take a image screenshot
$grabzIt->SetImageOptions("http://www.google.com");     
// Or to take a PDF screenshot
$grabzIt->SetPDFOptions("http://www.google.com");
// Or to capture table(s)
$grabzIt->SetTableOptions("http://www.google.com");

?>

Above code is used to create class object with your account API key and secret after creating object we are calling 3 different methods SetImageOptions used to capture image of given page output, SetPDFOptions used to create PDF of given url and SetTableOptions is used to extract tables from the web page.

More Options

There are many more options including; configuring the browser height, browser width, screenshot height, screenshot width, the delay before a screenshot is taken and the image format of the screenshot. For all these options please see the Client documentation.


Wednesday, August 20, 2014

php image data uri

To create data uri in php, read image (png, gif, jpg) file with file_get_contents and convert it to base64 using base64_encode. Using Data URIs you can reduce network requests. But, Please keep in mind if you plan on using data URIs, they are not supported by ie7 and lower.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/


function createDataURI($image,$mime='') {

    $finfo = new finfo(FILEINFO_MIME_TYPE);

    $mime = $finfo->buffer(file_get_contents($image));

    return 'data:'.$mime.';base64,'.base64_encode(file_get_contents($image));
}

?>

How to  create data uri

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


echo '';

?>

best method to encrypt or decrypt in php

Here is a safe encrypt and decrypt function for php developer. You can Encrypt and Decrypt using md5. The md5() function calculates the MD5 hash of a string. md5() and sha1() provides the same functinality of encryption in php but they differ in a simple way that md5() generates 32 characters of encrypted string which sha1() generates same of 40 characters.

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


function encrypt_decrypt($action, $string) {
   $output = false;

   $key = 'My strong random secret key';

   // initialization vector 
   $iv = md5(md5($key));

   if( $action == 'encrypt' ) {
       $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, $iv);
       $output = base64_encode($output);
   }
   else if( $action == 'decrypt' ){
       $output = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, $iv);
       $output = rtrim($output, "");
   }
   return $output;
}

?>

How to use encrypt or decrypt code:
 
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/


$plain_txt = "This is my plain text";
$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "Encrypted = $encrypted_txt\n";
echo "
"; $decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt); echo "Decrypted = $decrypted_txt\n"; ?>

Monday, August 11, 2014

get country from alpha-2 code in php

ISO 3166-1 alpha-2 codes are two-letter country codes defined in ISO 3166-1, part of the ISO 3166 standard published by the International Organization for Standardization (ISO), to represent countries, dependent territories, and special areas of geographical interest. In this post we use php to get country name from alpha-2 code of country.

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



function getCountryName($code)
{
    $country = '';
    if( $code == 'AF' ) $country = 'Afghanistan';
    if( $code == 'AX' ) $country = 'Aland Islands';
    if( $code == 'AL' ) $country = 'Albania';
    if( $code == 'DZ' ) $country = 'Algeria';
    if( $code == 'AS' ) $country = 'American Samoa';
    if( $code == 'AD' ) $country = 'Andorra';
    if( $code == 'AO' ) $country = 'Angola';
    if( $code == 'AI' ) $country = 'Anguilla';
    if( $code == 'AQ' ) $country = 'Antarctica';
    if( $code == 'AG' ) $country = 'Antigua and Barbuda';
    if( $code == 'AR' ) $country = 'Argentina';
    if( $code == 'AM' ) $country = 'Armenia';
    if( $code == 'AW' ) $country = 'Aruba';
    if( $code == 'AU' ) $country = 'Australia';
    if( $code == 'AT' ) $country = 'Austria';
    if( $code == 'AZ' ) $country = 'Azerbaijan';
    if( $code == 'BS' ) $country = 'Bahamas the';
    if( $code == 'BH' ) $country = 'Bahrain';
    if( $code == 'BD' ) $country = 'Bangladesh';
    if( $code == 'BB' ) $country = 'Barbados';
    if( $code == 'BY' ) $country = 'Belarus';
    if( $code == 'BE' ) $country = 'Belgium';
    if( $code == 'BZ' ) $country = 'Belize';
    if( $code == 'BJ' ) $country = 'Benin';
    if( $code == 'BM' ) $country = 'Bermuda';
    if( $code == 'BT' ) $country = 'Bhutan';
    if( $code == 'BO' ) $country = 'Bolivia';
    if( $code == 'BA' ) $country = 'Bosnia and Herzegovina';
    if( $code == 'BW' ) $country = 'Botswana';
    if( $code == 'BV' ) $country = 'Bouvet Island (Bouvetoya)';
    if( $code == 'BR' ) $country = 'Brazil';
    if( $code == 'IO' ) $country = 'British Indian Ocean Territory (Chagos Archipelago)';
    if( $code == 'VG' ) $country = 'British Virgin Islands';
    if( $code == 'BN' ) $country = 'Brunei Darussalam';
    if( $code == 'BG' ) $country = 'Bulgaria';
    if( $code == 'BF' ) $country = 'Burkina Faso';
    if( $code == 'BI' ) $country = 'Burundi';
    if( $code == 'KH' ) $country = 'Cambodia';
    if( $code == 'CM' ) $country = 'Cameroon';
    if( $code == 'CA' ) $country = 'Canada';
    if( $code == 'CV' ) $country = 'Cape Verde';
    if( $code == 'KY' ) $country = 'Cayman Islands';
    if( $code == 'CF' ) $country = 'Central African Republic';
    if( $code == 'TD' ) $country = 'Chad';
    if( $code == 'CL' ) $country = 'Chile';
    if( $code == 'CN' ) $country = 'China';
    if( $code == 'CX' ) $country = 'Christmas Island';
    if( $code == 'CC' ) $country = 'Cocos (Keeling) Islands';
    if( $code == 'CO' ) $country = 'Colombia';
    if( $code == 'KM' ) $country = 'Comoros the';
    if( $code == 'CD' ) $country = 'Congo';
    if( $code == 'CG' ) $country = 'Congo the';
    if( $code == 'CK' ) $country = 'Cook Islands';
    if( $code == 'CR' ) $country = 'Costa Rica';
    if( $code == 'CI' ) $country = 'Cote d\'Ivoire';
    if( $code == 'HR' ) $country = 'Croatia';
    if( $code == 'CU' ) $country = 'Cuba';
    if( $code == 'CY' ) $country = 'Cyprus';
    if( $code == 'CZ' ) $country = 'Czech Republic';
    if( $code == 'DK' ) $country = 'Denmark';
    if( $code == 'DJ' ) $country = 'Djibouti';
    if( $code == 'DM' ) $country = 'Dominica';
    if( $code == 'DO' ) $country = 'Dominican Republic';
    if( $code == 'EC' ) $country = 'Ecuador';
    if( $code == 'EG' ) $country = 'Egypt';
    if( $code == 'SV' ) $country = 'El Salvador';
    if( $code == 'GQ' ) $country = 'Equatorial Guinea';
    if( $code == 'ER' ) $country = 'Eritrea';
    if( $code == 'EE' ) $country = 'Estonia';
    if( $code == 'ET' ) $country = 'Ethiopia';
    if( $code == 'FO' ) $country = 'Faroe Islands';
    if( $code == 'FK' ) $country = 'Falkland Islands (Malvinas)';
    if( $code == 'FJ' ) $country = 'Fiji the Fiji Islands';
    if( $code == 'FI' ) $country = 'Finland';
    if( $code == 'FR' ) $country = 'France, French Republic';
    if( $code == 'GF' ) $country = 'French Guiana';
    if( $code == 'PF' ) $country = 'French Polynesia';
    if( $code == 'TF' ) $country = 'French Southern Territories';
    if( $code == 'GA' ) $country = 'Gabon';
    if( $code == 'GM' ) $country = 'Gambia the';
    if( $code == 'GE' ) $country = 'Georgia';
    if( $code == 'DE' ) $country = 'Germany';
    if( $code == 'GH' ) $country = 'Ghana';
    if( $code == 'GI' ) $country = 'Gibraltar';
    if( $code == 'GR' ) $country = 'Greece';
    if( $code == 'GL' ) $country = 'Greenland';
    if( $code == 'GD' ) $country = 'Grenada';
    if( $code == 'GP' ) $country = 'Guadeloupe';
    if( $code == 'GU' ) $country = 'Guam';
    if( $code == 'GT' ) $country = 'Guatemala';
    if( $code == 'GG' ) $country = 'Guernsey';
    if( $code == 'GN' ) $country = 'Guinea';
    if( $code == 'GW' ) $country = 'Guinea-Bissau';
    if( $code == 'GY' ) $country = 'Guyana';
    if( $code == 'HT' ) $country = 'Haiti';
    if( $code == 'HM' ) $country = 'Heard Island and McDonald Islands';
    if( $code == 'VA' ) $country = 'Holy See (Vatican City State)';
    if( $code == 'HN' ) $country = 'Honduras';
    if( $code == 'HK' ) $country = 'Hong Kong';
    if( $code == 'HU' ) $country = 'Hungary';
    if( $code == 'IS' ) $country = 'Iceland';
    if( $code == 'IN' ) $country = 'India';
    if( $code == 'ID' ) $country = 'Indonesia';
    if( $code == 'IR' ) $country = 'Iran';
    if( $code == 'IQ' ) $country = 'Iraq';
    if( $code == 'IE' ) $country = 'Ireland';
    if( $code == 'IM' ) $country = 'Isle of Man';
    if( $code == 'IL' ) $country = 'Israel';
    if( $code == 'IT' ) $country = 'Italy';
    if( $code == 'JM' ) $country = 'Jamaica';
    if( $code == 'JP' ) $country = 'Japan';
    if( $code == 'JE' ) $country = 'Jersey';
    if( $code == 'JO' ) $country = 'Jordan';
    if( $code == 'KZ' ) $country = 'Kazakhstan';
    if( $code == 'KE' ) $country = 'Kenya';
    if( $code == 'KI' ) $country = 'Kiribati';
    if( $code == 'KP' ) $country = 'Korea';
    if( $code == 'KR' ) $country = 'Korea';
    if( $code == 'KW' ) $country = 'Kuwait';
    if( $code == 'KG' ) $country = 'Kyrgyz Republic';
    if( $code == 'LA' ) $country = 'Lao';
    if( $code == 'LV' ) $country = 'Latvia';
    if( $code == 'LB' ) $country = 'Lebanon';
    if( $code == 'LS' ) $country = 'Lesotho';
    if( $code == 'LR' ) $country = 'Liberia';
    if( $code == 'LY' ) $country = 'Libyan Arab Jamahiriya';
    if( $code == 'LI' ) $country = 'Liechtenstein';
    if( $code == 'LT' ) $country = 'Lithuania';
    if( $code == 'LU' ) $country = 'Luxembourg';
    if( $code == 'MO' ) $country = 'Macao';
    if( $code == 'MK' ) $country = 'Macedonia';
    if( $code == 'MG' ) $country = 'Madagascar';
    if( $code == 'MW' ) $country = 'Malawi';
    if( $code == 'MY' ) $country = 'Malaysia';
    if( $code == 'MV' ) $country = 'Maldives';
    if( $code == 'ML' ) $country = 'Mali';
    if( $code == 'MT' ) $country = 'Malta';
    if( $code == 'MH' ) $country = 'Marshall Islands';
    if( $code == 'MQ' ) $country = 'Martinique';
    if( $code == 'MR' ) $country = 'Mauritania';
    if( $code == 'MU' ) $country = 'Mauritius';
    if( $code == 'YT' ) $country = 'Mayotte';
    if( $code == 'MX' ) $country = 'Mexico';
    if( $code == 'FM' ) $country = 'Micronesia';
    if( $code == 'MD' ) $country = 'Moldova';
    if( $code == 'MC' ) $country = 'Monaco';
    if( $code == 'MN' ) $country = 'Mongolia';
    if( $code == 'ME' ) $country = 'Montenegro';
    if( $code == 'MS' ) $country = 'Montserrat';
    if( $code == 'MA' ) $country = 'Morocco';
    if( $code == 'MZ' ) $country = 'Mozambique';
    if( $code == 'MM' ) $country = 'Myanmar';
    if( $code == 'NA' ) $country = 'Namibia';
    if( $code == 'NR' ) $country = 'Nauru';
    if( $code == 'NP' ) $country = 'Nepal';
    if( $code == 'AN' ) $country = 'Netherlands Antilles';
    if( $code == 'NL' ) $country = 'Netherlands the';
    if( $code == 'NC' ) $country = 'New Caledonia';
    if( $code == 'NZ' ) $country = 'New Zealand';
    if( $code == 'NI' ) $country = 'Nicaragua';
    if( $code == 'NE' ) $country = 'Niger';
    if( $code == 'NG' ) $country = 'Nigeria';
    if( $code == 'NU' ) $country = 'Niue';
    if( $code == 'NF' ) $country = 'Norfolk Island';
    if( $code == 'MP' ) $country = 'Northern Mariana Islands';
    if( $code == 'NO' ) $country = 'Norway';
    if( $code == 'OM' ) $country = 'Oman';
    if( $code == 'PK' ) $country = 'Pakistan';
    if( $code == 'PW' ) $country = 'Palau';
    if( $code == 'PS' ) $country = 'Palestinian Territory';
    if( $code == 'PA' ) $country = 'Panama';
    if( $code == 'PG' ) $country = 'Papua New Guinea';
    if( $code == 'PY' ) $country = 'Paraguay';
    if( $code == 'PE' ) $country = 'Peru';
    if( $code == 'PH' ) $country = 'Philippines';
    if( $code == 'PN' ) $country = 'Pitcairn Islands';
    if( $code == 'PL' ) $country = 'Poland';
    if( $code == 'PT' ) $country = 'Portugal, Portuguese Republic';
    if( $code == 'PR' ) $country = 'Puerto Rico';
    if( $code == 'QA' ) $country = 'Qatar';
    if( $code == 'RE' ) $country = 'Reunion';
    if( $code == 'RO' ) $country = 'Romania';
    if( $code == 'RU' ) $country = 'Russian Federation';
    if( $code == 'RW' ) $country = 'Rwanda';
    if( $code == 'BL' ) $country = 'Saint Barthelemy';
    if( $code == 'SH' ) $country = 'Saint Helena';
    if( $code == 'KN' ) $country = 'Saint Kitts and Nevis';
    if( $code == 'LC' ) $country = 'Saint Lucia';
    if( $code == 'MF' ) $country = 'Saint Martin';
    if( $code == 'PM' ) $country = 'Saint Pierre and Miquelon';
    if( $code == 'VC' ) $country = 'Saint Vincent and the Grenadines';
    if( $code == 'WS' ) $country = 'Samoa';
    if( $code == 'SM' ) $country = 'San Marino';
    if( $code == 'ST' ) $country = 'Sao Tome and Principe';
    if( $code == 'SA' ) $country = 'Saudi Arabia';
    if( $code == 'SN' ) $country = 'Senegal';
    if( $code == 'RS' ) $country = 'Serbia';
    if( $code == 'SC' ) $country = 'Seychelles';
    if( $code == 'SL' ) $country = 'Sierra Leone';
    if( $code == 'SG' ) $country = 'Singapore';
    if( $code == 'SK' ) $country = 'Slovakia (Slovak Republic)';
    if( $code == 'SI' ) $country = 'Slovenia';
    if( $code == 'SB' ) $country = 'Solomon Islands';
    if( $code == 'SO' ) $country = 'Somalia, Somali Republic';
    if( $code == 'ZA' ) $country = 'South Africa';
    if( $code == 'GS' ) $country = 'South Georgia and the South Sandwich Islands';
    if( $code == 'ES' ) $country = 'Spain';
    if( $code == 'LK' ) $country = 'Sri Lanka';
    if( $code == 'SD' ) $country = 'Sudan';
    if( $code == 'SR' ) $country = 'Suriname';
    if( $code == 'SJ' ) $country = 'Svalbard & Jan Mayen Islands';
    if( $code == 'SZ' ) $country = 'Swaziland';
    if( $code == 'SE' ) $country = 'Sweden';
    if( $code == 'CH' ) $country = 'Switzerland, Swiss Confederation';
    if( $code == 'SY' ) $country = 'Syrian Arab Republic';
    if( $code == 'TW' ) $country = 'Taiwan';
    if( $code == 'TJ' ) $country = 'Tajikistan';
    if( $code == 'TZ' ) $country = 'Tanzania';
    if( $code == 'TH' ) $country = 'Thailand';
    if( $code == 'TL' ) $country = 'Timor-Leste';
    if( $code == 'TG' ) $country = 'Togo';
    if( $code == 'TK' ) $country = 'Tokelau';
    if( $code == 'TO' ) $country = 'Tonga';
    if( $code == 'TT' ) $country = 'Trinidad and Tobago';
    if( $code == 'TN' ) $country = 'Tunisia';
    if( $code == 'TR' ) $country = 'Turkey';
    if( $code == 'TM' ) $country = 'Turkmenistan';
    if( $code == 'TC' ) $country = 'Turks and Caicos Islands';
    if( $code == 'TV' ) $country = 'Tuvalu';
    if( $code == 'UG' ) $country = 'Uganda';
    if( $code == 'UA' ) $country = 'Ukraine';
    if( $code == 'AE' ) $country = 'United Arab Emirates';
    if( $code == 'GB' ) $country = 'United Kingdom';
    if( $code == 'US' ) $country = 'United States of America';
    if( $code == 'UM' ) $country = 'United States Minor Outlying Islands';
    if( $code == 'VI' ) $country = 'United States Virgin Islands';
    if( $code == 'UY' ) $country = 'Uruguay, Eastern Republic of';
    if( $code == 'UZ' ) $country = 'Uzbekistan';
    if( $code == 'VU' ) $country = 'Vanuatu';
    if( $code == 'VE' ) $country = 'Venezuela';
    if( $code == 'VN' ) $country = 'Vietnam';
    if( $code == 'WF' ) $country = 'Wallis and Futuna';
    if( $code == 'EH' ) $country = 'Western Sahara';
    if( $code == 'YE' ) $country = 'Yemen';
    if( $code == 'ZM' ) $country = 'Zambia';
    if( $code == 'ZW' ) $country = 'Zimbabwe';
    if( $country == '') $country = $code;
    return $country;
}


?>


Usage:-


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

// for get United States of America use following syntax
echo getCountryName('US');



?>

Create sitemap.xml.gz using PHP

In this in post we learn how to generate compressed XML sitemap with php. If some reason Apache does not support gzipping - old version, modules not enabled etc, you can use PHP to generate the compressed XML sitemap. PHP comes with a module of its own to generate gzipped content. Execute phpinfo() and look for the strings "deflate" and "gzip", if you found them, you are ready to start outputting compressed content right away, all you have to do is send the header header('content-type: application/x-gzip') to send the content as a gzipped file.

Following example show you how you can do that:

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

$file_name = 'sitemap.xml';
header('content-type: application/x-gzip');
header('Content-Disposition: attachment; filename="'.$file_name.'.gz"');
$data = "dynamic XML sitemap string goes here";
$gzdata = gzencode($data, 9);
echo $gzdata;

?>

Wednesday, August 6, 2014

extract meta tag content in php

In last post we add script about grab webpage title tag and description , keywords meta tag content. But now this post we explain that how programmer can extract all the meta tags information from specific webpage with get_meta_tags and returns an array.
 


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


function get_meta_data($url, $searchkey='') {   
    $data = get_meta_tags($url);    // get the meta data in an array
    foreach($data as $key => $value) {
        if(mb_detect_encoding($value, 'UTF-8, ISO-8859-1', true) != 'ISO-8859-1') {    // check whether the content is UTF-8 or ISO-8859-1
            $value = utf8_decode($value);    // if UTF-8 decode it
        }
        $value = strtr($value, get_html_translation_table(HTML_ENTITIES));    // mask the content
        if($searchkey != '') {    // if only one meta tag is in demand e.g. 'description'
            if($key == $searchkey) {
                $str = $value;    // just return the value
            }
        } else {    // all meta tags
            $pattern = '/ |,/i';    // ' ' or ','
            $array = preg_split($pattern, $value, -1, PREG_SPLIT_NO_EMPTY);    // split it in an array, so we have the count of words           
            $str .= '

' . $key . ' (' . count($array) . ' words | ' . strlen($value) . ' chars)' . $value . '

'; // format data with count of words and chars } } return $str; } ?>
How you can use get_meta_data
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

$content = get_meta_data("http://4evertutorials.blogspot.com/"); 

echo "
";
print_r($content);
echo "
"; ?>

Monday, August 4, 2014

get title, meta tags info in php

This php script grab title tag and description, keywords meta of specified url with simple php curl function. And show all information in title tag , meta description and meta keywords tags.

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

function file_get_contents_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

$html = file_get_contents_curl("http://4evertutorials.blogspot.com/");

$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');

for ($i = 0; $i < $metas->length; $i++)
{
    $meta = $metas->item($i);
    if($meta->getAttribute('name') == 'description')
        $description = $meta->getAttribute('content');
    if($meta->getAttribute('name') == 'keywords')
        $keywords = $meta->getAttribute('content');
}

echo "Title: $title". '

';
echo "Description: $description". '

';
echo "Keywords: $keywords";





?>

Friday, August 1, 2014

manage email accounts using cPanel API in php

In this blog post we learn how php class can create and manage email accounts using the cPanel API. It can send HTTP requests to the cPanel API of a hosting account to perform several types of operations to manage email accounts.

Currently this class has following functions:
- check if a given email account exists
- create a new email account
- get the list of created email accounts
- change the password of an email account
- delete an email account.

For use this class first create a file name "class.email.php" without double quote. And copy following code , paste and save.

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


class cPanelEmailManager {
    private $cpanelHost;
    private $cpanelPort;
    private $username;
    private $password;
    private $logcurl;
    private $cookiefile;
    private $curlfile;
    private $emailArray;
    private $cpsess;

    /**
     * Constructor
     * @param string $user cPanel username
     * @param string $pass cPanel password
     * @param string $host cPanel domain
     * @param int $port cPanel domain
    */
    public function __construct($user,$pass,$host,$port=2083){
        $this->cpanelHost = $host;
        $this->cpanelPort = $port;
        $this->username = $user;
        $this->password = $pass;
        $this->logcurl = false;
        $this->cookiefile = "cpmm/cpmm_cookie_".rand(99999, 9999999).".txt";
        $this->LogIn();
    }

    /**
     * Checks if an email address exists
     * @param string $Needle Email address to check
     * @param bool $FullEmailOnly If false, will return true with or without the domain attached
     * @return bool
    */
    public function emailExists($Needle, $FullEmailOnly = false){
        $Haystack = empty($this->emailArray) ? $this->getEmails() : $this->emailArray;
        foreach($Haystack as $H){
            if($FullEmailOnly === true && $H['email'] == $Needle){
                return true;
            }else if($FullEmailOnly !== true && ($H['user'] == $Needle || $H['email'] == $Needle)){
                return true;
            }
        }
        return false;
    }

    /**
     * Creates a new email address
     * @param string $email Complete mail address to create, ie. myemail@mydomain.com
     * @param string $password Password for new email
     * @param string $quota Disk Space Quota, 0 for unlimited
     * @return bool
    */
    public function createEmail($email,$password,$quota = 0){
        if($this->emailExists($email,true)){
            return "Email address ".$email." already exist";
        }
        $e = explode("@",$email);
        $params = 'user='.$this->username.'&pass='.$this->password;;
        $url = "https://".$this->cpanelHost.":".$this->cpanelPort.$this->cpsess."/json-api/cpanel".
        "?cpanel_jsonapi_version=2".
        "&cpanel_jsonapi_func=addpop".
        "&cpanel_jsonapi_module=Email&".
        "email=".$e[0]."&".
        "domain=".$e[1]."&".
        "password=".urlencode($password)."&".
        "quota=".$quota;
        $answer = json_decode($this->Request($url,$params), true);
        $this->getEmails(true);
        return ($answer["cpanelresult"]["data"][0]['result'] === 1) ? true : false;
    }

    /**
     * Deletes an email address
     * @param string $email Complete mail address to delete, ie. myemail@mydomain.com
     * @return bool
    */
    public function deleteEmail($email){
        if(!$this->emailExists($email,true)){
            return "Email address ".$email." does not exist";
        }
        $e = explode("@",$email);
        $params = 'user='.$this->username.'&pass='.$this->password;;
        $url = "https://".$this->cpanelHost.":".$this->cpanelPort.$this->cpsess."/json-api/cpanel".
        "?cpanel_jsonapi_version=2".
        "&cpanel_jsonapi_func=delpop".
        "&cpanel_jsonapi_module=Email&".
        "email=".$e[0]."&".
        "domain=".$e[1];
        $answer = json_decode($this->Request($url,$params), true);
        $this->getEmails(true);
        return ($answer["cpanelresult"]["data"][0]['result'] === 1) ? true : false;
    }

    /**
     * Changes a password
     * @param string $email Complete email of account, ie. myemail@mydomain.com
     * @param string $newPW New password
     * @return bool
    */
    public function changePW($email, $newPW){
        if(!$this->emailExists($email,true)){
            return "Email address ".$email." does not exist";
        }
        $e = explode("@",$email);
        $params = 'user='.$this->username.'&pass='.$this->password;;
        $url = "https://".$this->cpanelHost.":".$this->cpanelPort.$this->cpsess."/json-api/cpanel".
        "?cpanel_jsonapi_version=2".
        "&cpanel_jsonapi_func=passwdpop".
        "&cpanel_jsonapi_module=Email&".
        "email=".$e[0]."&".
        "domain=".$e[1]."&".
        "password=".urlencode($newPW);
        $answer = json_decode($this->Request($url,$params), true);
        $this->getEmails(true);
        return ($answer["cpanelresult"]["data"][0]['result'] === 1) ? true : false;
    }

    /**
     * Lists all email accounts and their properties
     * @param int $pageSize Number of results per page
     * @param int $currentPage Page number to start from
     * @param bool $paginate Return in pages
     * @param bool $sort Sort the results
     * @param bstring $sortby Column to sort by, ie. "email", "_diskused", "mtime", or "domain"
     * @return array
    */
    public function listEmails($pageSize = 10, $currentPage = 1, $paginate = true, $sort = true, $sortby = "user"){
        $params = 'user='.$this->username.'&pass='.$this->password;;
        $url = "https://".$this->cpanelHost.":".$this->cpanelPort.$this->cpsess."/json-api/cpanel".
        "?cpanel_jsonapi_version=2".
        "&cpanel_jsonapi_func=listpopswithdisk".
        "&cpanel_jsonapi_module=Email".
        "&api2_paginate=".($paginate === false ? 0 : 1).
        "&api2_paginate_size=".$pageSize.
        "&api2_paginate_start=".$currentPage.
        "&api2_sort=".($sort === false ? 0 : 1).
        "&api2_sort_column=".$sortby.
        "&api2_sort_method=alphabet".
        "&api2_sort_reverse=0";
        $answer = $this->Request($url,$params);
        $emails = json_decode($answer, true);
        $this->emailArray = $emails["cpanelresult"]["data"];
        return $this->emailArray;
    }

    /**
     * Turns cURL logging on
     * @param int $curlfile Path to curl log file
     * @return array
    */
    public function logCurl($curlfile = "cpmm/cpmm_curl_log.txt"){
        if(!file_exists($curlfile)){
            try{
                fopen($curlfile, "w");
            }catch(Exception $ex){
                if(!file_exists($curlfile)){
                    return $ex.'Cookie file missing.'; exit;
                }
                return true;
            }
        }else if(!is_writable($curlfile)){
            return 'Cookie file not writable.'; exit;
        }
        $this->logcurl = true;
        return true;
    }
    
    /**
     * Returns a complete list of emails and their properties
     * @access private
    */
    private function getEmails($refresh = false){
        if(!empty($this->emailArray) && !$refresh){
            return $this->emailArray;
        }
        $params = 'user='.$this->username.'&pass='.$this->password;;
        $url = "https://".$this->cpanelHost.":".$this->cpanelPort.$this->cpsess."/json-api/cpanel".
        "?cpanel_jsonapi_version=2".
        "&cpanel_jsonapi_func=listpopswithdisk".
        "&cpanel_jsonapi_module=Email";
        $answer = $this->Request($url,$params);
        $emails = json_decode($answer, true);
        $this->emailArray = $emails["cpanelresult"]["data"];
        return $this->emailArray;
    }

    /**
     * Starts a session on the cPanel server
     * @access private
    */
    private function LogIn(){
        $url = 'https://'.$this->cpanelHost.":".$this->cpanelPort."/login/?login_only=1";
        $url .= "&user=".$this->username."&pass=".urlencode($this->password);
        $answer = $this->Request($url);
        $answer = json_decode($answer, true);
        if(isset($answer['status']) && $answer['status'] == 1){
            $this->cpsess = $answer['security_token'];
            $this->homepage = 'https://'.$this->cpanelHost.":".$this->cpanelPort.$answer['redirect'];
        }
    }

    /**
     * Makes an HTTP request
     * @access private
    */
    private function Request($url,$params=array()){
        if($this->logcurl){
            $curl_log = fopen($this->curlfile, 'a+');
        }
        if(!file_exists($this->cookiefile)){
            try{
                fopen($this->cookiefile, "w");
            }catch(Exception $ex){
                if(!file_exists($this->cookiefile)){
                    echo $ex.'Cookie file missing.'; exit;
                }
            }
        }else if(!is_writable($this->cookiefile)){
            echo 'Cookie file not writable.'; exit;
        }
        $ch = curl_init();
        $curlOpts = array(
            CURLOPT_URL             => $url,
            CURLOPT_USERAGENT       => 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_RETURNTRANSFER  => true,
            CURLOPT_COOKIEJAR       => realpath($this->cookiefile),
            CURLOPT_COOKIEFILE      => realpath($this->cookiefile),
            CURLOPT_FOLLOWLOCATION  => true,
            CURLOPT_HTTPHEADER      => array(
                "Host: ".$this->cpanelHost,
                "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                "Accept-Language: en-US,en;q=0.5",
                "Accept-Encoding: gzip, deflate",
                "Connection: keep-alive",
                "Content-Type: application/x-www-form-urlencoded")
        );
        if(!empty($params)){
            $curlOpts[CURLOPT_POST] = true;
            $curlOpts[CURLOPT_POSTFIELDS] = $params;
        }
        if($this->logcurl){
            $curlOpts[CURLOPT_STDERR] = $curl_log;
            $curlOpts[CURLOPT_FAILONERROR] = false;
            $curlOpts[CURLOPT_VERBOSE] = true;
        }
        curl_setopt_array($ch,$curlOpts);
        $answer = curl_exec($ch);
        if (curl_error($ch)) {
            echo curl_error($ch); exit;
        }
        curl_close($ch);
        if($this->logcurl){
            fclose($curl_log);
        }
        return (@gzdecode($answer)) ? gzdecode($answer) : $answer;
    }
}



?>

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


	// include the library
	require("class.email.php");

	// cPanel domain or IP
	$host = "mywebsite.com";

	// cPanel Username
	$user = "cPanel_Username";

	// cPanel Password
	$pass = "cPanel_Password";

	if($host == "mywebsite.com"){
	    echo "Put your cPanel credentials in and remove line ".__LINE__." from the example script before running."; exit;
	}

	// initialize the class
	$cpmm = new cPanelEmailManager($user, $pass, $host);

	// Create a new email address
	$email = "newemail@mywebsite.com";
	$password = "mybadpassword";
	$result = $cpmm->createEmail($email,$password);
	echo "Email ($email) ".($result ? "successfully" : "not")." created.
"; // Check if an email exists $email = "newemail@mywebsite.com"; $result = $cpmm->emailExists($email); echo "Email ($email) ".($result ? "does" : "does not")." exist.
"; // Change an email password $email = "newemail@mywebsite.com"; $newPassword = "mybetterpassword"; $result = $cpmm->changePW($email,$newPassword); echo ($result ? "Changed" : "Could not change")." password for email $email.
"; // Delete an email account $email = "newemail@mywebsite.com"; $result = $cpmm->deleteEmail($email); echo ($result ? "Deleted" : "Could not delete")." email account $email.
"; // List email accounts $pageSize = 15; $pageNo = 1; $result = $cpmm->listEmails($pageSize, $pageNo); var_dump($result); ?>




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.
 

© 2014 4everTutorials. All rights resevered.

Back To Top