Archive for March, 2008

mysql backup

usage

#mysqldump [options] db_name [tables]
#mysqldump [options] –databases db_name1 [db_name2 db_name3...]
#mysqldump [options] –all-databases

Example

#mysqldump -u root -p mydatabase > db.sql

Specific table

#mysqldump -u root -p mydatabase -tables customer > db.sql

How to restore database

#mysql -u root -p database < db.sql

If want to restore to specific database

mysql -u root -pMyPassword MyDatabase < db.sql


Simple PHP Cache Manager Class

This class can be used to cache arbitrary data in files.

It can check if the cache with a certain key already exists. If it exists and it is not expired, it can return the cached data. Otherwise it can store newly generated data in a cache file with the given key.

The class can be configured to set the cache life time and the root directory of where all the cache files will be stored.

cachemanager.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
< ?php
class CacheManager extends Entity {
 
	/**
	* Contains number of seconds - timeframe for storing cache
	* @http://www.easemarry.com/blog
	* @var int
	* @name timeframe
	* @access private
	*/
	var $timeframe;
 
	/**
	* Contains name of the cache root directory 
	*
	* @var string
	* @name _cacheRoot
	* @access public
	*/
	var $_cacheRoot;
 
	/**
	* Constructor, defines timeframe for storing cache
	*
	* @param int number of seconds
	* @param int number of minutes
	* @param int number of hours
	* @param int number of days
	* @param int number of month
	* @param int number of years
	*/
	function CacheManager ($second = 0, $minute = 0, $hour = 0, $day = 0, $month = 0, $year = 0) {
		$this->timeframe = mktime (2 + $hour, 0 + $minute, 0 + $second, 1 + $month, 1 + $day, 1970 + $year);
	}
 
	/**
	* Checks if cache contains file no older than timeframe
	*
	* @return string
	*/
	function CheckCache ($model, $key = 0, $fname = '', $timeframe = 0) {
		$result   = 0;
		$filename = ($fname ? $fname : $this->_cacheRoot.strtolower($model).'/'.($key ? $key : 'model').'.html');
		if ( file_exists ($filename) ) {
			$tframe = ($timeframe ? $timeframe : $this->timeframe);
			if (time() - filemtime ($filename) < $tframe) $result = $this->RetrieveData ($filename);
		}
		return $result;
	}
 
	/**
	* Read the content of the file
	*
	* @param string filename
	* @return string
	*/
	function RetrieveData ($filename) {
		$fp      = fopen ($filename, 'r');
		$content = fread ($fp, filesize ($filename));
		fclose ($fp);
		return $content;
	}
 
	/**
	* Store content in the file
	*
	* @return string
	*/
	function SaveToCache ($model, $key = 0, $content = '', $fname = '') {
		$filename = ($fname ? $fname : $this->_cacheRoot.strtolower($model).'/'.($key ? $key : 'model').'.html');
		$fp       = fopen ($filename, 'w+');
		fwrite ($fp, $content);
		fclose ($fp);
		return $filename;
	}
 
}
?>

example.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
< ?php
/**
* This example represents how easily we can automate 
* caching of both news list, and single news using 
* CacheManager class
*/
 
function GetElement ($key) {
	/* return single news */
	return 'Full News Number '.$key;
}
 
function GetElements () {
	/* return news list */
	for ($i=1; $i&lt;11; $i++) $result .= '<a href="./?id='.$i.'">News '.$i.'<br / />';
	return $result;
}
 
include './cachemanager.php';
 
$key = (isset($_GET['id']) ? intval($_GET['id']) : 0);
$CacheManager = &new CacheManager (0, 5);
$CacheManager->_cacheRoot = './cache/';
$content = $CacheManager->CheckCache ('news', $key);
if (!$content) {
    $content = ($key ? GetElement ($key) : $this->GetElements());
    $CacheManager->SaveToCache ('news', $key, $content);
}
 
echo $content;
?>


PHP functions to Apache handle.htpasswd file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
< ?php
/*
 
 Author : Mitko Kostov
 Weblog : http://mkostov.wordpress.com 
 Mail :mitko.kostov@gmail.com
 Date : 12/21/2007
 Used : PHP and Smarty
 
*/
// function to register user
function regUser() {      
        $filename = 'members/password/.htpasswd';
        $data = $_POST['username'].":".htpasswd($_POST['password'])."\n";
   if (is_writable($filename)) {   
            if (!$handle = fopen($filename, 'a')) {
                echo "Cannot open file ($filename)";
                exit;
            }   
            if (fwrite($handle, $data) === FALSE) {
                echo "Cannot write to file ($filename)";
                exit;
            }
            // echo "Success, wrote ($data) to file ($filename)";
            fclose($handle);
         } else {        
            echo "The file $filename is not writable";
           }
}
 
