Monday, December 30, 2013

Common security functions in PHP





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

/**
 * IsEmpty
 * 
 * @param mixed $value
 * @return boolean
 */
function IsEmpty($value) {
    if(strlen(trim(preg_replace('/\xc2\xa0/',' ',$value))) == 0) {
        return true;
    }else {
        return false;
    }
}


?>




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

/**
 * Sanitize
 * 
 * @param mixed $value
 * @return string
 */
function Sanitize($value) {
    if(get_magic_quotes_gpc()) $value = stripslashes($value);
    return htmlentities($value, ENT_QUOTES, 'utf-8');
}


?>





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

/**
 * ParseId
 * 
 * @param integer $id
 * @param integer $segment
 * @return mixed
 */
function ParseId($id, $segment = 2) {
    $pattern = '/^([0-9]+)-';
    for($i = 2; $i < $segment; $i++) {
        $pattern .= '([0-9]+)-';
    }
    $pattern .= '([0-9]+)$/';
    if(!preg_match($pattern, $id, $match)) {
        return false;
    }else {
        return $match;
    }
}


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


/**
 * ValidEmail
 * 
 * @param string $email
 * @return boolean
 */
function ValidEmail($email) {
    if(preg_match("/^[0-9a-z]+(([\.\-_])[0-9a-z]+)*@[0-9a-z]+(([\.\-])[0-9a-z-]+)*\.[a-z]{2,4}$/i", $email)) {
        return true;
    }else {
        return false;
    }
}

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


/**
 * ValidURL
 * 
 * @param string $email
 * @return boolean
 */
function ValidURL($url) {
    if(preg_match('/^https?:\/\/[^\s]+/i', $url)) {
        return true;
    }else {
        return false;
    }
}

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


/**
 * ValidString
 * 
 * @param string $string
 * @return boolean
 */
function ValidString($string) {
    if(preg_match('/^[a-z0-9A-z ]*$/i', $string)) {
        return true;
    }else {
        return false;
    }
}


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

/**
 * ValidUserName
 * 
 * @param string $string
 * @return boolean
 */
function ValidUserName($string) {
    if(preg_match('/^[a-z0-9]*$/i', $string)) {
        return true;
    }else {
        return false;
    }
}

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

/**
 * ValidImg
 * 
 * @param string $file
 * @return boolean
 */
function ValidImg($file) {
    $extensions = array('jpg','gif','png');
    $len  = strLen($file)-3;
    $ext  = strtolower(substr($file, $len, 3));
    if(in_array($ext, $extensions)) {
        return true;
    }else {
        return false;
    }
}


?>

Social Media URLs and PHP and JQuery


In this post we are learn check popularity of URL across social network like Facebook, Twitter, Reddit, Google plus, StumbleUpon, LinkedIn and Pinterest. Popularity means URL  how many times shared ,liked ,commented and pinned by the users across the social networks.

Note:  Use CURL function to grab this purpose. 

Facebook:

https://graph.facebook.com/fql?q=SELECT+like_count%2C+total_count%2C+share_count%2C+click_count%2C+comment_count+FROM+link_stat+WHERE+url+%3D+%22http%3A%2F%2Fgoogle.co.in%2F%22


It returns:

{
   "data": [
      {
         "like_count": 58263,
         "total_count": 211166,
         "share_count": 125191,
         "click_count": 86,
         "comment_count": 27712
      }
   ]
}






Twitter:

https://cdn.api.twitter.com/1/urls/count.json?url=http%3A%2F%2Fgoogle.co.in


It returns:

{"count":762,"url":"http:\/\/google.co.in\/"}









Reddit:

http://www.reddit.com/api/info.json?url=http%3A%2F%2Fgoogle.co.in

It returns:

