Category Archives: PHP Class

Database Class

<?php
class Database{
	
		protected $host;
		protected $user;
		protected $pass;
		protected $database;
		protected $port;
		
		function Database($host, $user, $pass, $database, $port){
			$this->host = $host;
			$this->user = $user;
			$this->pass = $pass;
			$this->database = $database;
			$this->port = $port;
		}		
		
		/** Connection Funtion **/
		function conn(){
			$this->conn = mysqli_connect($this->host. ":".$this->port, $this->user, $this->pass)or die("Invalid database");
			mysqli_select_db($this->conn, $this->database) or die("Can not connect database");
			mysqli_query($this->conn, "SET NAMES 'utf8'");
			date_default_timezone_set('Hongkong');
			return "Connect database succeed";
		}
	
		function close() {
			mysqli_close($this->conn);
		}
		
		function error() {
			return mysqli_error($this->conn);
		}
		
		/** Execution Query Function **/ 
		function query($query) {
			$this->query = $query;
			return $this->result = mysqli_query($this->conn, $this->query) or die(error());
		}
		
		function insert_id() {
			return mysqli_insert_id($this->conn);
		}
		
		function num_rows() {
			return mysqli_num_rows($this->result);
		}
		
		function free_result() {
			mysqli_free_result($this->result) ;
		}
		
		function fetch_array($mode = MYSQLI_ASSOC) {
			return mysqli_fetch_array($this->result, $mode);
		}
		
		function affected_rows() {
			return mysqli_affected_rows($this->conn);
		}
		
		/** Function **/		
		function escape_string($string) {
			if (get_magic_quotes_gpc()) {
				$string = stripslashes($string);
			}
			if (!is_numeric($string)) {
				$string = mysqli_real_escape_string($this->conn, $string);
			}
			return trim($string);
		}

		/*
			function insert_escape_string($string) {
				return $this->real_escape_string($string, true); 
			}
		*/
	
		function uniqid($length = 3){
			$array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
			"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
			0,1,2,3,5,6,7,8,9);

			$key = "";
			$size = sizeof($array)-1;
			for($i = $length; $i > 0;$i--) {
				$n = rand(0, $size);
				$key.= $array[$n];
			}
			
			$uniqid = uniqid();
			$uniqid .= md5($uniqid.$key);
			return $uniqid;
		}	
	}
?>

Tutorial

$host 	  = "127.0.0.1";
$user 	  = "root";
$pass	  = "";
$db 	  = "test";
$port	  = "3306";
$lang     = "zh-tw";
		
$database = new Database($host, $user, $pass, $db, $port);	
$database->conn();

$sql = "SELECT * FROM test";
$result = $database->query($sql);
$rows = $database->fetch_array($result);
$database->free_result();

Pagination Class

Pagination.cls.php