// function to show all users and passwords ( encrypted )
function showUser()
{    
     $file = file('members/password/.htpasswd');
     $array = array();
     $count = count($file);
     for ($i = 0; $i < $count; $i++)
     {
                list($username, $password) = explode(':', $file[$i]);
                $array[] = array("username" => $username, "password" => $password);
      }
 
     return $array;
}
function delUser($username) { 
   $fileName = file('members/password/.htpasswd');
   $pattern = "/". $username."/";  
   foreach ($fileName as $key => $value) {   
   if(preg_match($pattern, $value)) { $line = $key;  }
   } 
  unset($fileName[$line]); 
   if (!$fp = fopen('members/password/.htpasswd', 'w+'))
      {  
        print "Cannot open file ($fileName)";     
        exit;
      }
 
     if($fp)
      {       
        foreach($fileName as $line) { fwrite($fp,$line); }       
        fclose($fp);
      } 
}
 
// function for encrypting password   
function htpasswd($pass)
{
     $pass = crypt(trim($pass),base64_encode(CRYPT_STD_DES));
     return $pass;
}
?>


PHP Cookie Handler Class


This class allows for the handling of normal and serialized cookies as well as switching between these types of cookies.

Cookie Functions:
Write Cookies
Read Cookies
Delete Cookies

Use of this class is fairly simple.

Step 1: Include the class source in your php project using the require or include statement.
Step 2: Instance the cookie class by using the new keyword. The constructor uses these parameters
cookieName[string]{required} as the base name of the cookie
cookieTimeout[int]{required} as the time added the Unix timestamp to determine when a cookie expires
cookieSerialize[bool]{optional} default is false. If set to true then the cookies will be stored as a single serialized cookie.
cookiePath[string]{optional} default is “/” for root path you can set for sub-directory paths here if you wish.

The constructor also handles the switch over from individual cookies to serialzied cookies.

Step 3: Write a cookie

NOTE: It is important to remember that writing cookies must be done before any other output is sent to the browser.

The WriteCookie function takes as an array as an argument. This array should be built so that the name of the value name
is stored as the array element index and the value to be set is the element value
array[name] = value

Create one element for each value you want stored as a cookie.

Step 4: Read a cookie

NOTE: Of course you can read a cookie from the $_COOKIE array however you will lose out on the in built handling of serialized cookies.

You read a cookie’s value by calling the ReadCookie function which takes as its argument the value name and you will receive the
cookie value in return. If the value name is not present (this single cookie is not set or not in the serialized array) then a NULL
is returned.

It is best to store the value to a variable and then test for NULL by the is_null function.

Step 5: KillCookie

The KillCookie function allows you to delete a single cookie item or array element. It takes as its argument the value name to be deleted.

Step 6: DestroyAllCookies

Will go through all the cookies with the base name as set in the constructor and delete them.
The delete process for this and the KillCookie function is handled by setting the cookie’s expire date as the current Unix timestamp
- a large integer (several years).

Step 7: To change cookies from individual cookies to a serialized cookie
This is handled by changing the constructor’s cookieSerialize flag from false to true. It must be done when the cookieClass is
instanced or it will not function correctly.