{"kind": "Listing", "data": {"modhash": "", "children": [{"kind": "t3", "data": {"domain": "google.co.in", "banned_by": null, "media_embed": {}, "subreddit": "technology", "selftext_html": null, "selftext": "", "likes": null, "secure_media": null, "link_flair_text": null, "id": "100fzk", "secure_media_embed": {}, "clicked": false, "stickied": false, "author": "marktripeasy", "media": null, "score": 1, "approved_by": null, "over_18": false, "hidden": false, "thumbnail": "", "subreddit_id": "t5_2qh16", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 0, "saved": false, "is_self": false, "permalink": "/r/technology/comments/100fzk/httplocalhost42600loyaltyaccountpointsummary/", "name": "t3_100fzk", "created": 1347867646.0, "url": "http://google.co.in", "author_flair_text": null, "title": "http://localhost:42600/Loyalty/Account/PointSummary", "created_utc": 1347864046.0, "ups": 1, "num_comments": 0, "visited": false, "num_reports": null, "distinguished": null}}, {"kind": "t3", "data": {"domain": "google.co.in", "banned_by": null, "media_embed": {}, "subreddit": "AdviceAnimals", "selftext_html": null, "selftext": "", "likes": null, "secure_media": null, "link_flair_text": null, "id": "s40co", "secure_media_embed": {}, "clicked": false, "stickied": false, "author": "ayushrj", "media": null, "score": 1, "approved_by": null, "over_18": false, "hidden": false, "thumbnail": "default", "subreddit_id": "t5_2s7tt", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 0, "saved": false, "is_self": false, "permalink": "/r/AdviceAnimals/comments/s40co/google/", "name": "t3_s40co", "created": 1334131500.0, "url": "http://www.google.co.in", "author_flair_text": null, "title": "Google", "created_utc": 1334127900.0, "ups": 1, "num_comments": 1, "visited": false, "num_reports": null, "distinguished": null}}, {"kind": "t3", "data": {"domain": "google.co.in", "banned_by": null, "media_embed": {}, "subreddit": "funny", "selftext_html": null, "selftext": "", "likes": null, "secure_media": null, "link_flair_text": null, "id": "7zkbq", "secure_media_embed": {}, "clicked": false, "stickied": false, "author": "mbbala", "media": null, "score": 0, "approved_by": null, "over_18": false, "hidden": false, "thumbnail": "default", "subreddit_id": "t5_2qh33", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 1, "saved": false, "is_self": false, "permalink": "/r/funny/comments/7zkbq/my_first_page/", "name": "t3_7zkbq", "created": 1235393963.0, "url": "http://www.google.co.in", "author_flair_text": null, "title": "My First Page", "created_utc": 1235393963.0, "ups": 1, "num_comments": 0, "visited": false, "num_reports": null, "distinguished": null}}, {"kind": "t3", "data": {"domain": "google.co.in", "banned_by": null, "media_embed": {}, "subreddit": "todayilearned", "selftext_html": null, "selftext": "", "likes": null, "secure_media": null, "link_flair_text": null, "id": "hv9ap", "secure_media_embed": {}, "clicked": false, "stickied": false, "author": "turner13", "media": null, "score": 0, "approved_by": null, "over_18": false, "hidden": false, "thumbnail": "default", "subreddit_id": "t5_2qqjc", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 2, "saved": false, "is_self": false, "permalink": "/r/todayilearned/comments/hv9ap/til_the_guitar_was_invented_by_les_paul_by/", "name": "t3_hv9ap", "created": 1307598634.0, "url": "http://www.google.co.in", "author_flair_text": null, "title": "TIL the Guitar was invented by Les Paul by visiting the Google Home Page today. There is a Guitar on Google Home page which plays music too..", "created_utc": 1307595034.0, "ups": 2, "num_comments": 3, "visited": false, "num_reports": null, "distinguished": null}}, {"kind": "t3", "data": {"domain": "google.co.in", "banned_by": null, "media_embed": {}, "subreddit": "science", "selftext_html": null, "selftext": "", "likes": null, "secure_media": null, "link_flair_text": null, "id": "1170xo", "secure_media_embed": {}, "clicked": false, "stickied": false, "author": "moneykannan", "media": null, "score": 0, "approved_by": null, "over_18": false, "hidden": false, "thumbnail": "", "subreddit_id": "t5_mouw", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 6, "saved": false, "is_self": false, "permalink": "/r/science/comments/1170xo/search/", "name": "t3_1170xo", "created": 1349793735.0, "url": "http://www.google.co.in", "author_flair_text": null, "title": "SEARCH", "created_utc": 1349790135.0, "ups": 3, "num_comments": 0, "visited": false, "num_reports": null, "distinguished": null}}, {"kind": "t3", "data": {"domain": "google.co.in", "banned_by": null, "media_embed": {}, "subreddit": "ExploreAmerica", "selftext_html": null, "selftext": "", "likes": null, "secure_media": null, "link_flair_text": null, "id": "13bj9u", "secure_media_embed": {}, "clicked": false, "stickied": false, "author": "moheetarora", "media": null, "score": 1, "approved_by": null, "over_18": false, "hidden": false, "thumbnail": "", "subreddit_id": "t5_2umqx", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 0, "saved": false, "is_self": false, "permalink": "/r/ExploreAmerica/comments/13bj9u/googling/", "name": "t3_13bj9u", "created": 1353101986.0, "url": "http://www.google.co.in", "author_flair_text": null, "title": "googling", "created_utc": 1353101986.0, "ups": 1, "num_comments": 0, "visited": false, "num_reports": null, "distinguished": null}}, {"kind": "t3", "data": {"domain": "google.co.in", "banned_by": null, "media_embed": {}, "subreddit": "politics", "selftext_html": null, "selftext": "", "likes": null, "secure_media": null, "link_flair_text": null, "id": "zfvol", "secure_media_embed": {}, "clicked": false, "stickied": false, "author": "barackromney", "media": null, "score": 1, "approved_by": null, "over_18": false, "hidden": false, "thumbnail": "", "subreddit_id": "t5_2cneq", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 0, "saved": false, "is_self": false, "permalink": "/r/politics/comments/zfvol/barackromney_yes_we_can_together_believe_in/", "name": "t3_zfvol", "created": 1346922086.0, "url": "http://google.co.in", "author_flair_text": null, "title": "BarackRomney: \"Yes We can Together Believe in America\"", "created_utc": 1346918486.0, "ups": 1, "num_comments": 1, "visited": false, "num_reports": null, "distinguished": null}}, {"kind": "t3", "data": {"domain": "google.co.in", "banned_by": null, "media_embed": {}, "subreddit": "sex", "selftext_html": null, "selftext": "", "likes": null, "secure_media": null, "link_flair_text": null, "id": "f01o3", "secure_media_embed": {}, "clicked": false, "stickied": false, "author": "lmyadav", "media": null, "score": 1, "approved_by": null, "over_18": false, "hidden": false, "thumbnail": "default", "subreddit_id": "t5_2qh3p", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 0, "saved": false, "is_self": false, "permalink": "/r/sex/comments/f01o3/hhh/", "name": "t3_f01o3", "created": 1294724871.0, "url": "http://www.google.co.in", "author_flair_text": null, "title": "hhh", "created_utc": 1294724871.0, "ups": 1, "num_comments": 0, "visited": false, "num_reports": null, "distinguished": null}}, {"kind": "t3", "data": {"domain": "google.co.in", "banned_by": null, "media_embed": {}, "subreddit": "Twitter", "selftext_html": null, "selftext": "", "likes": null, "secure_media": null, "link_flair_text": null, "id": "bh817", "secure_media_embed": {}, "clicked": false, "stickied": false, "author": "hruaia", "media": null, "score": 1, "approved_by": null, "over_18": false, "hidden": false, "thumbnail": "default", "subreddit_id": "t5_2qhwg", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 0, "saved": false, "is_self": false, "permalink": "/r/Twitter/comments/bh817/google/", "name": "t3_bh817", "created": 1269371573.0, "url": "http://www.google.co.in", "author_flair_text": null, "title": "Google", "created_utc": 1269367973.0, "ups": 1, "num_comments": 1, "visited": false, "num_reports": null, "distinguished": null}}, {"kind": "t3", "data": {"domain": "google.co.in", "banned_by": null, "media_embed": {}, "subreddit": "reddit.com", "selftext_html": null, "selftext": "", "likes": null, "secure_media": null, "link_flair_text": null, "id": "dx2to", "secure_media_embed": {}, "clicked": false, "stickied": false, "author": "hrkindian", "media": null, "score": 0, "approved_by": null, "over_18": false, "hidden": false, "thumbnail": "", "subreddit_id": "t5_6", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 6, "saved": false, "is_self": false, "permalink": "/r/reddit.com/comments/dx2to/google/", "name": "t3_dx2to", "created": 1288174192.0, "url": "http://www.google.co.in", "author_flair_text": null, "title": "Google", "created_utc": 1288170592.0, "ups": 2, "num_comments": 3, "visited": false, "num_reports": null, "distinguished": null}}], "after": null, "before": null}}