class Pagination {
			function basic($url = "", $page, $limit, $total, $parameter=array(), $value=array()){
			
			$previous = "<i class='fa fa-chevron-left'></i>";
			$next = "<i class='fa fa-chevron-right'></i></a>";
			$stages = 3;
			$url_query = "";
			$this->total_pages = $total;
			
			if( count($parameter) != 0){
				for ($x = 0; $x < count($parameter); $x++) {
					$url_query .= "&".$parameter[$x]."=".$value[$x];
				} 
			}
			
			// Initial page num setup
			if ($page == 0){$page = 1;}
			$previousPage = $page - 1;	
			$nextPage = $page + 1;							
			$lastPage = ceil($this->total_pages/$limit);		
			$lastPagem = $lastPage - 1;					

			$paginate = '';
			if($lastPage > 1)
			{		
				$paginate .= "<ul class='pagination pagination-small m-t-none m-b-none'>";
				// Previous
				if ($page > 1){
					$paginate.= "<li><a href='".$url."?page=$previousPage$url_query'>$previous</a></li>";
				}else{
				    $paginate.= "<li><a style='color:#ccc;background-color: #fafafa;'>$previous</a></li>";	
				}
			
				// Pages	
				if ($lastPage < 7 + ($stages * 2))	// Not enough pages to breaking it up
				{	
					for ($counter = 1; $counter <= $lastPage; $counter++)
					{
						if ($counter == $page){
							  $paginate.= "<li><a style='color:#ccc;background-color: #fafafa;'>$counter</a></li>";
						}else{
							$paginate.= "<li><a href='".$url."?page=$counter$url_query'>$counter</a></li>";
						}					
					}
				}
				elseif($lastPage > 5 + ($stages * 2))	// Enough pages to hide a few?
				{
					// Beginning only hide later pages
					if($page < 1 + ($stages * 2))		
					{
						for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
						{
							if ($counter == $page){
							   $paginate.= "<li><a style='color:#ccc;background-color: #fafafa;'>$counter</a></li>";
							}else{
								$paginate.= "<li><a href='".$url."?page=$counter$url_query'>$counter</a></li>";}					
						}
						$paginate.= "...";
					
						$paginate.= "<li><a href='".$url."?page=$lastPagem$url_query'>$lastPagem</a></li>";
						$paginate.= "<li><a href='".$url."?page=$lastPage$url_query'>$lastPage</a></li>";		
					}
					// Middle hide some front and some back
					elseif($lastPage - ($stages * 2) > $page && $page > ($stages * 2))
					{
						$paginate.= "<li><a href='".$url."?page=1$url_query'>1</a></li>";
						$paginate.= "<li><a href='".$url."?page=2$url_query'>2</a></li>";
						$paginate.= "...";
						for ($counter = $page - $stages; $counter <= $page + $stages; $counter++)
						{
							if ($counter == $page){
								 $paginate.= "<li><a style='color:#ccc;background-color: #fafafa;'>$counter</a></li>";
							}else{
								$paginate.= "<li><a href='".$url."?page=$counter$url_query'>$counter</a></li>";}					
						}
						$paginate.= "...";
						$paginate.= "<li><a href='".$url."?page=$lastPagem$url_query'>$lastPagem</a></li>";
						$paginate.= "<li><a href='".$url."?page=$lastPage$url_query'>$lastPage</a></li>";		
					}
					// End only hide early pages
					else{
						$paginate.= "<li><a href='".$url."?page=1$url_query'>1</a></li>";
						$paginate.= "<li><a href='".$url."?page=2$url_query'>2</a></li>";
						$paginate.= "...";
						for ($counter = $lastPage - (2 + ($stages * 2)); $counter <= $lastPage; $counter++)
						{
							if ($counter == $page){
								  $paginate.= "<li><a style='color:#ccc;background-color: #fafafa;'>$counter</a></li>";
							}else{
								$paginate.= "<li><a href='".$url."?page=$counter$url_query'>$counter</a></li>";
							}					
						}
					}
				}				
				// Next
				if ($page < $counter - 1){ 
					$paginate.= "<li><a href='".$url."?page=$nextPage$url_query'>$next</a></li>";
				}else{
					$paginate.= "<li><a style='color:#ccc;background-color: #fafafa;'>$next</a></li>";
				}
				$paginate.= "</ul>";		
			}
			// pagination
			return $paginate;		
		}

		function short($path = "", $short_item = array(), $arr = array()){			
			$parameter = $short_item[0];
			$value = $short_item[1];			
			$url_query = "";

			if( strtolower($value) == "desc"){
				$url_query .= "&".$parameter."=asc";
			}else if( strtolower($value) == "asc"){
				$url_query .= "&".$parameter."=desc";
			}else{
				$url_query .= "&".$parameter."=asc";
			}		
			
			if($_SERVER['QUERY_STRING'] != null){
					
					$query_string = $this->remove_qs_key($_SERVER['QUERY_STRING'], $parameter);
					
					foreach ($arr as $value) {
						$query_string = $this->remove_qs_key($query_string, $value);
					}
					foreach ($arr as $value) {
						$query_string .= "&$value=";
					}
					$names_and_values = explode("&", $query_string.$url_query);
					$return_string = "";

					foreach($names_and_values as $value){
						list($var_name, $var_value) = explode("=", $value);
						if($var_name != "view_page"){
							$return_string.= $var_name."=".$var_value."&";
						}
					}	
					return $path."?".substr($return_string, 0, -1);
				}
				return $path.$url_query;
			}
		function remove_qs_key($url, $key) {
			return preg_replace('/(?:&|(\?))' . $key . '=[^&]*(?(1)&|)?/i', "$1", $url);
		}
		
		function total(){
			return $this->total_pages;	
		}
	}

.paginate {
	font-family:Arial, Helvetica, sans-serif;
	padding: 3px;
	margin: 3px;
}

