如何秀出複數的排序條件資料

SELECT * FROM Product ORDER BY SellDate DESC

因為資料的SellDate可能同時會有幾十筆都相同,我希望可以在篩選出這批資料後在更詳細的依照他們的編號去做排序…

1. 先過濾出整批的較新日期的資料,資料舊的往後排
2. 再依照這些相同SellDate的資料去依照他們的編號往下排,編號大的排上面

SELECT * FROM Product ORDER BY SellDate DESC, product_no DESC

若果編號在另一個 table (假設名稱是 ‘Porduct2’), ‘Product’ 和 ‘Product2’ 都有 common key ‘id’:

SELECT Product.* FROM Product, Product2 WHERE Product.id = Product2.id ORDER BY Product.SellDate DESC, Product2.product_no DESC

PHP GooGle PageRank程式

<?php
// Google PageRank Calculator function by ZeNiTRaM – version 0.1
// Licensed under the GPL License
// eMail me at zenitram [AT] dubmail.net
// Uses code from The Google Checksum Calculator, by Alex Stapleton, Andy Doctorow, Vijay “Cyberax" Bhatter, and a few others, licensed under the public domain (http://www.mobileread.com/forums/showpost.php?p=7769&postcount=87) and XMLize.php by Hans Anderson (http://www.hansanderson.com/php/xml/).
// Use: $pagerank = GetPagerank(“http://www.google.es");
// GetPagerank returns a STRING with the Pagerank number directly from Google

//    S    P    A    N    I    S    H———————————————————————————–
// Calculadora Google Pagerank por ZeNiTRaM – version 0.1
// Licenciado bajo la licencia GPL.
// Contacta conmigo en zenitram [AT] dubmail.net
// Usa codigo de The Google Checksum Calculator, por Alex Stapleton, Andy Doctorow, Vijay “Cyberax" Bhatter, y unos cuantos otros mas, licenciado bajo dominio publico (http://www.mobileread.com/forums/showpost.php?p=7769&postcount=87) y XMLize.php por Hans Anderson (http://www.hansanderson.com/php/xml/).

/*
Changelog
0.1:    Started counting versions and tidied all the code. Maybe I will add some new functions to get more information from Google.
He empezado a contar versiones y limpiado un poco todo el codigo. Quizas a&ntilde;ada nuevas funciones para conseguir mas informacion de Google.
*/