StumbleUpon:

http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http%3A%2F%2Fgoogle.co.in

It returns:

{"result":{"url":"http:\/\/www.google.co.in\/","in_index":true,"publicid":"1sbqjf","views":50621,"title":"Google","thumbnail":"http:\/\/cdn.stumble-upon.com\/mthumb\/849\/280849.jpg","thumbnail_b":"http:\/\/cdn.stumble-upon.com\/bthumb\/849\/280849.jpg","submit_link":"http:\/\/www.stumbleupon.com\/submit\/?url=http:\/\/www.google.co.in\/","badge_link":"http:\/\/www.stumbleupon.com\/badge\/?url=http:\/\/www.google.co.in\/","info_link":"http:\/\/www.stumbleupon.com\/url\/www.google.co.in\/"},"timestamp":1388407808,"success":true}





LinkedIn:


http://www.linkedin.com/countserv/count/share?url=http%3A%2F%2Fgoogle.co.in&format=json

It returns:

{"count":2586,"fCnt":"2,586","fCntPlusOne":"2,587","url":"http:\/\/google.co.in"}




Pinterest:


http://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=http%3A%2F%2Fgoogle.com

It returns:

receiveCount({"count": 10615, "url": "http://google.com"})


Tuesday, November 12, 2013

Flip multidimensional array in PHP

In this post you learn that how to flip a multidimensional array in php. Below function to accomplish the your task.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

function multi_array_flip($arrayIn, $DesiredKey, $DesiredKey2=false, $OrigKeyName=false) { 
$ArrayOut=array(); 
foreach ($arrayIn as $Key=>$Value) 
    { 
        // If there is an original key that need to be preserved as data in the new array then do that if requested ($OrigKeyName=true) 
        if ($OrigKeyName) $Value[$OrigKeyName]=$Key; 
        // Require a string value in the data part of the array that is keyed to $DesiredKey 
        if (!is_string($Value[$DesiredKey])) return false; 

        // If $DesiredKey2 was specified then assume a multidimensional array is desired and build it 
        if (is_string($DesiredKey2)) 
        { 
            // Require a string value in the data part of the array that is keyed to $DesiredKey2 
            if (!is_string($Value[$DesiredKey2])) return false; 

            // Build NEW multidimensional array 
            $ArrayOut[$Value[$DesiredKey]][$Value[$DesiredKey2]]=$Value; 
        } 

            // Build NEW single dimention array 
        else $ArrayOut[$Value[$DesiredKey]][]=$Value; 
    } 
return $ArrayOut; 
}//end multi_array_flip 

?>

Monday, November 4, 2013

Regular Expression in PHP


In this post you learn that how to write the Regular Expression. Regular expression is the most important part in form validations and it is widely used for search, replace and web crawling systems. If you want to write a selector engine (used to find elements in a DOM), it should be possible with Regular Expressions. 



Basics of regular expression in following three parts.

PART 1

^     Start of string
$     End of string
.      Any single character
+     One or more character
\      Escape Special characters
?    Zero or more characters



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

#Input exactly match with “abc” 
$A = /^abc$/;

#Input start with “abc”
$B = /^abc/;

#Input end with “abc”
$C = /abc$/;

#Input “abc” and one character allowed Eg. abcx
$D = /^abc.$/;

#Input  “abc” and more than one character allowed Eg. abcxy
$E = /^abc.+$/;

#Input exactly match with “abc.def”, cause (.) escaped
$F = /^abc\.def$/;

#Passes any characters followed or not by “abc” Eg. abcxyz12....
$G = /^abc.+?$/


?>




PART 2

[abc]               Should match any single of character
[^abc]             Should not match any single character
[a-zA-Z0-9]    Characters range lowercase a-z, uppercase A-Z and numbers
[a-z-._]            Match against character range lowercase a-z and ._- special chats 
(.*?)                 Capture everything enclosed with brackets 
(com|info)       Input should be “com” or “info”
{2}                    Exactly two characters
{2,3}                 Minimum 2 characters and Maximum 3 characters
{2,}                   More than 2 characters

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

#URL validation:

var URL = /^(http|https|ftp):\/\/(www+\.)?[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.([a-zA-Z]{2,3})\/?/;
URL.test(“http://4evertutorials.blogspot.com”); // pass
URL.test(“http://www.4evertutorials.blogspot.com”); // pass
URL.test(“https://4evertutorials.blogspot.com/”); // pass

?>

PART 3

\d is short form of [0-9]  Any numbers
\D is short form of [^0-9] Any non-digits
\w is short form of [a-zA-Z0-9_] Characters,numbers and underscore
\W is short form of [^a-zA-Z0-9_] Except any characters, numbers and underscore
\s White space character
\S Non white space character


Thursday, September 5, 2013

Set php.ini file Values Using .htaccess


If are using PHP as an apache module, PHP allows us to modify php.ini using Apache Configuration. This can be done using the following directives:

php_value name value 
Sets the value of the specified directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. To clear a previously set value use none as the value.

php_flag name on|off
Used to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives.

php_admin_value name value
Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or ini_set(). 

php_admin_flag name on|off 
Used to set a boolean configuration directive. This can not be used in .htaccess files. Any directive type set with php_admin_flag can not be overridden by .htaccess or ini_set().

In .htaccess File put following code

#htacces code format
php_value setting_name setting_value

#example
php_value  upload_max_filesize  7M


Of course you could simply place these in the .htaccess
It's actually very easy

Check domain availability using cURL php

Here is a simple function for checking domain availability using cURL in php.


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

function domain_checker($domain) { 

$data = 'http://'.$domain; 

// Create a curl handle to a non-existing location 
$ch = curl_init($data); 

// Execute 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_exec($ch); 

// Check if any error occured 
if(curl_errno($ch)) 
{ 
    return 'The domain is available!'; 
} else { 
    return 'The domain is not available'; 
} 

// Close handle 
curl_close($ch); 
} 


?>



// Usage: 

<?php
domain_check("blogger.com");

?> 

WordPress Functions for functions.php File

Here are some of common functions in WordPress theme’s functions.php file that I would suggest you include in your functions.php file



Get Ping/Trackback Count

Here is an interesting one I used recently. This function returns the number of pings/trackbacks for a post. This can be useful if you only want to show a certain section if there are any pings/trackbacks.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

function pings_count($post_id) {
    global $wpdb;
    $count = "SELECT COUNT(*) FROM $wpdb->comments WHERE (comment_type = 'pingback' OR comment_type = 'trackback') AND comment_post_ID = '$post_id'";
    return $wpdb->get_var($count);
}


?>


Plain Text Feedburner Subscriber Count

Here is the classic: get your feedburner subscriber count in plain text. Note most of these functions make use of cURL and this one requires PHP v5+ (so you can use SimpleXMLElement).

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

function get_subscriber_count() {
        $id = "YourFeedId";
    $url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=". $id;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    $data = curl_exec($ch);
    curl_close($ch);
    $xml = new SimpleXMLElement($data);
    return $xml->feed->entry['circulation'];
}


?>

Get TinyURL

This one can be useful if you want to generate a short URL of your post for people to share.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

function get_tiny_url($url) {
    if (function_exists('curl_init')) {
        $url = 'http://tinyurl.com/api-create.php?url=' . $url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        $tinyurl = curl_exec($ch);
        curl_close($ch);
        return $tinyurl;
    } else {
        //cURL disabled on server; Return long URL instead.
        return $url;
    }
}


?>

Month Number to Month Name PHP


This is a simple code for you to convert a month number to a month name in PHP 

Example:


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

$monthNum = 11;
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
echo $monthName; //output: November




?>

Saturday, August 24, 2013

Calendar Script PHP

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



$day = date('j'); //what day is it today
$month = date('n'); //what month are we in?
$year = date('Y'); //what year are we in?

//get the first first day of the month
$first_day_of_month = date('w',mktime(1,1,1,$month,1,$year));

$days_in_month = date('t'); //how many days in this month

print "SU\tMO\tTU\tWE\tTH\tFR\tSA
"; //print the weekday headers //count ahead to the weekday of the first day of the month for ($spacer = 0; $spacer < $first_day_of_month; $spacer++) { print "  \t"; } for ($x = 1; $x <= $days_in_month; $x++) { //begin our main loop //if we have gone past the end of the week, go to the next line if ($spacer >= 7) { print "
"; $spacer = 0; } //if the length of the current day is one, put a "0" in front of it if (strlen($x) == 1) { $x = "0$x"; } if ($x == $day) { //is this day the current day print "$x\t"; //if so put an indicator } else { print "$x\t"; //otherwise just print it } $spacer++; //increment our spacer } ?>

Square Roots in PHP

Doing square roots in PHP is really simple, all you need to do is to call the function sqrt().  Lets see some code.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

//Set number you would like to take square root
$int = 9;
//Take square root
$sqrt = sqrt($int);
//Display result
echo $sqrt;


?>
As you can see, simple to do. Now lets do it in a more mathematical way using the PHP function pow(), which is the power function. pow() has two inputs, pow($base, $n). $base is the base number you will raise to the $n power. Now usually, we would use this function to calculate powers like 22 (which is 4). However, if you know your math, we can raise numbers to the power of fractions, which is the same as taking the root of numbers. Not just the square root either, we can use this to find the cube root, fourth root, any root you would like to find. Now lets see some code for finding the cube root of 729.

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

//Set base number and the exponent
$base = 729;
$exp = 1/3;
//Take root
$sqrt = pow($base, $exp);
//Display result
echo $sqrt;


?>
The $base is the number we will be taking the power of $exp of. This way we can use the pow() function to not only find powers of numbers but the roots as well.



Other notes:

All PHP code needs “<?php” before and “?>” after the code to run.

The double slash “//” is a comment that PHP will ignore. For bigger comments, use “/* really big comment */”.

The “$int” is a variable. Use the dollar sign in front of a meaningful variable name to create variables in PHP.

sqrt() is the function that calculates the square root of a float number.

pow($float, $exp) is the function calculates a number $float to the power of $exp.

The “echo” function prints whatever values you pass to it in the HTML of the webpage.

Saturday, August 17, 2013

Convert bytes to B, KB, MB, GB, TB, PB, EB, ZB, YB

Simple PHP function that formats the bytes to the desired form. Possible unit options are:

Byte (B)
Kilobyte (KB)
Megabyte (MB)
Gigabyte (GB)
Terabyte (TB)
Petabyte (PB)
Exabyte (EB)
Zettabyte (ZB)
Yottabyte (YB)

Function takes three parameter: (bytes mandatory, unit optional, decimals optional):



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

function byteFormat($bytes, $unit = "", $decimals = 2) {
 $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 
   'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
 
 $value = 0;
 if ($bytes > 0) {
  // Generate automatic prefix by bytes 
  // If wrong prefix given
  if (!array_key_exists($unit, $units)) {
   $pow = floor(log($bytes)/log(1024));
   $unit = array_search($pow, $units);
  }
 
  // Calculate byte value by prefix
  $value = ($bytes/pow(1024,floor($units[$unit])));
 }
 
 // If decimals is not numeric or decimals is less than 0 
 // then set default value
 if (!is_numeric($decimals) || $decimals < 0) {
  $decimals = 2;
 }
 
 // Format output
 return sprintf('%.' . $decimals . 'f '.$unit, $value);
  }


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

echo byteFormat(4096, "B") ."\n";
echo byteFormat(8, "B", 2) . "\n";
echo byteFormat(1, "KB", 5) . "\n";
echo byteFormat(1073741824, "B", 0) . "\n";
echo byteFormat(1073741824, "KB", 0) . "\n";
echo byteFormat(1073741824, "MB") . "\n";
echo byteFormat(1073741824) . "\n";
echo byteFormat(1073741824, "TB", 10) . "\n";
echo byteFormat(1099511627776, "PB", 6) . "\n";



?>

PHP Memory Usage


This is a simple example of a class, which can be used to collect the PHP script memory usage information and to print all information.


PHP Memory Usage - Class

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

 class MemoryUsageInformation {
    private $real_usage;
    private $statistics = array();
 
    // Memory Usage Information constructor
    public function __construct($real_usage = false) {
      $this->real_usage = $real_usage;
    }
 
    // Returns current memory usage with or without styling
    public function getCurrentMemoryUsage($with_style = true) {
      $mem = memory_get_usage($this->real_usage);
      return ($with_style) ? $this->byteFormat($mem) : $mem;
    }
 
    // Returns peak of memory usage
    public function getPeakMemoryUsage($with_style = true) {
      $mem = memory_get_peak_usage($this->real_usage);
      return ($with_style) ? $this->byteFormat($mem) : $mem;
    }
 
    // Set memory usage with info
    public function setMemoryUsage($info = '') {
      $this->statistics[] = array('time' => time(), 
                                  'info' => $info, 
                                  'memory_usage' => $this->getCurrentMemoryUsage());
    }
 
    // Print all memory usage info and memory limit and 
    public function printMemoryUsageInformation() {
      foreach ($this->statistics as $satistic) {
        echo  "Time: " . $satistic['time'] . 
              " | Memory Usage: " . $satistic['memory_usage'] . 
              " | Info: " . $satistic['info'];
        echo "\n";
      }
      echo "\n\n";
      echo "Peak of memory usage: " . $this->getPeakMemoryUsage();
      echo "\n\n";
    }
 
    // Set start with default info or some custom info
    public function setStart($info = 'Initial Memory Usage') {
      $this->setMemoryUsage($info);
    }
 
    // Set end with default info or some custom info
    public function setEnd($info = 'Memory Usage at the End') {
      $this->setMemoryUsage($info);
    }
 
    // Byte formatting
    private function byteFormat($bytes, $unit = "", $decimals = 2) {
     $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 
       'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
 
     $value = 0;
     if ($bytes > 0) {
      // Generate automatic prefix by bytes 
      // If wrong prefix given
      if (!array_key_exists($unit, $units)) {
       $pow = floor(log($bytes)/log(1024));
       $unit = array_search($pow, $units);
      }
 
      // Calculate byte value by prefix
      $value = ($bytes/pow(1024,floor($units[$unit])));
     }
 
     // If decimals is not numeric or decimals is less than 0 
     // then set default value
     if (!is_numeric($decimals) || $decimals < 0) {
      $decimals = 2;
     }
 
     // Format output
     return sprintf('%.' . $decimals . 'f '.$unit, $value);
    }
  }



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

 // Create new MemoryUsageInformation class
  $m = new MemoryUsageInformation(true);
 
  // Set start
  $m->setStart();
 
  // Create example array
  $a = array();
 
  // Set memory usage before loop
  $m->setMemoryUsage('Before Loop');
 
  // Fill array with
  for($i = 0; $i < 100000; $i++) {
    $a[$i] = uniqid();
  }
 
  // Set memory usage after loop
  $m->setMemoryUsage('After Loop');
 
  // Unset array
  unset($a);
 
  // Set memory usage after unset
  $m->setMemoryUsage('After Unset');
 
  // Set end
  $m->setEnd();
 
  // Print memory usage statistics
  $m->printMemoryUsageInformation();


?>
CHECK Output of PHP Memory class

Objects to Array php


Every PHP coders have come accross Arrays and stdClass Objects (belongs to PHP Predefined Classes). Sometimes it’s very useful convert Objects to Arrays and Arrays to Objects. This is easy if arrays and objects are one-dimensional, but might be little tricky if using multidimensional arrays and objects.



This post defines two simple function to convert
:multidimensional Objects to Arrays
:multidimensional Arrays to Objects


Function to Convert stdClass Objects to Multidimensional Arrays
Objects to Array php


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

 
 function objectToArray($d) {
  if (is_object($d)) {
   // Gets the properties of the given object
   // with get_object_vars function
   $d = get_object_vars($d);
  }
 
  if (is_array($d)) {
   /*
   * Return array converted to object
   * Using __FUNCTION__ (Magic constant)
   * for recursive call
   */
   return array_map(__FUNCTION__, $d);
  }
  else {
   // Return array
   return $d;
  }
 }
 
?>




Function to Convert Multidimensional Arrays to stdClass Objects
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

 
 function arrayToObject($d) {
  if (is_array($d)) {
   /*
   * Return array converted to object
   * Using __FUNCTION__ (Magic constant)
   * for recursive call
   */
   return (object) array_map(__FUNCTION__, $d);
  }
  else {
   // Return object
   return $d;
  }
 }

?>

Function usage

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


// Create new stdClass Object
 $init = new stdClass;
 
 // Add some test data
 $init->foo = "Test data";
 $init->bar = new stdClass;
 $init->bar->baaz = "Testing";
 $init->bar->fooz = new stdClass;
 $init->bar->fooz->baz = "Testing again";
 $init->foox = "Just test";
 
 // Convert array to object and then object back to array
 $array = objectToArray($init);
 $object = arrayToObject($array);
 
 // Print objects and array
 print_r($init);
 echo "\n";
 print_r($array);
 echo "\n";
 print_r($object);

?>

Saturday, July 20, 2013

Two way encryption in PHP Mcrypt

This class provides the functionality to encrypt and decrypt a text string. The class makes use of the PHP mcrypt extension which provides the ability to create two way encryption, or decoding of text messages.


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

error_reporting(E_ALL);

class runCrypt 
{
    /**
    *
    * This is called when we wish to set a variable
    *
    * @access    public
    * @param    string    $name
    * @param    string    $value
    *
    */
    public function __set( $name, $value )
    {
        switch( $name)
        {
            case 'key':
            case 'ivs':
            case 'iv':
            $this->$name = $value;
            break;

            default:
            throw new Exception( "$name cannot be set" );
        }
    }

    /**
    *
    * Gettor - This is called when an non existant variable is called
    *
    * @access    public
    * @param    string    $name
    *
    */
    public function __get( $name )
    {
        switch( $name )
        {
            case 'key':
            return 'keee';

            case 'ivs':
            return mcrypt_get_iv_size( MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB );

            case 'iv':
            return mcrypt_create_iv( $this->ivs );

            default:
            throw new Exception( "$name cannot be called" );
        }
    }

    /**
    *
    * Encrypt a string
    *
    * @access    public
    * @param    string    $text
    * @return    string    The encrypted string
    *
    */
    public function encrypt( $text )
    {
        // add end of text delimiter
        $data = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv );
        return base64_encode( $data );
    }
 
    /**
    *
    * Decrypt a string
    *
    * @access    public
    * @param    string    $text
    * @return    string    The decrypted string
    *
    */
    public function decrypt( $text )
    {
        $text = base64_decode( $text );
        return mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv );
    }
} // end of class

?>



Example Usage


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


// a new runCrypt instance
$crypt = new runCrypt;

// encrypt the string
$encoded = $crypt->encrypt( 'my message');
echo $encoded."\n";

// decrypt the string
echo $crypt->decrypt( $encoded ) . "\n";

?>

Round up to multiple in php


Here is a simple function that will round a number up to a given multiple. may this help you

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

function roundUpToMultiple( $number, $multiple)
{
    return ceil( $number/$multiple ) * $multiple;
} 


?>


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

echo roundUpToMultiple( 12, 7 );

?>

Thursday, June 27, 2013

PHP date validation

Date Validation yyyy-mm-dd
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


$date = '2013-06-27';

function isValidDate($date)
{
 if(preg_match("/^(\d{4})-(\d{2})-(\d{2})$/", $date, $matches))
 {
  if(checkdate($matches[2], $matches[3], $matches[1]))
  {
   return true;
  }
 }
}

if(isValidDate($date)){
 echo 'valid date';
} else
{
 echo 'invalid date';
}

?>










Date Validation dd-mm-yyyy
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$date = '27-06-2013';

function isValidDate($date)
{
 if(preg_match("/^(\d{2})-(\d{2})-(\d{4})$/", $date, $matches))
 {

  if(checkdate($matches[2], $matches[1], $matches[3]))
  {
   return true;
  }
 }
}

if(isValidDate($date))
{
 echo 'valid date';
} else
{
 echo 'invalid date';
}


?>








Date Validation mm-dd-yyyy

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


$date = '06-27-2013';

function isValidDate($date)
{
 if(preg_match("/^(\d{2})-(\d{2})-(\d{4})$/", $date, $matches))
{
  if(checkdate($matches[1], $matches[2], $matches[3]))
  {
   return true;
  }
 }
}

if(isValidDate($date)){
 echo 'valid date';
} else
{
 echo 'invalid date';
}

?>









Date Validation dd-mmm-yyyy
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


$date = '27-Jun-2013';

function isValidDate($date)
{
 if(preg_match("/^(\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{4})$/", $date, $matches)) 
 {
  $month = array('Jan'=>'01'
         ,'Feb'=>'02'
         ,'Mar'=>'03'
         ,'Apr'=>'04'
         ,'May'=>'05'
         ,'Jun'=>'06'
         ,'Jul'=>'07'
         ,'Aug'=>'08'
         ,'Sep'=>'09'
         ,'Oct'=>'10'
         ,'Nov'=>'11'
         ,'Dec'=>'12'
        );

  if(checkdate($month[$matches[2]],$matches[1],$matches[3]))
  {
   return true;
  }
 }
}

if(isValidDate($date))
{
 echo 'valid date';
} else
{
 echo 'invalid date';
}

?>

PHP function to calculate percentage

This post shows you how to calculate a percentage using a division and multiplying its result by 100. This is the simpliest way to calculate a percentage in PHP
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


function percentage($x, $y, $precision) 
{

        // $precision define digit after the decimal point

 $result = round( ($x / $y) * 100, $precision );
 
 return $result;
}


echo percentage(2, 3, 2); // This will print 66.67

echo percentage(2, 3, 0); // This will print 67

?>

Friday, June 21, 2013

Replace characters with icons emoticons php

Learn to use PHP to change character sequences into emoticons or icons by using the str_replace function. You will want to alter the string data as it comes out of the MySQL database for display, not when the data is being inserted into the database.

# USAGE EXAMPLE 

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


$db_string = "Show me some <3 right now. It is raining today [umbr], that gives me peace [peace].";

echo $db_string;
echo "
"; $chars = array("<3", "[peace]", "[umbr]"); $icons = array("❤", "☮", "☂"); $new_str = str_replace($chars,$icons,$db_string); echo $new_str; ?>

Get Favicon From other Website Using PHP


Learn to get and render favicon.ico files dynamically from other servers in your PHP scripts. You can look for files and also process the DOM structure of external pages on the web. I recommend saving the favicon image file to your server converting it to a JPG or PNG file if it will be a frequently viewed image.

# USAGE EXAMPLE 

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



function getfavicon($url){
    $favicon = '';
    $html = file_get_contents($url);
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $links = $dom->getElementsByTagName('link');
    for ($i = 0; $i < $links->length; $i++){
        $link = $links->item($i);
        if($link->getAttribute('rel') == 'icon'){
            $favicon = $link->getAttribute('href');
 }
    }
    return $favicon;
}


$website = "http://4evertutorials.blogspot.com/"; # replace with your url
$favicon = getfavicon($website);
echo $favicon;

?>

Render XML file for Flash Photo Gallery with php

Learn how to render dynamic XML files for Flash(or any other) Photo Gallery applications using PHP loops to show the most current data at all times.


This script would be named something like galleryXML.php

This file reads a directory on its own to render the XML file, all you have to do it point it at a folder of images no matter how many are in it, and it will produce nice clean XML nodes for all of the images.




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


# set the content type to xml
header("Content-Type: text/xml");

# Initialize the xmlOutput variable
$xmlBody = '';

# Specify Directory where images are 
$dir = "images/gallery/"; 

# Start XMLBody output
$xmlBody .= ""; 

# open specified directory using opendir() the function
$dirHandle = opendir($dir); 

# Create incremental counter variable
$i = 0;
while ($file = readdir($dirHandle)) 
{ 
      
      # if file is not a folder and if file name contains the string .jpg  

      if(!is_dir($file) && strpos($file, '.jpg'))
      {
        # increment $i by one each pass in the loop
         $i++; 
         $xmlBody .= '

    ' . $i . '
    ' . $dir . '' . $file . '
';
      } # close the if statement

} # End while loop


# close the open directory
closedir($dirHandle); 

$xmlBody .= "";

# output the gallery data as XML file for Flash Photo Gallery
echo $xmlBody; 


?>

Cookies and Session in PHP

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

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

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

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

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

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

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

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

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

Wednesday, May 22, 2013

Google translator code php

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




googletranslate.php

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

class translate { 


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




    function __construct($from , $to){ 

        $this->debug = 0; 


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


        if(!$from){ 

            $this->translate_from = "en"; 

        }else{ 

            $this->translate_from = $from; 

        } 
         
        if(!$to){ 

            $this->translate_into = "it"; 


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

        } 

    } 


    function TranslateUrl($word){ 


        if(!$word){ 

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


        $word = urlencode($word); 

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


        return $url; 

    } 

    function get($word){ 


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

        $dom->loadHTML($html); 

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

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

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

                return ($var); 

            } 
             
                   
        } 

    } 

   

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

                return file_get_contents($Url); 

            }else{ 

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

            } 

        } 
      
        
        $ch = curl_init(); 

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


} 



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

