PHP Development

Generate the Guid use for php class

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
< ?php
class   System
{
	function   currentTimeMillis()
	{
		list($usec,   $sec)   =   explode("   ",microtime());
		return   $sec.substr($usec,   2,   3);
	}
}
class   NetAddress
{
	var   $Name   = 'easemarry.com';
	var   $IP   = '69.65.10.199';
	function   getLocalHost()   //   static
	{
		$address   =   new   NetAddress();
		$address->Name   =   $_ENV["COMPUTERNAME"];
		$address->IP   =   $_SERVER["SERVER_ADDR"];
		return   $address;
	}
	function   toString()
	{
		return   strtolower($this->Name.'/'.$this->IP);
	}
}
class   Random
{
	function   nextLong()
	{
		$tmp   =   rand(0,1)?'-':'';
		return   $tmp.rand(1000,   9999).rand(1000,   9999).rand(1000,   9999).rand(100,   999).rand(100,   999);
	}
}
 
class   Guid
{
	var   $valueBeforeMD5;
	var   $valueAfterMD5;
	function   Guid()
	{
		$this->getGuid();
	}
	//
	function   getGuid()
	{
		$address   =   NetAddress::getLocalHost();
		$this->valueBeforeMD5   =   $address->toString().':'.System::currentTimeMillis().':'.Random::nextLong();
		$this->valueAfterMD5   =   md5($this->valueBeforeMD5);
	}
	function   newGuid()
	{
		$Guid   =   new   Guid();
		return   $Guid;
	}
	function   toString()
	{
		$raw   =   strtoupper($this->valueAfterMD5);
		return   substr($raw,0,8).'_'.substr($raw,8,4).'_'.substr($raw,12,4).'_'.substr($raw,16,4).'_'.substr($raw,20).'_'.time();
	}
}
?>


Using sockets in PHP : Get articles from Usenet

http://www.phpbuilder.net/columns/armel20010427.php3

PHP can open sockets on remote or local hosts. Here is a hands-on example of using such a socket: getting connected to a Usenet News Server, talking to this server, and downloading some articles for a precise newsgroup.

Opening a socket in PHP

Sockets are opened using fsockopen(). This function is both available in PHP3 and PHP4. It uses the following prototype :

<?php
int fsockopen
    
(string hostname,
        
int port [,
        
int errno [,
        
string errstr [,
        
double timeout]]])
?>

 For the Internet domain, it will open a TCP socket connection to hostname on port port. hostname may in this case be either a fully qualified domain name or an IP address. For UDP connections, you need to explicitly specify the protocol: udp://hostname. For the Unix domain, hostname will be used as the path to the socket, port must be set to 0 in this case. The optional timeout can be used to set a timeout in seconds for the connect system call.

More information about fsockopen() : http://www.php.net/manual/function.fsockopen.php

Network News Transfer Protocol

Accessing a Usenet News Server requires using a specific protocol, called NNTP and standing for Network News Transfer Protocol.

This protocol is higly detailed in RFC977 (Request For Comment number 977), which is available at : http://www.w3.org/Protocols/rfc977/rfc977.html

This document described precisely how to connect to and then dialog with the NNTP server thanks to the various commands available for the task.

Connecting

Connecting to the NNTP server requires knowing its hostname (or IP address) and the port it is listening on. You should include a timeout so that an unsuccessful attempt at connecting does not “freeze” the application.
<?php
$cfgServer    
= “your.news.host”;
$cfgPort    = 119;
$cfgTimeOut    = 10;// open a socket
if(!$cfgTimeOut)
    
// without timeout
    
$usenet_handle = fsockopen($cfgServer, $cfgPort);
else
    
// with timeout
    
$usenet_handle = fsockopen($cfgServer, $cfgPort, &$errno, &$errstr, $cfgTimeOut);if(!

$usenet_handle) {
    echo
“Connexion failed\n”;
    exit();
}    
else {
    echo
“Connected\n”;
    
$tmp = fgets($usenet_handle, 1024);
}
?>
Talking to the Server

We are now connected to the server, and can talk to it through th previously opened socket. Let us say we want to get the 10 latest articles from some newsgroup. RFC977 specifies that the first step is to select the right newsgroup with the GROUP command :

GROUP ggg

The required parameter ggg is the name of the newsgroup to be selected (e.g. “net.news”). A list of valid newsgroups may be obtained from the LIST command. The successful selection response will return the article numbers of the first and last articles in the group, and an estimate of the number of articles on file in the group.

Example:

chrome:~$ telnet my.news.host 119
Trying aa.bb.cc.dd…
Connected to my.news.host.
Escape character is ‘^]’.
200 my.news.host InterNetNews NNRP server INN 2.2.2 13-Dec-1999 ready (posting ok).
GROUP alt.test
211 232 222996 223235 alt.test
quit
205
After receiving the command ” GROUP alt.test”, the News Server answered “211 232 222996 223235 alt.test”. 211 is an RFC defined code (basically saying the command was succesfully executed – check the RFC for more details). It also answered it currently has 232 articles, indexed 222996 for the oldest through 223235 for the latest. These are called article numbers. Now, let us have a count here : 222996 + 232 by no means equals to 232235. The seven missing articles were removed one way or another from the server, either cancelled by their legitimate author (yes, it is possible and easy to do !) or deleted after report of abuse for example.
Be careful though, the server might require authentication before selecting the newsgroup, depending on wether it is a public or private server. It could also let anybody retrieve articles but require authentication to publish an article.

<?php//$cfgUser    = “xxxxxx”;
//$cfgPasswd    = “yyyyyy”;
$cfgNewsGroup    = “alt.php”;

// identification required on private server
if($cfgUser) {
    
fputs($usenet_handle, “AUTHINFO USER “.$cfgUser.“\n”);
    
$tmp = fgets($usenet_handle, 1024);    fputs($usenet_handle, “AUTHINFO PASS “.$cfgPasswd.“\n”);
    
$tmp = fgets($usenet_handle, 1024);    

// check error
    
    
if($tmp != “281 Ok\r\n”) {
        echo
“502 Authentication error\n”;
        exit();
    }    
}
// select newsgroup

fputs($usenet_handle, “GROUP “.$cfgNewsGroup.“\n”);
$tmp = fgets($usenet_handle, 1024);if($tmp == “480 Authentication required for command\r\n”) {
    echo
“$tmp\n;
    exit();
}    

$info = split(” “, $tmp);
$first = $info[2];
$last = $info[3]; print “First : $first\n;
print
“Last : $last\n;?>


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 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;?/>"/>