.paginate a {
	padding:2px 5px 2px 5px;
	margin:2px;
	border:1px solid #999;
	text-decoration:none;
	color: #666;
}
.paginate a:hover, .paginate a:active {
	border: 1px solid #999;
	color: #000;
}
.paginate span.currently {
	margin: 2px;
	padding: 2px 5px 2px 5px;
	border: 1px solid #999;

	font-weight: bold;
	background-color: #999;
	color: #FFF;
}
.paginate span.disabled {
	padding:2px 5px 2px 5px;
	margin:2px;
	border:1px solid #eee;
	color:#DDD;
}

Tutorial

# BASIC PAGEINATION :
$pagination = new Pagination();
$pagination->basic( URL, PAGE, LIMIT, TOTAL, array(PARAMETER), array(VALUES)); 
$pagination->total();

# Example
$pagination->basic( "index", $page, $limit, $total ); 
OR
$pagination->basic(  "index", 
		  $page, $limit, $total, 
		  array( "user_id", "time"),  
		  array( $user_id , $time )
		); 
		$pagination->total();		


# OUTPUT :
← 1 2 3 4 5 →

# PAGEINATION SHORT :
$pagination->short( URL, array(【SHORT ITEM】PARAMETER, VALUES), array(【CLEAN ITEM : E.g "user_id=asc" -> "user_id="】))
		
# Example
$pagination->short("index", 
		    array("user_id", $user_id),
		    array("time")
		  );

Watermark Class

<?php
class Watermark{
 
    public function __construct(){
    }
 
    public function waterInfo($ground,$watermark,$pos=0,$prefix="",$tm=50){
        $allPathGround  = $ground;
        $allPathWater   = $watermark;
        $groundInfo = $this->imgInfo($allPathGround);    
        $waterInfo  = $this->imgInfo($allPathWater);
 
     
        if(!$newPos=$this->imgPos($groundInfo,$waterInfo,$pos)){
            echo "You Watermark is bigger then image.";     
            return false;
        }

        $groundRes=$this->imgRes($allPathGround,$groundInfo['mime']);
        $waterRes=$this->imgRes($allPathWater,$waterInfo['mime']);
        $newGround=$this->imgCopy($groundRes,$waterRes,$newPos,$waterInfo,$tm);
        $this->saveImg($newGround,$ground,$groundInfo['mime'],$prefix);
    }
 
    private function saveImg($img,$ground,$info,$prefix){
        $path=$prefix;
        switch($info){
            case "image/jpg":   
            case "image/jpeg":
            case "image/pjpeg":
                imagejpeg($img,$path);
                break;
            case "image/gif":
                imagegif($img,$path);
                break;
            case "image/png":
                imagepng($img,$path);
                break;
            default:
                imagegd2($img,$path);   
        }   
    }
 
    private function imgCopy($ground,$watermark,$pos,$waterInfo,$tm){   
        imagecopymerge($ground,$watermark,$pos[0],$pos[1],0,0,$waterInfo[0],$waterInfo[1],$tm);
            return $ground;
    }
 
    private function imgRes($img,$imgType){
        switch($imgType){
            case "image/jpg":   
            case "image/jpeg":
            case "image/pjpeg":
                $res=imagecreatefromjpeg($img);
                break;
            case "image/gif":
                $res=imagecreatefromgif($img);
                break;
            case "image/png":
                $res=imagecreatefrompng($img);
                break;
            case "image/wbmp":
                $res=imagecreatefromwbmp($img);
                break;
            default:
                $res=imagecreatefromgd2($img);
        }   
        return $res;
    }
 
    private function imgPos($ground,$watermark,$pos){
        if($ground[0]<$watermark[0] || $ground[1]<$watermark[1]) 
            return false;
        switch($pos){
            case 1:
                $x=0;
                $y=0;
                break;
            case 2:
                $x=ceil(($ground[0]-$watermark[0])/2);
                $y=0;
                break;
            case 3: 
                $x=$ground[0]-$watermark[0];
                $y=0;
                break;
            case 4:
                $x=0;
                $y=ceil(($ground[1]-$watermark[1])/2);
                break;
            case 5:
                $x=ceil(($ground[0]-$watermark[0])/2);
                $y=ceil(($ground[1]-$watermark[1])/2);
                break;
            case 6:
                $x=$ground[0]-$watermark[0];
                $y=ceil(($ground[1]-$watermark[1])/2);
                break;
            case 7:
                $x=0;
                $y=$ground[1]-$watermark[1];
                break;
            case 8:
                $x=ceil($ground[0]-$watermark[0]/2);
                $y=$ground[1]-$watermark[1];
                break;
            case 9:
                $x=$ground[0]-$watermark[0];
                $y=$ground[1]-$watermark[1];
                break;
            case 0:
            default:
                $x=rand(0,$ground[0]-$watermark[0]);
                $y=rand(0,$ground[1]-$watermark[1]);
        }
        $xy[]=$x;
        $xy[]=$y;
        return $xy; 
    }
     