require_once("googletranslate.php"); 


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

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



?>

Supported languages

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

Saturday, May 18, 2013

Compute difference between two dates in php

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


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

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

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

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

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


?>

Wednesday, May 15, 2013

get the geographic location of a IP address

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

geoIPLocation.php

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

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

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

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

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


?>





usage of script

example 1 : Using your local IP 


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

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

?>





example 2 : Find the proper IP

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

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


?>


Monday, May 13, 2013

SEO Friendly URL function in PHP

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


function SEOURL($_string)
{

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

}


// usage

SEOURL($simple_url);


?>

Wednesday, May 1, 2013

Redirect page after certain time PHP

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

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

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

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

}


?>

Secure login with MySQLi Extension php

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

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


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


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

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

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

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

               // fetch values 

                    $stmt->fetch();

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

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

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

                    
                    } else { 

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

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

               
}

?>

Saturday, April 20, 2013

Dynamic selection of year list in php

To avoid the need to write up to many lines in your HTML forms. PHP for loop helps us for that. Use below simple code for that
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

  echo "";


?>

Friday, April 19, 2013

Generate a CSV file from MySQL records


This class can generate a CSV file from MySQL query results.

It can connect to a given MySQL database and execute a SQL query.

The class can generate a CSV file from the query results.

The CSV file may have headers generated from the query result column names or use custom names.