// Function GetPagerank
$a = GetPagerank(‘http://tw.yahoo.com/’);
echo $a;
function GetPagerank($urlo) {
define(‘GOOGLE_MAGIC’, 0xE6359A60);

$url = ‘info:’.$urlo;
$ch = GoogleCH(strord($url));
$chf = “6$ch";

$file = file(“http://www.google.com/search?client=navclient-auto&ch=$chf&q=$url");
$file_str = implode(“", $file);
$xml = xmlize($file_str);

$pr = $xml[“GSP"][“#"][“RES"][0][“#"][“R"][0][“#"][“RK"][0][“#"];
if(!$pr) $pr = 0;
return $pr;
}

//Starts code from XMLize.php
function xmlize($data, $WHITE=1) {

$data = trim($data);
$vals = $index = $array = array();
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, $WHITE);
if ( !xml_parse_into_struct($parser, $data, $vals, $index) )
{
die(sprintf(“XML error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));

}
xml_parser_free($parser);

$i = 0;

$tagname = $vals[$i][‘tag’];
if ( isset ($vals[$i][‘attributes’] ) )
{
$array[$tagname][‘@’] = $vals[$i][‘attributes’];
} else {
$array[$tagname][‘@’] = array();
}

$array[$tagname][“#"] = xml_depth($vals, $i);

return $array;
}

/*
*
* You don’t need to do anything with this function, it’s called by
* xmlize.  It’s a recursive function, calling itself as it goes deeper
* into the xml levels.  If you make any improvements, please let me know.
*
*
*/

function xml_depth($vals, &$i) {
$children = array();

if ( isset($vals[$i][‘value’]) )
{
array_push($children, $vals[$i][‘value’]);
}

while (++$i < count($vals)) {

switch ($vals[$i][‘type’]) {

case ‘open’:

if ( isset ( $vals[$i][‘tag’] ) )
{
$tagname = $vals[$i][‘tag’];
} else {
$tagname = “;
}

if ( isset ( $children[$tagname] ) )
{
$size = sizeof($children[$tagname]);
} else {
$size = 0;
}

if ( isset ( $vals[$i][‘attributes’] ) ) {
$children[$tagname][$size][‘@’] = $vals[$i][“attributes"];
}

$children[$tagname][$size][‘#’] = xml_depth($vals, $i);

break;

case ‘cdata’:
array_push($children, $vals[$i][‘value’]);
break;

case ‘complete’:
$tagname = $vals[$i][‘tag’];

if( isset ($children[$tagname]) )
{
$size = sizeof($children[$tagname]);
} else {
$size = 0;
}

if( isset ( $vals[$i][‘value’] ) )
{
$children[$tagname][$size][“#"] = $vals[$i][‘value’];
} else {
$children[$tagname][$size][“#"] = “;
}

if ( isset ($vals[$i][‘attributes’]) ) {
$children[$tagname][$size][‘@’]
= $vals[$i][‘attributes’];
}

break;

case ‘close’:
return $children;
break;
}

}

return $children;

}

/* function by acebone@f2s.com, a HUGE help!
*
* this helps you understand the structure of the array xmlize() outputs
*
* usage:
* traverse_xmlize($xml, ‘xml_’);
* print ‘<pre>’ . implode(“", $traverse_array . ‘</pre>’;
*
*
*/

function traverse_xmlize($array, $arrName = “array", $level = 0) {

foreach($array as $key=>$val)
{
if ( is_array($val) )
{
traverse_xmlize($val, $arrName . “[" . $key . “]", $level + 1);
} else {
$GLOBALS[‘traverse_array’][] = ‘$’ . $arrName . ‘[‘ . $key . ‘] = “‘ . $val . “\"\n";
}
}

return 1;

}
//Ends code from XMLize.php

//Starts code from The Google Checksum Calculator
//unsigned shift right
function zeroFill($a, $b)
{
$z = hexdec(80000000);
if ($z & $a)
{
$a = ($a>>1);
$a &= (~$z);
$a |= 0x40000000;
$a = ($a>>($b-1));
}
else
{
$a = ($a>>$b);
}
return $a;
}

function mix($a,$b,$c) {
$a -= $b; $a -= $c; $a ^= (zeroFill($c,13));
$b -= $c; $b -= $a; $b ^= ($a<<8);
$c -= $a; $c -= $b; $c ^= (zeroFill($b,13));
$a -= $b; $a -= $c; $a ^= (zeroFill($c,12));
$b -= $c; $b -= $a; $b ^= ($a<<16);
$c -= $a; $c -= $b; $c ^= (zeroFill($b,5));
$a -= $b; $a -= $c; $a ^= (zeroFill($c,3));
$b -= $c; $b -= $a; $b ^= ($a<<10);
$c -= $a; $c -= $b; $c ^= (zeroFill($b,15));

return array($a,$b,$c);
}

function GoogleCH($url, $length=null, $init=GOOGLE_MAGIC) {
if(is_null($length)) {
$length = sizeof($url);
}
$a = $b = 0x9E3779B9;
$c = $init;
$k = 0;
$len = $length;
while($len >= 12) {
$a += ($url[$k+0] +($url[$k+1]<<8) +($url[$k+2]<<16) +($url[$k+3]<<24));
$b += ($url[$k+4] +($url[$k+5]<<8) +($url[$k+6]<<16) +($url[$k+7]<<24));
$c += ($url[$k+8] +($url[$k+9]<<8) +($url[$k+10]<<16)+($url[$k+11]<<24));
$mix = mix($a,$b,$c);
$a = $mix[0]; $b = $mix[1]; $c = $mix[2];
$k += 12;
$len -= 12;
}

$c += $length;
switch($len)              /* all the case statements fall through */
{
case 11: $c+=($url[$k+10]<<24);
case 10: $c+=($url[$k+9]<<16);
case 9 : $c+=($url[$k+8]<<8);
/* the first byte of c is reserved for the length */
case 8 : $b+=($url[$k+7]<<24);
case 7 : $b+=($url[$k+6]<<16);
case 6 : $b+=($url[$k+5]<<8);
case 5 : $b+=($url[$k+4]);
case 4 : $a+=($url[$k+3]<<24);
case 3 : $a+=($url[$k+2]<<16);
case 2 : $a+=($url[$k+1]<<8);
case 1 : $a+=($url[$k+0]);
/* case 0: nothing left to add */
}
$mix = mix($a,$b,$c);
/*——————————————– report the result */
return $mix[2];
}

//converts a string into an array of integers containing the numeric value of the char
function strord($string) {
for($i=0;$i<strlen($string);$i++) {
$result[$i] = ord($string{$i});
}
return $result;
}
//End code from The Google Checksum Calculator
?>

非mmcache!Memcached的應用:多網站伺服器 PHP 共享 Session

請注意是 Memcached 不是 mmcache,很多人搞不清楚他們兩個的不同!多半玩過 PHP 的人大概都聽過 mmcache,它是一個預編譯緩衝的 PHP 加速程式,能夠提升 PHP 的執行效能。但很少人聽過 Memcached ,因為大多人乍看之下都以為它是mmcache,使得它沒什麼機會介紹自己。事實上,若您正打算架構一個真正高負載的大型網站系統,你需要瞭解的並不是 mmcache,而是 memcached。

Memcached 是什麼?顧名思義,他是由記憶體(Memory)和暫存(cache)所組合起來的常駐程式(Daemon),你也可以稱它為『暫存伺服器』。 Memcached 能提供一個暫存資料的服務,透過網路供其他電腦使用。Memcached 有什麼用途?最常見的應用就是在網站伺服器的叢集,它能讓許多的網站伺服器 Session 互相流通使用。如果你正在傷透腦筋煩惱這一點,恭喜你找到解決方法了!

想要在網站伺服器的叢集中,多網站伺服器 Session 互相流通使用,首先你必須將 Memcached 架起來當 Session 分享伺服器,這邊建議你使用大的記憶體,最好是能多大就有多大,因為 Memcached 並不會以硬碟當資料暫存,而是會完全跑在記憶體上,所以若記憶被用完了,Memcached 就會無法再存放更多資料。

接著,你必須修改 PHP 的 Session Save Handler,讓 PHP 懂得利用 Memcached Server 存放 PHP 的 Session 資料並能從 Memcached Server 取出 Session 的資料。PHP提供了 session_set_save_handler() 函式讓我們能輕易修改 Session Save Handler ,以下是我修改後的 PHP 程式碼,你必須在呼叫 session_start() 之前使用:

<?

define(“SHARED_SESS_TIME", 3600); // Timeout

// Session Class by Fred

class Shared_Session
{
function init()
{
ini_set(“session.use_trans_sid", 0);
ini_set(“session.gc_maxlifetime", SHARED_SESS_TIME);
ini_set(“session.use_cookies", 1);
ini_set(“session.cookie_path", “/");
ini_set(“session.cookie_domain", “.yourdomain.com.tw“);

session_module_name(“user");
session_set_save_handler(
array(“Shared_Session", “open"),
array(“Shared_Session", “close"),
array(“Shared_Session", “read"),
array(“Shared_Session", “write"),
array(“Shared_Session", “destroy"),
array(“Shared_Session", “gc")
);
}

function open($save_path, $session_name) {
return true;
}

function close() {
return true;
}

function read($sesskey) {
global $memcache;

return $memcache->get($sesskey);
}

function write($sesskey, $data) {
global $memcache;

$memcache->set($sesskey, $data, SHARED_SESS_TIME);

return true;
}

function destroy($sesskey) {
global $memcache;

$memcache->delete($sesskey);
$memcache->flush_all();

return true;
}

function gc($maxlifetime = null) {
return true;
}
}

$GLOBALS[“memcache"] = memcache();
$GLOBALS[“memcache"]->add_server(“192.168.1.1“, 11211);
$GLOBALS[“memcache"]->add_server(“192.168.1.2“, 11211);
Shared_Session::init();

?>

其中粗字體的部分,是要特別修改的地方:

  • 3600 是 Session 的生命週期﹝以秒為單位﹞,這應該不用再做太多解釋。
  • .yourdomain.com.tw 是你的網域名稱:想像一個情況若是 Loadbalance 在用戶第一次連線分配用戶到A伺服器,第二次連線分配給同一用戶到B伺服器,會導致 B 伺服器無法透過 cookies 取得 A 伺服器分配給用戶的 session_id,因為 cookies 無法跨網域存取解決方法是必須修改 cookies 的網域設定,讓 www1.yourdomain.com.tw、www2.yourdomain.com.twwww3.yourdomain.com.tw…等等,都可以共同存取同一個 cookies ,以取得同一個 session_id,故此時你必須設定成為『.yourdomain.com.tw’。
  • 192.168.1.1 這是你的 Memcached Server 的 IP 位置,這裡值得提的是 add_server() 方法,你可以有多行設定許多 IP 做 Loadbalance 負載分配,前面也講到 Memcached 是純粹使用記憶體,若其中一台機器記憶體滿了,本方法可以從中找到另一台可用的機器使用。故你可以建立一個 Memcached 的叢集來處理 Session。

因 為我偷懶, Memcached 的安裝方法就沒寫了,去求助 google 大神,它應該會告訴你更多詳細的安裝資料。其實 Memcached 除了可應用在 Session 共享上,也可以應用在資料庫的資料暫存緩充,降低SQL Server負擔以提升速度。Memcached多好用?就看你怎麼用了!

FreeBSD 使用PHP 透過FTP連線拋檔 備份

<?php
define(“FTP_TIMEOUT",90);
// FTP Statuscodes
define(“FTP_COMMAND_OK",200);
define(“FTP_FILE_ACTION_OK",250);
define(“FTP_FILE_TRANSFER_OK",226);
define(“FTP_COMMAND_NOT_IMPLEMENTED",502);
define(“FTP_FILE_STATUS",213);
define(“FTP_NAME_SYSTEM_TYPE",215);
define(“FTP_PASSIVE_MODE",227);
define(“FTP_PATHNAME",257);
define(“FTP_SERVICE_READY",220);
define(“FTP_USER_LOGGED_IN",230);
define(“FTP_PASSWORD_NEEDED",331);
define(“FTP_USER_NOT_LOGGED_IN",530);

if (!defined(“FTP_ASCII")) define(“FTP_ASCII",0);
if (!defined(“FTP_BINARY")) define(“FTP_BINARY",1);

class FTP {

var $passiveMode = TRUE;
var $lastLines = array();
var $lastLine = “";
var $controlSocket = NULL;
var $newResult = FALSE;
var $lastResult = -1;
var $pasvAddr = NULL;

var $error_no = NULL;
var $error_msg = NULL;

function FTP() {
}

function connect($host, $port=21, $timeout=FTP_TIMEOUT) { //Opens an FTP connection
$this->_resetError();

$err_no = 0;
$err_msg = “";
$this->controlSocket = @fsockopen($host, $port, $err_no, $err_msg, $timeout) or $this->_setError(-1,"fsockopen failed");
if ($err_no<>0) $this->setError($err_no,$err_msg);

if ($this->_isError()) return false;

@socket_set_timeout($this->controlSocket,$timeout) or $this->_setError(-1,"socket_set_timeout failed");
if ($this->_isError()) return false;

$this->_waitForResult();
if ($this->_isError()) return false;

return $this->getLastResult() == FTP_SERVICE_READY;
}

function isConnected() {
return $this->controlSocket != NULL;
}

function disconnect() {
if (!$this->isConnected()) return;
@fclose($this->controlSocket);
}

function close() { //Closes an FTP connection
$this->disconnect();
}

function login($user, $pass) { //Logs in to an FTP connection
$this->_resetError();

$this->_printCommand(“USER $user");
if ($this->_isError()) return false;

$this->_waitForResult();
if ($this->_isError()) return false;

if ($this->getLastResult() == FTP_PASSWORD_NEEDED){
$this->_printCommand(“PASS $pass");
if ($this->_isError()) return FALSE;

$this->_waitForResult();
if ($this->_isError()) return FALSE;
}

$result = $this->getLastResult() == FTP_USER_LOGGED_IN;
return $result;
}

function cdup() { //Changes to the parent directory
$this->_resetError();

$this->_printCommand(“CDUP");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
return ($lr==FTP_FILE_ACTION_OK || $lr==FTP_COMMAND_OK);
}

function cwd($path) {
$this->_resetError();

$this->_printCommand(“CWD $path");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
return ($lr==FTP_FILE_ACTION_OK || $lr==FTP_COMMAND_OK);
}

function cd($path) {
return $this->cwd($path);
}

function chdir($path) { //Changes directories on a FTP server
return $this->cwd($path);
}

function chmod($mode,$filename) { //Set permissions on a file via FTP
return $this->site(“CHMOD $mode $filename");
}

function delete($filename) { //Deletes a file on the FTP server
$this->_resetError();

$this->_printCommand(“DELE $filename");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
return ($lr==FTP_FILE_ACTION_OK || $lr==FTP_COMMAND_OK);
}

function exec($cmd) { //Requests execution of a program on the FTP server
return $this->site(“EXEC $cmd");
}

function fget($fp,$remote,$mode=FTP_BINARY,$resumepos=0) { //Downloads a file from the FTP server and saves to an open file
$this->_resetError();

$type = “I";
if ($mode==FTP_ASCII) $type = “A";

$this->_printCommand(“TYPE $type");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;

$result = $this->_download(“RETR $remote");
if ($result) {
fwrite($fp,$result);
}
return $result;
}

function fput($remote,$resource,$mode=FTP_BINARY,$startpos=0) { //Uploads from an open file to the FTP server
$this->_resetError();

$type = “I";
if ($mode==FTP_ASCII) $type = “A";

$this->_printCommand(“TYPE $type");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;

if ($startpos>0) fseek($resource,$startpos);
$result = $this->_uploadResource(“STOR $remote",$resource);
return $result;
}

function get_option($option) { //Retrieves various runtime behaviours of the current FTP stream
$this->_resetError();

switch ($option) {
case “FTP_TIMEOUT_SEC" : return FTP_TIMEOUT;
case “PHP_FTP_OPT_AUTOSEEK" : return FALSE;
}
setError(-1,"Unknown option: $option");
return false;
}

function get($locale,$remote,$mode=FTP_BINARY,$resumepos=0) { //Downloads a file from the FTP server
if (!($fp = @fopen($locale,"wb"))) return FALSE;
$result = $this->fget($fp,$remote,$mode,$resumepos);
@fclose($fp);
if (!$result) @unlink($locale);
return $result;
}
function mdtm($name) { //Returns the last modified time of the given file
$this->_resetError();

$this->_printCommand(“MDTM $name");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
if ($lr!=FTP_FILE_STATUS) return FALSE;
$subject = trim(substr($this->lastLine,4));
$lucifer = array();
if (preg_match(“/([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])/",$subject,$lucifer)) return mktime($lucifer[4],$lucifer[5],$lucifer[6],$lucifer[2],$lucifer[3],$lucifer[1],0);
return FALSE;
}

function mkdir($name) { //Creates a directory
$this->_resetError();

$this->_printCommand(“MKD $name");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
return ($lr==FTP_PATHNAME || $lr==FTP_FILE_ACTION_OK || $lr==FTP_COMMAND_OK);
}

function nb_continue() { //Continues retrieving/sending a file (non-blocking)
$this->_resetError();
// todo
}

function nb_fget() { //Retrieves a file from the FTP server and writes it to an open file (non-blocking)
$this->_resetError();
// todo
}

function nb_fput() { //Stores a file from an open file to the FTP server (non-blocking)
$this->_resetError();
// todo
}

function nb_get() { //Retrieves a file from the FTP server and writes it to a local file (non-blocking)
$this->_resetError();
// todo
}

function nb_put() { //Stores a file on the FTP server (non-blocking)
$this->_resetError();
// todo
}

function nlist($remote_filespec="") { //Returns a list of files in the given directory
$this->_resetError();
$result = $this->_download(trim(“NLST $remote_filespec"));
return ($result !== FALSE) ? explode(“\n",str_replace(“\r","",trim($result))) : $result;
}

function pasv($pasv) { //Turns passive mode on or off
if (!$pasv) {
$this->_setError(“Active (PORT) mode is not supported");
return false;
}
return true;
}

function put($remote,$local,$mode=FTP_BINARY,$startpos=0) { //Uploads a file to the FTP server
if (!($fp = @fopen($local,"rb"))) return FALSE;
$result = $this->fput($remote,$fp,$mode,$startpos);
@fclose($fp);
return $result;
}

function pwd() { //Returns the current directory name
$this->_resetError();

$this->_printCommand(“PWD");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
if ($lr!=FTP_PATHNAME) return FALSE;
$subject = trim(substr($this->lastLine,4));
$lucifer = array();
if (preg_match(“/\"(.*)\"/",$subject,$lucifer)) return $lucifer[1];
return FALSE;
}

function quit() { //Alias of close
$this->close();
}

function raw($cmd) { //Sends an arbitrary command to an FTP server
$this->_resetError();

$this->_printCommand($cmd);
$this->_waitForResult();
$this->getLastResult();
return array($this->lastLine);
}

function rawlist($remote_filespec="") { //Returns a detailed list of files in the given directory
$this->_resetError();
$result = $this->_download(trim(“LIST $remote_filespec"));
return ($result !== FALSE) ? explode(“\n",str_replace(“\r","",trim($result))) : $result;
}

function ls($remote_filespec="") { //Returns a parsed rawlist in an assoc array
$a = $this->rawlist($remote_filespec);
if (!$a) return $a;
$systype = $this->systype();
$is_windows = stristr($systype,"WIN")!==FALSE;
$b = array();
while (list($i,$line) = each($a)) {
if ($is_windows && preg_match(“/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)/",$line,$lucifer)) {
$b[$i] = array();
if ($lucifer[3]<70) { $lucifer[3]+=2000; } else { $lucifer[3]+=1900; } // 4digit year fix
$b[$i][‘isdir’] = ($lucifer[7]=="<DIR>");
$b[$i][‘size’] = $lucifer[7];
$b[$i][‘month’] = $lucifer[1];
$b[$i][‘day’] = $lucifer[2];
$b[$i][‘year’] = $lucifer[3];
$b[$i][‘hour’] = $lucifer[4];
$b[$i][‘minute’] = $lucifer[5];
$b[$i][‘time’] = @mktime($lucifer[4]+(strcasecmp($lucifer[6],"PM")==0?12:0),$lucifer[5],0,$lucifer[1],$lucifer[2],$lucifer[3]);
$b[$i][‘am/pm’] = $lucifer[6];
$b[$i][‘name’] = $lucifer[8];
} else if (!$is_windows && $lucifer=preg_split(“/[ ]/",$line,9,PREG_SPLIT_NO_EMPTY)) {
echo $line."\n";
$lcount=count($lucifer);
if ($lcount<8) continue;
$b[$i] = array();
$b[$i][‘isdir’] = $lucifer[0]{0} === “d";
$b[$i][‘islink’] = $lucifer[0]{0} === “l";
$b[$i][‘perms’] = $lucifer[0];
$b[$i][‘number’] = $lucifer[1];
$b[$i][‘owner’] = $lucifer[2];
$b[$i][‘group’] = $lucifer[3];
$b[$i][‘size’] = $lucifer[4];
if ($lcount==8) {
sscanf($lucifer[5],"%d-%d-%d",$b[$i][‘year’],$b[$i][‘month’],$b[$i][‘day’]);
sscanf($lucifer[6],"%d:%d",$b[$i][‘hour’],$b[$i][‘minute’]);
$b[$i][‘time’] = @mktime($b[$i][‘hour’],$b[$i][‘minute’],0,$b[$i][‘month’],$b[$i][‘day’],$b[$i][‘year’]);
$b[$i][‘name’] = $lucifer[7];
} else {
$b[$i][‘month’] = $lucifer[5];
$b[$i][‘day’] = $lucifer[6];
if (preg_match(“/([0-9]{2}):([0-9]{2})/",$lucifer[7],$l2)) {
$b[$i][‘year’] = date(“Y");
$b[$i][‘hour’] = $l2[1];
$b[$i][‘minute’] = $l2[2];
} else {
$b[$i][‘year’] = $lucifer[7];
$b[$i][‘hour’] = 0;
$b[$i][‘minute’] = 0;
}
$b[$i][‘time’] = strtotime(sprintf(“%d %s %d %02d:%02d",$b[$i][‘day’],$b[$i][‘month’],$b[$i][‘year’],$b[$i][‘hour’],$b[$i][‘minute’]));
$b[$i][‘name’] = $lucifer[8];
}
}
}
return $b;
}

function rename($from,$to) { //Renames a file on the FTP server
$this->_resetError();

$this->_printCommand(“RNFR $from");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
$this->_printCommand(“RNTO $to");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
return ($lr==FTP_FILE_ACTION_OK || $lr==FTP_COMMAND_OK);
}

function rmdir($name) { //Removes a directory
$this->_resetError();

$this->_printCommand(“RMD $name");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
return ($lr==FTP_FILE_ACTION_OK || $lr==FTP_COMMAND_OK);
}

function set_option() { //Set miscellaneous runtime FTP options
$this->_resetError();
$this->_setError(-1,"set_option not supported");
return false;
}

function site($cmd) { //Sends a SITE command to the server
$this->_resetError();

$this->_printCommand(“SITE $cmd");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
return true;
}

function size($name) { //Returns the size of the given file
$this->_resetError();

$this->_printCommand(“SIZE $name");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
return $lr==FTP_FILE_STATUS ? trim(substr($this->lastLine,4)) : FALSE;
}

function ssl_connect() { //Opens an Secure SSL-FTP connection
$this->_resetError();
$this->_setError(-1,"ssl_connect not supported");
return false;
}

function systype() { // Returns the system type identifier of the remote FTP server
$this->_resetError();

$this->_printCommand(“SYST");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
return $lr==FTP_NAME_SYSTEM_TYPE ? trim(substr($this->lastLine,4)) : FALSE;
}

function getLastResult() {
$this->newResult = FALSE;
return $this->lastResult;
}

/* private */
function _hasNewResult() {
return $this->newResult;
}

/* private */
function _waitForResult() {
while(!$this->_hasNewResult() && $this->_readln()!==FALSE && !$this->_isError()) { /* noop */ }
}

/* private */
function _readln() {
$line = fgets($this->controlSocket);
if ($line === FALSE) {
$this->_setError(-1,"fgets failed in _readln");
return FALSE;
}
if (strlen($line)==0) return $line;

$lucifer = array();
if (preg_match(“/^[0-9][0-9][0-9] /",$line,$lucifer)) {
//its a resultline
$this->lastResult = intval($lucifer[0]);
$this->newResult = TRUE;
if (substr($lucifer[0],0,1)==’5′) {
$this->_setError($this->lastResult,trim(substr($line,4)));
}
}

$this->lastLine = trim($line);
$this->lastLines[] = “< “.trim($line);
return $line;
}

/* private */
function _printCommand($line) {
$this->lastLines[] = “> “.$line;
fwrite($this->controlSocket,$line."\r\n");
fflush($this->controlSocket);
}

/* private */
function _pasv() {
$this->_resetError();
$this->_printCommand(“PASV");
$this->_waitForResult();
$lr = $this->getLastResult();
if ($this->_isError()) return FALSE;
if ($lr!=FTP_PASSIVE_MODE) return FALSE;
$subject = trim(substr($this->lastLine,4));
$lucifer = array();
if (preg_match(“/\\((\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3})\\)/",$subject,$lucifer)) {
$this->pasvAddr=$lucifer;

$host = sprintf(“%d.%d.%d.%d",$lucifer[1],$lucifer[2],$lucifer[3],$lucifer[4]);
$port = $lucifer[5]*256 + $lucifer[6];

$err_no=0;
$err_msg="";
$passiveConnection = fsockopen($host,$port,$err_no,$err_msg, FTP_TIMEOUT);
if ($err_no!=0) {
$this->_setError($err_no,$err_msg);
return FALSE;
}

return $passiveConnection;
}
return FALSE;
}

/* private */
function _download($cmd) {
if (!($passiveConnection = $this->_pasv())) return FALSE;
$this->_printCommand($cmd);
$this->_waitForResult();
$lr = $this->getLastResult();
if (!$this->_isError()) {
$result = “";
while (!feof($passiveConnection)) {
$result .= fgets($passiveConnection);
}
fclose($passiveConnection);
$this->_waitForResult();
$lr = $this->getLastResult();
return ($lr==FTP_FILE_TRANSFER_OK) || ($lr==FTP_FILE_ACTION_OK) || ($lr==FTP_COMMAND_OK) ? $result : FALSE;
} else {
fclose($passiveConnection);
return FALSE;
}
}

/* upload */
function _uploadResource($cmd,$resource) {
if (!($passiveConnection = $this->_pasv())) return FALSE;
$this->_printCommand($cmd);
$this->_waitForResult();
$lr = $this->getLastResult();
if (!$this->_isError()) {
$result = “";
while (!feof($resource)) {
$buf = fread($resource,1024);
fwrite($passiveConnection,$buf);
}
fclose($passiveConnection);
$this->_waitForResult();
$lr = $this->getLastResult();
return ($lr==FTP_FILE_TRANSFER_OK) || ($lr==FTP_FILE_ACTION_OK) || ($lr==FTP_COMMAND_OK) ? $result : FALSE;
} else {
fclose($passiveConnection);
return FALSE;
}
}

/* private */
function _resetError() {
$this->error_no = NULL;
$this->error_msg = NULL;
}

/* private */
function _setError($no,$msg) {
if (is_array($this->error_no)) {
$this->error_no[] = $no;
$this->error_msg[] = $msg;
} else if ($this->error_no!=NULL) {
$this->error_no = array($this->error_no,$no);
$this->error_msg = array($this->error_msg,$msg);
} else {
$this->error_no = $no;
$this->error_msg = $msg;
}
}

/* private */
function _isError() {
return ($this->error_no != NULL) && ($this->error_no !== 0);
}

}

//echo “argv[] = “;
//print_r($argv); // just to see what was passed in

if ($argc > 0)
{
for ($i=1;$i < $argc;$i++)
{
parse_str($argv[$i],$tmp);
$_REQUEST = array_merge($_REQUEST, $tmp);
}
}

//echo “\$_REQUEST = “;
//print_r($_REQUEST);

$backup_dir = ‘/var/backup’;
$www= ‘/var/www’;
$db=’/var/db/mysql’;
$etc= ‘/usr/local/etc’;
$dates = date(“Ymd");
$filename_www = $backup_dir.’/’.$dates.’www.tar.gz’;
$filename_db = $backup_dir.’/’.$dates.’db.tar.gz’;
$filename_etc = $backup_dir.’/’.$dates.’etc.tar.gz’;
$ftp_www = $dates.’www.tar.gz’;
$ftp_db = $dates.’db.tar.gz’;
$ftp_etc = $dates.’etc.tar.gz’;
if (file_exists($backup_dir)) {
echo “備份目錄存在 $filename 開始備份 www 備份到 $filename_www \n";
} else {
echo “備份目錄不存在 $backup_dir \n";
mkdir($backup_dir, 755);
echo “\n 備份目錄建立 開始備份 $www 備份到 $filename_www \n";
}
$run = ‘tar -zcpf ‘.$filename_www.’ ‘.$www.’ > /dev/null’;
$output = shell_exec($run);
echo “\n 備份資料庫 開始備份 $db 備份到 $filename_db \n";
$run = ‘/usr/local/etc/rc.d/mysql-server stop > /dev/null’;
$output = shell_exec($run);
echo “\n mysql 停止 \n";
$run = ‘tar -zcpf ‘.$filename_db.’ ‘.$db.’ > /dev/null’;
$output = shell_exec($run);
$run = ‘/usr/local/etc/rc.d/mysql-server start > /dev/null’;
$output = shell_exec($run);
echo “\n mysql 啟動 \n";
echo “\n 設定檔備份 $etc 備份到 $filename_etc \n";
$run = ‘tar -zcpf ‘.$filename_etc.’ ‘.$etc.’ > /dev/null’;
$output = shell_exec($run);

$ftp_server = “ip";
$ftp_user = “backup";
$ftp_passwd = “passwd";

echo “連線到 $ftp_server $ftp_user $ftp_passwd \n";
/* direct object methods */
$ftp =& new FTP();
if ($ftp->connect($ftp_server)) {
if ($ftp->login($ftp_user,$ftp_passwd)) {
echo “\n".$ftp->sysType() . “\n";
echo $ftp->pwd() . “\n";
$ftp->put($ftp_www,$filename_www );
$ftp->put($ftp_db,$filename_db );
$ftp->put($ftp_etc,$filename_etc );
} else {
echo “連線失敗: “;
print_r($ftp->error_no);
print_r($ftp->error_msg);
}
$ftp->disconnect();
$end=$ftp->lastLines;
} else {
echo “連線失敗: “;
print_r($ftp->error_no);
print_r($ftp->error_msg);
}
echo “$end \n";

?>