If you have any comments or questions concerning this php class you may contact me at jrsofty@gmail.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
< ?php
	// cookieClass
	// Copyright (C) 2005 JRSofty Programming.
	// http://jrsofty1.stinkbugonline.com
	// Licensed under GNU/GPL 
 
	class cookieClass{
 
		var $cName = '';
		var $cTime = '';
		var $cSerialize = false;		
		var $cPath = '';
 
		function cookieClass($cookieName, $cookieTimeout, $cookieSerialize = false, $cookiePath = "/"){
			$this->cName = $cookieName;
			$this->cTime = $cookieTimeout;
			$this->cSerialize = $cookieSerialize;
			$this->cPath = $cookiePath;
			// This should fix the issue if you have cookies set and THEN turn on the serialization.
			$iname = $this->cName . "_S";
			if($this->cSerialize && !isset($_COOKIE[$iname])){
				$cookArr = array();
				foreach($_COOKIE as $name=>$val){
					if(strpos($name,$this->cName) !== false ){ // make sure it is a cookie set by this application
						$subname = substr($name,strlen($this->cName) + 1);
						$cookArr[$subname] = $val;
						$this->KillCookie($name);
					}
				}
				$this->WriteCookie($cookArr);
			}
			// This is the opposite from above. changes a serialized cookie to multiple cookies without loss of data
			if(!$this->cSerialize && isset($_COOKIE[$iname])){
				$cookArr = unserialize($_COOKIE[$iname]);
				$this->KillCookie($iname);
				$this->WriteCookie($cookArr);
			}
 
 
		}
 
		function DestroyAllCookies(){
			foreach($_COOKIE as $name=>$val){
				if(strpos($name,$this->cName) !== false){
					$_COOKIE[$name] = NULL;
					$this->KillCookie($name);
				}
			}
		}
 
		function ReadCookie($item){
			if($this->cSerialize){
				$name = $this->cName . "_S";
				if(isset($_COOKIE[$name])){
					// handle the cookie as a serialzied variable
					$sCookie = unserialize($_COOKIE[$name]);
					if(isset($sCookie[$item])){
						return $sCookie[$item];
					}else{
						return NULL;
					}
				}else{
					return NULL;
				}
			}else{
				$name = $this->cName . "_" . $item;
				if(isset($_COOKIE[$name])){
					// handle the item as separate cookies
					return $_COOKIE[$name];
				}else{
					return NULL;
				}
			}	
		}
 
		function KillCookie($cName){
			$tStamp = time() - 432000;
			setcookie($cName,"",$tStamp,$this->cPath);
		}
 
		function WriteCookie($itemArr){
			if($this->cSerialize){					
				$sItems = serialize($itemArr);
				$name = $this->cName . "_S";
				$_COOKIE[$name] = $sItems;
				$tStamp = time() + $this->cTime;
				setcookie($name,$sItems,$tStamp,$this->cPath);
			}else{
				$tStamp = time() + $this->cTime;
				foreach($itemArr as $nam=>$val){
					$name = $this->cName . "_" . $nam;
					$_COOKIE[$name] = $val;
					setcookie($name,$val,$tStamp,$this->cPath);
				}e
			}
		}
 
 
	}
?>


PHP generate new an resizing image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
< ?PHP     
class HanroadClass
{
	/************************
	generate new an Resizing image by the PHP GD library
	Support picture format: jpg, gif, png
	$source_img:     Source image path
	$target_dir:     Target image path
	$target_name:    Target image name
	$new_width:      Target image width
	$new_height:     Target image height
	$if_cut:         cutting image ?
	1(yes):          Specified high or width generated Images
	0(no):           Proportion generated Images
	**********************/
	function  HrResize($source_img,$target_dir,$target_name,$new_width,$new_height,$if_cut)
	{
		//Get image format
		$img_type   =   strtolower(substr(strrchr($source_img,"."),1));
 
		//Target image path
		$tar_url   =   $target_dir."/".$target_name.".".$img_type;
 
		if($img_type=="jpg")   $temp_img   =   imagecreatefromjpeg($source_img);
		if($img_type=="gif")   $temp_img   =   imagecreatefromgif($source_img);
		if($img_type=="png")   $temp_img   =   imagecreatefrompng($source_img);
 
		//Source image's width and height
		$old_width     =   imagesx($temp_img);
		$old_height   =   imagesy($temp_img);
 
		//Change the ratio of the image before and after
		$new_ratio   =   $new_width/$new_height;
		$old_ratio   =   $old_width/$old_height;
 
		//Generate new image
		if($if_cut=="1")
		{
			$new_width     =   $new_width;
			$new_height   =   $new_height;
			if($old_ratio>=$new_ratio)
			{
				$old_width     =   $old_height*$new_ratio;
				$old_height   =   $old_height;
			}
			else
			{
				$old_width     =   $old_width;
				$old_height   =   $old_width/$new_ratio;
			}
		}
 
		else
		{
			$old_width     =   $old_width;
			$old_height   =   $old_height;
			if($old_ratio>=$new_ratio)
			{
				$new_width     =   $new_width;
				$new_height   =   $new_width/$old_ratio;
			}
			else
			{
				$new_width     =   $new_height*$old_ratio;
				$new_height   =   $new_height;
			}
		}
		$new_img   =   imagecreatetruecolor($new_width,$new_height);
		imagecopyresampled($new_img,$temp_img,0,0,0,0,$new_width,$new_height,$old_width,$old_height);
 
		if($img_type=="jpg")   imagejpeg($new_img,$tar_url,90);
		if($img_type=="gif")   imagegif($new_img,$tar_url);
		if($img_type=="png")   imagepng($new_img,$tar_url);
 
		return $target_name.".".$img_type;
	}
}
?>
 
< ?php
$nesimg=new HanroadClass();
$img1=$nesimg->HrResize("c:\test.jpg","c:\test_1.jpg",120,120,1);
$img2=$nesimg->HrResize("c:\test.jpg","c:\test_2.jpg",120,120,0);
?>
$img1:
<img src="<?php echo $img1;?/>"/><br /><br />
$img2:
<img src="<?php echo $img2;?/>"/>