The generated CSV file may be save to a file, served for download or displayed on a Web page.

class.select2csv.php


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

/** 
 * select2csv 
 *  
 * @package   MySQL Select CSV Dump 
 * @author    Mark Berube 
 * @license   Distributed under GNU/GPL 
 * @version   0.1 
 * @access    public 
 */  
class select2csv{ 
    var $result; 
    var $result_col_headers = array(); 
    var $qry = false; 
    var $conn_to_db; 
    var $conn_array; 
    var $error = false; 
    var $debug = false; 
    var $use_first_line_header_row = true; 
    var $csv; 
    var $delim; 
    var $output_file; 
    var $delivery;// 'local_file', 'passthru', 'print' 
      
    /** 
     * select2csv::__construct() 
     * @desc object constructor 
     * @param array $conn_array 
     * @param bool $conn_to_db 
     * @return void 
     */  
    function __construct($conn_array=false,$conn_to_db=false){ 
        $this->conn_to_db = $conn_to_db; 
        $this->conn_array = $conn_array; 
    } 

    /** 
     * select2csv::set_qry() 
     * @desc Sets the MySQL qry to be executed 
     * @param string $qry 
     * @return void 
     */ 
    function set_qry($qry){ 
        $this->qry = $qry; 
    } 
     
    /** 
     * select2csv::set_delim() 
     * @desc Sets the Delimiter for the CSV output 
     * @param string $delim 
     * @return void 
     */ 
    function set_delim($delim){ 
        $this->delim = $delim; 
    } 