    private function imgInfo($img){
        return getimagesize($img);  
    }
}
?>

index.php

 $watermark = new watermark();  
 $watermark->waterInfo("./abc/06.jpg","./abc/d.png",7,"./abc.jpg",20);
 // $watermark->waterInfo(IMAGE, WATER-MARK(PNG-8), POSIITION, abc.jpg(GEN IMAGE), ALPHA);    

Remark :
POSITION 位置
1 2 3
4 5 6
7 8 9

IMAGE : 圖片
WATER-MARK(PNG-8) : 水印圖片
POSITION : 位置
abc.jpg(GEN IMAGE) : 輸出圖片
ALPHA : 透明 1-100

Cookie Class

cookie.cls.php

<?php
	class Cookie{
		private $cookie; 
		
		function encryptCookie($cookie){
		  $this->cookie = $cookie;
		  if(!$this->cookie){return false;}
			   $key = '0b16b6d29f92bc32f417f14f2c16ea2a';
			   $text = $this->cookie;
			   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
			   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
			   $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
		   return trim(base64_encode($crypttext)); //encode for cookie
		}

		function decryptCookie($cookie){
			   $this->cookie = $cookie;
			   if(!$this->cookie){return false;}
			   $key = '0b16b6d29f92bc32f417f14f2c16ea2a';
			   $crypttext = base64_decode($this->cookie); //decode cookie
			   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
			   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
			   $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
			   return trim($decrypttext);
		}
	}
?>

IP Class

	class IP{
		var $ip = "";
		var $hostname = "";
		var $city = "";
		var $region = "";
		var $country = "";
		var $loc = "";
		var $org ="";
		var $arr = array();
		
		function info(){
			$ip_address = $_SERVER['REMOTE_ADDR'];
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_URL, "http://ipinfo.io/".$ip_address."/json");
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       
			$data = json_decode(curl_exec($ch));
			curl_close($ch);

			if (isset($data->ip)) {
				$this->ip = $data->ip;
			}
			if (isset($data->hostname)) {
				$this->hostname = $data->hostname;
			}
			if (isset($data->city)) {
				$this->city = $data->city;
			}
			if (isset($data->region)) {
				$this->region = $data->region;
			}
			if (isset($data->country)) {
				$this->country = $data->country;
			}
			if (isset($data->loc)) {
				$this->loc = $data->loc;
			}
			if (isset($data->org)) {
				$this->org = $data->org;
			}
			
			$this->arr['ip'] = $this->ip ;
			$this->arr['hostname'] = $this->hostname ;
			$this->arr['city'] = $this->city ;
			$this->arr['region'] = $this->region ;
			$this->arr['country'] = $this->country ;
			$this->arr['loc'] = $this->loc ;
			$this->arr['org'] = $this->org ;
			return $this->arr;
		}
	}

$ip_address = new IP();
echo $ip->info()['ip']."<br/>";
echo $ip->info()['hostname']."<br/>";
echo $ip->info()['city']."<br/>";
echo $ip->info()['region']."<br/>";
echo $ip->info()['country']."<br/>";
echo $ip->info()['loc']."<br/>";
echo $ip->info()['org']."<br/>";

ip.sql

CREATE TABLE `guest` (
		  `ip` varchar(50) NOT NULL,
		  `hostname` varchar(255) NOT NULL,
		  `city` varchar(255) NOT NULL,
		  `region` varchar(255) NOT NULL,
		  `country` varchar(255) NOT NULL,
		  `loc` varchar(255) NOT NULL,
		  `org` varchar(255) NOT NULL,
		  `entry` datetime NOT NULL,
		  `times` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Remark :

IP: 59.148.244.85
Location: Central District,
Full response:
{
	"ip": "59.148.244.85",
	"hostname": "059148244085.ctinets.com",
	"city": "Central District",
	"region": "",
	"country": "HK",
	"loc": "22.2910,114.1500",
	"org": "AS9269 Hong Kong Broadband Network Ltd."
}