    /** 
     * select2csv::set_custom_headers() 
     * @desc Sets the Delimiter for the CSV output 
     * @param array $headers_arr 
     * @return void 
     */ 
    function set_custom_headers($headers_arr){ 
        $this->result_col_headers = $headers_arr; 
    } 

    /** 
     * select2csv::first_line_headers() 
     * @desc Disables creating the first line headers row 
     * @return void 
     */ 
    function remove_header_line(){ 
        $this->use_first_line_header_row = false; 
    } 
     
    /** 
     * select2csv::debug() 
     * @desc If function is called with no args it will echo errors if something is missing. Default is off 
     * @param bool $val 
     * @return void 
     */ 
    function debug($val=true){ 
        $this->debug = $val; 
    } 
     
    /** 
     * select2csv::execute() 
     * @desc execute query object after all parameters set 
     * @param string $action 
     * @return array if action is select else true or false 
     */ 
    function execute($action='s'){  
        if($this->conn_to_db){ 
            $conn_array = $this->conn_array; 
            $conn = mysql_connect($conn_array['host'], $conn_array['user'], $conn_array['pw'])or die("Unable to connect to MYSQL because: ".mysql_error());
            $db_select = mysql_select_db($conn_array['db'],$conn) or die("Could not select '".$conn_array['db']."' database because: ".mysql_error()); 
        } 
         
        //select will return array, either empty or populated 
        $this->result_val_type = 'array'; 
        $this->result = $this->db_qry_get_rows(); 
            if(empty($this->result_col_headers)){ 
                $this->result_col_headers = $this->db_qry_get_headers(); 
            } 
        $this->build_csv(); 
             
        if($this->conn_to_db){ 
            mysql_close($conn); 
        } 
        if($this->debug){ 
            if($this->error){ 
                echo $this->error; 
                return false; 
            } 
        } 
    } 

    function build_csv(){ 
        //$result = $this->result; 
        $NumFields = count($this->result_col_headers); 
        $header_row = ""; 
        $data_rows = ""; 

        if($this->use_first_line_header_row){ 
            /////////////////////// 
            //build the headers from array keys 
            /////////////////////// 
            $col = 1; 
                foreach ($this->result_col_headers as $header){ 
                    $header_row .= $header; 
                    $header_row .= ($col < $NumFields) ? $this->delim : "\r\n"; 
                    $col++; 
                } 
        } 

        /////////////////////// 
        //Now Get the data rows 
        /////////////////////// 
        foreach($this->result as $row){ 
        //print_r($row); 
            $col = 1;//reset 
            foreach ($row as $data){ 
                $data_rows .= trim($data); 
                $data_rows .= ($col < $NumFields) ? $this->delim : "\r\n"; 
                $col++; 
            } 

        } 

        $this->csv = $header_row . $data_rows; 
        unset($header_row,$data_rows); 
    } 
     
    /** 
     * select2csv::db_qry_get_rows() 
     * @desc Assembles 'select' qry results to a 2-dim assoc array. This function is called with the 's' action 
     * @return array if executed without error else false 
     */ 
    function db_qry_get_rows(){ 
        $rows = array(); 
                if($this->qry == false){ 
                $this->error = "You must set a query (using set_qry()) before executing a 'select'"; 
                return false; 
                } 
        $res = mysql_query($this->qry); 
            if($res){ 
                $cnt = 0; 
                    while($row = mysql_fetch_assoc($res)){ 
                        foreach ($row as $key => $val){ 
                            $rows[$cnt][$key] = $val; 
                        } 
                    $cnt++; 
                    } 
                mysql_free_result($res); 
            } 
        return $rows; 
    } 

    /** 
     * select2csv::db_qry_get_headers() 
     * @desc Grabs this first record result and extracts the array keys for use as column headers...just for ease of access 
     * @return array 
     */ 
    function db_qry_get_headers(){ 
        $headers = array(); 
        if(is_array($this->result[0])){ 
            if(empty($this->result[0])){ 
                return $headers; 
            }else{ 
                foreach ($this->result[0] as $key => $value) { 
                    $headers[] = $key; 
                } 
            } 
            return $headers; 
        } 
        return false; 
    } 
     
    /** 
     * select2csv::output() 
     * @desc Delivers csv content in one of three ways: creation of local file, print to the browser window, or passthru for download 
     * @param string $delivery 
     * @param string $fname 
     * @param string $local_path                
     * @return void 
     */ 
    function output($delivery, $fname='', $local_path='.'){ 
        switch($delivery){ 
            case 'local_file': 
                  file_put_contents($local_path.'/'.$fname,$this->csv); 
            break; 
            case 'passthru': 
                  $tmp = 'Select2CSV_Dump.csv'; 
                  file_put_contents($tmp,$this->csv); 
                  $file_size = filesize($tmp); 
                  if ($fp = fopen($tmp, 'rb')) { 
                      Header('Content-Disposition: attachment; filename="'.$fname.'"'); 
                      Header('Content-Length: '.$file_size); 
                      fpassthru($fp); 
                  } else { 
                      echo "cannot find tmp file: check that the script has write permission to the containing folder"; 
                  } 
            break; 
            case 'print': 
                  echo '
'."\n".$this->csv.'
'; break; } } } ////////////////// // Example usage ////////////////// ini_set('display_errors','On'); $db_creds = array( 'db' => "db_name", 'user' => "myusername", 'pw' => "mypassword", 'host' => "localhost" ); $csv = new select2csv($db_creds,true); $csv->set_qry("SELECT fname,lname,email,role FROM users"); //$csv->remove_header_line();//disables using a column header row at all $csv->set_custom_headers(array('First','Last','EMail','Role'));//default is to use the field names from query as column headers $csv->set_delim('|'); $csv->execute(); /////////////////// // 3 methods of delivery show below /////////////////// //$csv->output('passthru','csvtest.csv'); $csv->output('print'); //$csv->output('local_file','csvtest.csv','./tmp'); ?>

Forex Class for PHP 5


This class can convert money amounts between currencies using iGoogle calculator API.

It can send a HTTP request to the iGoogle calculator API to convert a given money amount between to given currencies.

The class parses the response and returns an array with the original and converted values and currency symbols, the current time and the API URL.





class.forex.php




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


/** 
 *  Foreign Exchange Class | PHP 5 
 *  Build 2013.01.14  
 * 
 *    Copyright (c) 2013 
 *    Jonathan Discipulo  
 *    http://jondiscipulo.com/ 
 *  
 *  This library is free software; you can redistribute it and/or 
 *  modify it under the terms of the GNU Lesser General Public 
 *  License as published by the Free Software Foundation; either 
 *  version 2.1 of the License, or (at your option) any later version. 
 *  
 *  This library is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
 *  Lesser General Public License for more details. 
 *  
 *  You should have received a copy of the GNU Lesser General Public 
 *  License along with this library; if not, write to the Free Software 
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA 
 *  
 *  http://www.gnu.org/copyleft/lesser.html 
 *  
**/ 

// }} 
// {{ Forex 
class Forex { 

    private $amount, $from, $to; 
    protected $api, $query; 
    public $result; 
     
    // }} 
    // {{ Constructor 
    public function __construct() { 
         
        $this->api = 'http://www.google.com/ig/calculator'; 
         
    } 

    // }} 
    // {{ Convert 
    public function convert( $amount, $from='USD', $to='USD' ) { 
     
        $this->amount = $amount; 
        $this->from = $from; 
        $this->to = $to; 
        $this->query = '?hl=en&q=' . $this->amount . $this->from . '%3D%3F' . $this->to; 
        $content = file_get_contents( $this->api . $this->query ); 
        $this->result = $this->parse( $content ); 
         
    } 

    // }} 
    // {{ Get Result 
    public function get( $string='converted' ) { 
         
        $array = $this->result; 
        return $array[$string]; 
         
    } 

    // }} 
    // {{ Get Result Array 
    public function getResultArray() { 
         
        return $this->result; 
         
    } 
     
    // }} 
    // {{ Parse 
    private function parse( $string ) { 
        if (!empty($string)) { 
            $data = explode( '"', $string ); 
            $object = explode( ' ', $data[3]); 
            $result = array( 
                'from' => $this->from, 
                'to' => $this->to, 
                'amount' => $this->amount, 
                'converted' => $object[0], 
                'stamp' => gmdate('Y/m/d H:i:s') . ' UTC', 
                'api' => $this->api 
            ); 
        } else { 
            $result = null; 
        } 
        return $result; 
    } 

    // }} 
    // {{ Magic Method: Sleep 
    public function __sleep() { 
        // reserved for codes to run when in sleep 
    } 
     
    // }} 
    // {{ Magic Method: Wake Up 
    public function __wakeup() { 
        // reserved for codes to run when after sleep 
    } 

    // }} 
    // {{ Destructor 
    public function __destruct() { 
         
        // reserved for codes to run when this object is destructed 
        if (isset($this->amount)) unset($this->amount); 
        if (isset($this->from)) unset($this->from); 
        if (isset($this->to)) unset($this->to); 
        if (isset($this->result)) unset($this->result); 
         
    } 

} 

?>








sample.php



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

require_once('class.forex.php'); 

$forex = new Forex(); 
$forex->convert( '1', 'USD', 'PHP' ); 

echo $forex->get('from') . ' ' . $forex->get('amount') . ' is equal to ' . $forex->get('to') . ' ' . $forex->get('converted') . ' as of ' . $forex->get('stamp') . '
'; echo ""; print_r( $forex->getResultArray() ); echo ""; ?>

Code Treasury

Ads

Contact Us

Name

Email *

Message *

Ads

Powered by Blogger.
 

© 2014 4everTutorials. All rights resevered.

Back To Top