امتیاز موضوع:
  • 1 رأی - میانگین امتیازات: 4
  • 1
  • 2
  • 3
  • 4
  • 5
کلاس‌های مفید php
نویسنده پیام
babyy آفلاین
بازنشسته
*****

ارسال‌ها: 3,095
موضوع‌ها: 141
تاریخ عضویت: مرداد ۱۳۸۷

تشکرها : 35081
( 26090 تشکر در 9068 ارسال )
ارسال: #1
کلاس‌های مفید php
database-adapter برای کار با دیتاییس‌های SQL

مثال:

کد php:
<?php
require_once 'DbAdapter.php';
$connection = array ('dsn' => 'mysql:dbname=databasename;host=localhost'//dsn: data source name
 
'username' => 'root',
 
'password' => '',
 
 );

$dbObj = new DbAdapter($connection); //First of all creating an object 
$table 'book';

/* DEMO EXAMPLES
 * 
 * //SIMPLE SELECT
 * 1. $dbObj->select() //or select('*') || select("'field1',field2") || select(array('field1','field2'))
 ->from($table) // pass second argument as alias
 * ->fetch(); will select only one row || fetchAll () for all rows
 * 
 * 
 * //SELECT WITH WHERE
 * 2. $dbObj->select() 
 ->from($table)
 * ->where("field = 'value'") // or where(array('field'=>'value')) // Always put ANd between multiple condtions if array is passed
 * ->fetchAll();
 * 
 * //SELECT WITH FETCH MODE
 * 3. $dbObj->select(array('field1','field2')) 
 ->from($table)
 * ->setFetchMode('FETCH_OBJ') // set fetch mode for current operation see all AVAILABLE FETCH MODES in (INTERFACE DbAdapterInterface)
 * ->where(array('field'=>'value'))
 * ->fetchAll();
 * 
 * //INSERT A RECORD MANUALLY
 * 4. $dbObj->insert($table,array('field'=>'field_value'));
 * 
 * //INSERT A RECORD AUTOMATICALLY
 * 5. $dbObj->insert($table,$_POST,TRUE); // THIRD ARGUMENT SET TO TRUE FOR AUTO INSERT
 * 
 * //UPDATE A RECORD AUTOMATICALLY
 * 6. $dbObj->update($table,$_POST); // IF COMPLETE FORM IS POSTED WITH HIDDEN PRIMARY KEY THEN IT WILL AUTO UPDATE
 * 
 * 7. //UPDATE A RECORD MANUALLY
 * $dbObj->update($table,array('field'=>'field_value'),array('condition'=>'value')); 
 * 
 * 8. //DELETE RECORS
 * $dbObj->delete($table,array('key'=>'value'));
 * 
 * //Query
 * 9. $dbObj->query("SELECT * FROM $table")->fetch();
 * 
 * 
 * //GROUP BY,ORDER BY ,LIMIT
 * 10. $dbObj->select() 
 ->from($table)
 * ->orderBy('field1,field1') // or orderBy(array('field1','field2'))
 ->groupBy('field1') // or groupBy(array('field1','field2'))
 * ->limit('1') or limit('0,10')
 * ->fetchAll();
 * 
 * //JOIN (join type,table,join conditions)
 * 11. $dbObj->select(array('field1','field2')) 
 ->from(table1,'tbl1')
 ->join('left','table2 as tbl2','tbl1.id = tbl2.someid')
 ->join('left','table3 as tbl3','tbl2.someid = tbl3.someid')
 * ->fetchAll();
 * 
 * 
 * 12. //OR WHERE
 * $dbObj->select('*') 
 ->from(table1,'tbl1')
 * ->orWhere(array('field1'=>'value','field2'=>'value')) // Always put OR between multiple condtions if array is passed
 * ->fetchAll();
 * 
 * 13. //MIX OF ORWHERE AND WHERE
 * $dbObj->select('*') 
 ->from(table1,'tbl1')
 * ->where(array('field1'=>'value','field2'=>'value'))
 * ->orWhere(array('field1'=>'value','field2'=>'value')) // ALWAYS SHOULD BE USED AFTER WHERE OR STATND ALONE
 * ->fetchAll();
 * 
 * if orWhere is used with where then it will just put OR between two statement 
 * The syntex will create syntex below :
 * SELECT * FROM {table} where (table.field1 ='value' AND table.field1 ='value' ) OR (table.field1 ='value' AND table.field1 ='value' )
 * 
 * 14. OPERATOR USE
 * (A) <> OR != :- NOT EQUAL
 * (B) < :- LESS THAN
 * (C) > :- GREATOR THAN
 * (D) >= : GREATOR THAN EQUAL
 * (E) <= : LESS THAN EQUAL 
 * 
 * 
 * 
 */ 
 

 
$data $dbObj->select() 
 ->
from($table)
 ->
fetchAll();
 
 echo 
'<prE>';
 
print_r($data);
?>

دانلود
کلاس DbAdapterInterface.php :
کد php:
<?php 
   
/*  
    * @interface    : DbAdapterInterface 
    * @package      : DbAdapter 
    * @author       : Satyam Kumawat 
    * @version      : $id:1.0 
    */ 


interface DbAdapterInterface 

    const 
EXECEPTION 'Error Occured '
    
//const AUTO_INSERT = true; 
     
    /* FETCH TYPE*/ 
    
const FETCH_LAZY   =1
    const 
FETCH_ASSOC 2
    const 
FETCH_NUM   3
    const 
FETCH_BOTH  4
    const 
FETCH_OBJ   5
    
//const FETCH_BOUND = 6; 
    /** FETCH TYPE **/ 
     
    /* 
     @function  :connect 
     @params    :array config parameters as taken by PDO object 
     @return    :PDO connection object 
    */ 
    
public function connect($config); 
     
    
/* 
     @function  :select 
     @params    :Array of fields| String of fields | if none give then (*) is set 
     @return    :append select statement in query 
    */ 
    
public function select(); 
     
    
/* 
     @function  :delete 
     @params    :String table name,Array condtions| String conditions 
     @return    :no of affected row by given query 
    */ 
    
public function delete($table,$conditions=NULL); 
     
    
/* 
     @function  :insert 
     @params    :String table name,Array fields to be inserted, 
                 autoInsert(if set to true then direct pass [FORM VALUES ($_REQUEST)] and function will insert required column according to the table structure automatically) 
     @return    :last insert id 
    */ 
    
public function insert($table,$values,$autoInsert=false); 
     
    
/* 
     @function  :update 
     @params    :String table name,Array fields to be inserted, Array| String of condtions (if condtions in not given then it will search primary key in the given array values and updated the record automatically) 
                 
     @return    :last update record  id 
    */ 
    
public function update($table,$values,$conditions null); 
     
    
/* 
     @function  :query 
     @params    :Sting query (any sql statement) 
    */ 
    
public function query(); 
     
    
/* 
     @function  :fetch 
     @params    :null 
     @return    :first affected row 
    */ 
    
public function fetch(); 
     
     
    
/* 
     @function  :fetchAll 
     @params    :null 
     @return    :all affected row 
    */ 
    
public function fetchAll(); 
     
    
/* 
     @function  :where 
     @params    :Array of conditions | String of prepared condtions 
    */ 
    
public function where($cond); 
     
    
/* 
     @function  :orWhere 
     @params    :Array of conditions | String of prepared condtions 
    */ 
    
public function orWhere($cond); 
     
    
/* 
     @function  :where 
     @params    :Array of orderBy | String orderBy 
    */ 
    
public function orderBy($orderBy); 
     
    
/* 
     @function  :groupBy 
     @params    :Array of groupBy | String of groupBy  
    */ 
    
public function groupBy($groupBy); 
     
    
/* 
     @function  :where 
     @params    :String limit 
    */ 
    
public function limit($limit); 
     


?>
کلاس DbAdapter.php:
کد php:
<?php
   
/* 
    * @class    : DbAdapter
    * @package  : DbAdapter
    * @author   : Satyam Kumawat
    * @version  : $id:1.0
    */

require_once 'DbAdapterInterface.php';
class 
DbAdapter  implements DbAdapterInterface{
    
    private 
$select null;
    private 
$isConnected false;
    public  
$pdo null;
    private 
$fields = array();
    private 
$table null;
    private 
$where null;
    private 
$orWhere null;
    private 
$orderBy null;
    private 
$groupBy null;
    private 
$limit null;
    private 
$fetchmode self::FETCH_ASSOC;
    private 
$reflectionObj null;
    private 
$statementObj null;
    private 
$tblStructure null;
    private 
$primaryKey null;
    private 
$join null;
    
    public function 
__construct(array $config)
    {
        
$this->connect($config);
        
    }
    
    public function 
connect($config){
        
      if(!
$this->isConnected)
      {
              try{
                   
$connection = new PDO($config['dsn'],$config['username'],$config['password']);
                 
                 
$connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,self::FETCH_ASSOC);
                 
$connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
                 
                 
$this->pdo $connection;
                 
$this->isConnected true;
              } 
            catch (
Exception $e){
                 
$this->exceptionHandler($e);
                 exit;
              }
     }
           
      
      
    }
    public function 
buildSql(){
    
      
$sql   $this->select;
      
$sql  .= $this->fields;
      
      if(
is_null($this->table))
      {
            throw new 
AdapterException('Table is missing');
      }
      
      
$sql  .= $this->table;
      
      if(!
is_null($this->join)){
          
$sql .=$this->join;    
      }
      
      if(!
is_null($this->where)){
          
$sql  .= $this->where;
      }
      
      if(!
is_null($this->orWhere)){
          
$sql  .= $this->orWhere;
      }
      
      if(!
is_null($this->groupBy)){
          
$sql  .= $this->groupBy;
      }
      
       if(!
is_null($this->orderBy)){
          
$sql  .= $this->orderBy;
      }
       if(!
is_null($this->limit)){
          
$sql  .= $this->limit;
      }
          
      
$this->_destruct();
      
      return 
$sql;
    }

    public function 
select($fields ='*'){
        
    
      if(
is_null($this->select))    
        
$this->select  'SELECT ';
      
      if(
is_array($fields))
      {
          
        
$fieldString ="";
        foreach(
$fields as $key)
        {
            
$fieldString .= "`$key`,";
        }
        
$fieldString=substr($fieldString,0,-1); 
        
$this->fields $fieldString;
      }
      else 
      {
          
$this->fields $fields;
      }
  
      return 
$this;
      
    }
    
    public function 
insert($table,$values,$autoInsert false)
    {
         
$this->table $table;
        
        if(!
is_array($values))
        {
           throw new 
AdapterException('INSERT query require Array  ('.gettype($values).') given','general');
                       
        }
        
        
$sql  'INSERT INTO';
        
$sql .= $this->_padString($this->table);
        
$sql .= $this->_padString('SET');
        
        if(
$autoInsert)
        {
            
$columns $this->getTblStructure();
            foreach(
$values as $key =>$values)
            {
                if(
in_array($key$columns))
                
$sql .= "`$key` ='".mysql_real_escape_string($values)."',";
            }
            
        }
        else 
        {
               foreach(
$values as $key =>$values)
            {
                
$sql .= "`$key` ='".mysql_real_escape_string($values)."' ,";
            }
        }
        
$sql=substr($sql,0,-1); 
        
        if(
$this->execute($sql))
        {
            return 
$this->pdo->lastInsertId();
        }
        
            
    }
    
    public function 
update($table,$values,$conditions null)
    {
        
$this->table $table;
        if(!
is_array($values))
        {
           throw new 
AdapterException('Update query require Array  ('.gettype($values).') given','general');
                       
        }
        
        
$sql  'UPDATE';
        
$sql .= $this->_padString($table);
        
$sql .= $this->_padString('SET');
        
        if(
is_null($conditions))
        {
            
$primaryKey $this->getPrimaryKey();
            
$columns $this->getTblStructure();
            
            if(!(
$primaryValue $values["$primaryKey"]))
            {
               throw new 
AdapterException("Auto Update  Syntex  Require PRIMARY KEY  ($primaryKey)");
                           
            }
            
$keyCount 0;
            foreach(
$values as $key =>$value)
            {
                
$keyCount ++;
                
                if(
$key != $primaryKey && in_array($key$columns))
                 {
                     if(
$keyCount >)
                    {
                        
$sql .= ",";
                    }
                     
$sql .= "`$key`='".mysql_real_escape_string($value)."'";
                 }
            }
                
            
$sql .= $this->_padString("WHERE `$primaryKey` =".$primaryValue);
            
        }
        else 
        {
            
$keyCount =0;
               foreach(
$values as $key =>$values)
            {
                
$keyCount ++;
                if(
$keyCount >)
                {
                    
$sql .= ",";
                }
                
$sql .= "`$key` ='".mysql_real_escape_string($values)."'";
            }
            
            
            
$sql .= $this->_padString("WHERE");
            
            if(
is_array($conditions))
            {
                
$count =0;
                foreach(
$conditions as $key =>$val)
                {
                    
$count ++;
                    if(
$count >)
                    {
                        
$sql .= " AND ";
                    }
                    
$sql .= "`$key` ='$val'";
                    
                    
                }
        
            }
            else {
                
$sql .= $condtions;
            }
            
        }
        return 
$this->execute($sql);
        
    }
    
    public function 
getPrimaryKey()
    {
       
$sql ="SHOW KEYS FROM ".$this->table." WHERE Key_name = 'PRIMARY'";
       
$keyData $this->query($sql)->fetch(self::FETCH_ASSOC);
       
$this->primaryKey $keyData['Column_name'];
       return 
$this->primaryKey;
    }
    
    public function 
getTblStructure()
    {
         
//$this->table = 'book';
         
$sql $this->_padString('DESCRIBE');
         
$sql .= $this->table;
         
$this->query($sql);    
         
$columns =   $this->query($sql)->fetchAll(PDO::FETCH_COLUMN);
         
$this->tblStructure $columns;
         
         return 
$columns;
         
    }
    
    public function 
from($table,$alias=null){
        
        
$this->table " FROM $table as ".(is_null($alias) ? $table$alias);
        return 
$this;
    }
    
    public  function 
execute($sql){
        
        try{
            return 
$this->pdo->exec($sql);
       }
       catch(
PDOException $e)
       {
            
$exception = new AdapterException($e,'query');
         
$exception->throwException();
            
       }
    }
    
    public function 
fetch(){
        return  
$this->query()->fetch();
    }
    
    public function 
fetchAll(){
        
        
$data $this->query()->fetchAll();
        return 
$data;
        
    }
    
    
    public function 
query($sql=null)
    {
        if(
is_null($sql))
         
$sql $this->buildSql();
        
       try{
           
            
// $this->statementObj =  $this->pdo->query($sql);
          //return $this;
         
          
return $this->pdo->query($sql);
        
       }
       catch(
PDOException $e)
       {
            new 
AdapterException($e,'query');
        
            
       }
      
    }
    
    public function 
where($conditions =NULL)
    {
        if(
is_null($conditions))
        {
          return 
$this;    
        }
        
        
$where $this->_padString("WHERE ( ");
        
        
$count 0;
        if(
is_array($conditions))
        {
            foreach(
$conditions as $key =>$value){
                
$count++;
                if(
$count >1)
                {
                    
$where .=  $this->_padString("AND");
                }
                
               if(
$char $this->_searchSpecialchar($key))
                {
                    
$where .= "$key '$value'";
                }
                else{
                    
$where .= "$key= '$value'";
                }
            }
        }
        else 
        {
            
$where .= $conditions;
        }
        
$where .=  $this->_padString(")");;
        
        
$this->where $where;
        return 
$this;
        
    }
    
    public function 
orWhere($conditions)
    {
        if(
is_null($conditions))
        {
          return 
$this;    
        }
        
        
$onlyOR false;
        if(
is_null($this->where))
        {
            
$where $this->_padString("WHERE (");
            
$onlyOR true;
        }
        else {
            
$where $this->_padString("OR (");
        }
        
        
        
$count 0;
        if(
is_array($conditions))
        {
            foreach(
$conditions as $key =>$value)
            {
                
$count++;
                
$KeyWord = ($onlyOR) ? 'OR' :'AND';
                if(
$count >1)
                {
                    
$where .=  $this->_padString($KeyWord);
                }
                
                if(
$char $this->_searchSpecialchar($key))
                {
                    
$where .= "$key '$value'";
                }
                else{
                    
$where .= "$key= '$value'";
                }
            
            }
        }
        else 
        {
            
$where .= $conditions;
        }
        
$where .=  $this->_padString(")");;
        
        
$this->orWhere $where;
        return 
$this;
    }
    
    public function 
_searchSpecialchar($string)
    {
        if(
preg_match("/[<>>=<=!=]{2}|[><]{1}$/",trim($string),$match))
        {
            return 
$match[0];
        }
        else {
            return 
false;
        }
        
    }
    public function 
delete($table,$conditions=NULL)
    {
        return  
$this->_delete($table,$conditions);
       
    }
    
    private function 
_delete($table,$conditions)
    {
        
          
$sql   $this->_padString("DELETE FROM",2,'right');
          
$sql  .= $table;
          
          if(!
is_null($conditions)){
              
$sql  .=  $this->_padString("WHERE");
              
$sql  .= $conditions;
          }
         return 
$this->execute($sql);
    }
   
    public function 
setFetchMode($mode)
    {
        
$this->hasConstant($mode);
        
        
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,constant("self::$mode"));
        return 
$this;
    }
    public function 
join($type='left',$table=null,$joinCond=null)
    {
        if(
is_null($table)){
            throw new 
AdapterException('Join function required second arugment to be (String) table name (Null) given.');
        }
        if(
is_null($table)){
            throw new 
AdapterException('Join function required third arugment to be (String) join conditions  (Null) given.');
        }
        
       
$joinTitle $this->_padStringstrtoupper($type) .' '.'JOIN');
       
$statement =  $this->_padString($joinTitle) .$table .' ON'.$this->_padString($joinCond);
       if(
is_null($this->join)){
           
        
$this->join =  $statement ;
       }
       else {
           
$this->join .= $statement ;
       }
        
            
        return 
$this;
    }
    
    public function 
orderBy($orderBy)
    {
        if(
is_array($orderBy))
        {
              
$this->orderBy $this->_padString('ORDER BY').implode(',',$orderBy);
        }
        else {
            
            
$this->orderBy $this->_padString('ORDER BY'). $orderBy;
        }
        return 
$this;
    }
    
    public function 
groupBy($groupBy)
    {
        if(
is_array($groupBy))
        {
            
$this->groupBy $this->_padString('GROUP BY').implode(',',$groupBy);
        }
        else{
            
            
$this->groupBy $this->_padString('GROUP BY').$groupBy;
        }
        return 
$this;
    }
    
    public function 
limit($limit)
    {
        
$this->limit $this->_padString('limit') .$limit;
        return 
$this;
    }
    
    private function 
_padString($input,$pad_length=2,$type=null)
    {
        
$pad_length strlen($input) + $pad_length;
        
        switch (
$type
        {
            case 
'left':
                
$string str_pad($input,$pad_length," ",STR_PAD_LEFT);    
                break;
                
            case 
'right':
                
$string str_pad($input,$pad_length," ",STR_PAD_RIGHT);    
                break;
                
            default:
                 
$string str_pad($input,$pad_length," ",STR_PAD_BOTH);    
                break;
        }    
            
      return 
$string;
        
    }
    
    public function 
setAttribute($attribute,$value)
    {
        if(!
defined(@constant("PDO::$attribute")))
        {
            throw new 
Exception("Error Occured : PDO  attribute ($attribute) does not exists");
        }
        
        
$this->pdo->setAttribute(constant("PDO::$attribute"),$value);
        return 
$this;
    }

    
    private function 
hasProperty($property)
    {
        if(!
$this->reflectionObj)
        {
            
$reflect = new ReflectionClass($this);
            
$this->reflectionObj $reflect;
        }
        
        if(!
$this->reflectionObj->hasProperty($property))
        {
           throw new 
Exception(self::EXECEPTION .__CLASS__ ." does not have Property ($property) ");
        }    
        
    }
    private function 
hasConstant($constant)
    {
        if(!
$this->reflectionObj)
        {
            
$reflect = new ReflectionClass($this);
            
$this->reflectionObj $reflect;
        }
            
        if(!
$this->reflectionObj->hasConstant($constant))
        {
            throw new 
Exception(self::EXECEPTION .__CLASS__ ." does not have Constant ($constant)");
        }    
        
    }
    private function 
exceptionHandler($expectionobj)
    {
        
        
$message $expectionobj->getMessage();
        
$file    $expectionobj->getFile();
        
$line    $expectionobj->getLine();
        
        echo 
self::EXECEPTION.' <br>'.' Message : ' .$message .'<br>'.'File : '.$file.'<br>'.'Line No : '.$line;
    }
    
    
/* 
    * @function : __get
    * @use      : call everytime a property is access
    * @return   : property of a class if exists
    * @input    : property_name 
    */
     
    
public function __get($property)
    {
        if(
property_exists($this$property))
        {
            
$reflect = new ReflectionProperty($this,$property);
            if(
$reflect->isPrivate())
            {
                throw new 
Exception("Propety ($property) is private and not accesible outside the class");
            }
            else{
                return   
$this->{$property};
            }
        }else{
          throw new 
Exception("Propety ($property) not available in the class");
          
        }
    }
    public function 
__call($name,$args)
    {
        if(!
method_exists($this$name))
        {
            throw new 
Exception("Error Occured : function ($name) not exists");
        }
        else 
        {
            
//call_user_func_array($name, $arga);
        
}
    }
    private function 
_destruct()
    {
        
$this->table  null;
        
$this->select null;
        
$this->fields null;
        
$this->where  null;
    }
    
    


}
    
/* 
    * @class    : AdapterException
    * @package  : DbAdapter
    * @author   : Satyam Kumawat
    * @use      : For exception handling 
    * @version  : $id:1.0
    */
     
    
class AdapterException 
    
{
        const 
EXECP_HEADING'Error Occured';
        private 
$exceptionType;
        private 
$message;
        private 
$expectionObj;
        
        public function 
__construct($expectionObj,$type='general')
        {
         
            
$this->exceptionType $type;
            
            if(
is_object($expectionObj))
            {
                
$this->expectionObj $expectionObj;
                
$this->prepareExeception()->throwException();;
                
            }
            else{
                
                
$this->simpleException($expectionObj)->throwException();    
            }
            
        }
        public function 
throwException()
        {
            
$html  "<table width='800px' style='border:1px solid black;color:red;'><tr style='font-size:20px;'><td style='
            text-align:center'><b><u>"
.self::EXECP_HEADING."</u><b></td></tr>";
            
            foreach(
$this->message as $heading =>$data):
                
$html .="<tr><td><b><u>".ucwords($heading)." : </u></b>".$data."</td></tr>";
            endforeach;
            
            
$html .='</table>';
            echo 
$html;
            exit;
        }
        public function 
prepareExeception()
        {
           
$message = array();
            switch (
$this->exceptionType) {
                case 
'general':
                
                    
$message['message']  = $this->expectionObj->getMessage();
                    
$message['file']     =  $this->expectionObj->getFile();
                    
$message['line no']  = $this->expectionObj->getLine();
                    
                    break;
                    
                case 
'query':
                    
$message['message']  = $this->expectionObj->getMessage();
                    
$message['file']     =  $this->expectionObj->getFile();
                    
$message['line no']  = $this->expectionObj->getLine();
                    
$trace     $this->expectionObj->getTrace();
                    
                    
$message['query']  = $trace[0]['args'][0];
                    break;
            
                default:
                    
$message['message']  = $this->expectionObj->getMessage();
                    
$message['file']     =  $this->expectionObj->getFile();
                    
$message['line no']  = $this->expectionObj->getLine();
                    break;
            }
            
            
$this->message $message;
            return 
$this;
        }
        
        public function 
simpleException($msg)
        {
               
$message['message']  = $msg;
               
$this->message $message;
               return 
$this;
        }
        
    }

?>
(آخرین ویرایش در این ارسال: ۰۹-فروردین-۱۳۹۲, ۱۲:۵۵:۲۷، توسط hamed_Arfaee.)
۰۵-فروردین-۱۳۹۲, ۲۰:۴۱:۳۹
وب سایت ارسال‌ها
پاسخ
تشکر شده توسط : hadikh73, Ghoghnus, lord_viper, hamed_Arfaee, omid_phoenix, aKaReZa75, javaweb, Ambassador, liliamq60
hamed_Arfaee آفلاین
مدیر بخش
*****

ارسال‌ها: 1,334
موضوع‌ها: 231
تاریخ عضویت: تير ۱۳۸۳

تشکرها : 1250
( 2634 تشکر در 730 ارسال )
ارسال: #2
RE: کلاس‌های مفید php
سلام
من کلاس لایه دیتابیس"MYBB" رو خیلی دوست دارم
اینم خود کلاس و مثال های نحوه استفادش :
کد php:
<?php
/**
 * MyBB 1.6
 * Copyright 2010 MyBB Group, All Rights Reserved
 *
 * Website: http://mybb.com
 * License: http://mybb.com/about/license
 *
 * $Id$
 */

class DB_MySQLi
{
    
/**
     * The title of this layer.
     *
     * @var string
     */
    
public $title "MySQLi";
    
    
/**
     * The short title of this layer.
     *
     * @var string
     */
    
public $short_title "MySQLi";
    
    
/**
     * The type of db software being used.
     *
     * @var string
     */
    
public $type;

    
/**
     * A count of the number of queries.
     *
     * @var int
     */
    
public $query_count 0;

    
/**
     * A list of the performed queries.
     *
     * @var array
     */
    
public $querylist = array();

    
/**
     * 1 if error reporting enabled, 0 if disabled.
     *
     * @var boolean
     */
    
public $error_reporting 1;

    
/**
     * The read database connection resource.
     *
     * @var resource
     */
    
public $read_link;
    
    
/**
     * The write database connection resource
     *
     * @var resource
     */
    
public $write_link;
    
    
/**
     * Reference to the last database connection resource used.
     *
     * @var resource
     */
    
public $current_link;

    
/**
     * Explanation of a query.
     *
     * @var string
     */
    
public $explain;

    
/**
     * The current version of MySQL.
     *
     * @var string
     */
    
public $version;

    
/**
     * The current table type in use (myisam/innodb)
     *
     * @var string
     */
    
public $table_type "myisam";

    
/**
     * The table prefix used for simple select, update, insert and delete queries
     *
     * @var string
     */
    
public $table_prefix;
    
    
/**
     * The extension used to run the SQL database
     *
     * @var string
     */
    
public $engine "mysqli";
    
    
/**
     * Weather or not this engine can use the search functionality
     *
     * @var boolean
     */
    
public $can_search true;

    
/**
     * The database encoding currently in use (if supported)
     *
     * @var string
     */
    
public $db_encoding "utf8";

    
/**
     * The time spent performing queries
     *
     * @var float
     */
    
public $query_time 0;

    
/**
     * Connect to the database server.
     *
     * @param array Array of DBMS connection details.
     * @return resource The DB connection resource. Returns false on fail or -1 on a db connect failure.
     */
    
function connect($config)
    {
        
// Simple connection to one server
        
if(array_key_exists('hostname'$config))
        {
            
$connections['read'][] = $config;
        }
        else
        
// Connecting to more than one server
        
{
            
// Specified multiple servers, but no specific read/write servers
            
if(!array_key_exists('read'$config))
            {
                foreach(
$config as $key => $settings)
                {
                    if(
is_int($key)) $connections['read'][] = $settings;
                }
            }
            
// Specified both read & write servers
            
else
            {
                
$connections $config;
            }
        }

        
$this->db_encoding $config['encoding'];

        
// Actually connect to the specified servers
        
foreach(array('read''write') as $type)
        {
            if(!
is_array($connections[$type]))
            {
                break;
            }
            
            if(
array_key_exists('hostname'$connections[$type]))
            {
                
$details $connections[$type];
                unset(
$connections);
                
$connections[$type][] = $details;
            }

            
// Shuffle the connections
            
shuffle($connections[$type]);

            
// Loop-de-loop
            
foreach($connections[$type] as $single_connection)
            {
                
$connect_function "mysqli_connect";
                
$persist "";
                if(
$single_connection['pconnect'] && version_compare(PHP_VERSION'5.3.0''>='))
                {
                    
$persist "p:";
                }
                
                
$link $type."_link";

                
$this->get_execution_time();

                
// Specified a custom port for this connection?
                
list($hostname$port) = explode(":"$single_connection['hostname'], 2);
                if(
$port)
                {
                    
$this->$link = @$connect_function($persist.$hostname$single_connection['username'], $single_connection['password'], ""$port);
                }
                else
                {
                    
$this->$link = @$connect_function($persist.$single_connection['hostname'], $single_connection['username'], $single_connection['password']);
                }

                
$time_spent $this->get_execution_time();
                
$this->query_time += $time_spent;

                
// Successful connection? break down brother!
                
if($this->$link)
                {
                    
$this->connections[] = "[".strtoupper($type)."] {$single_connection['username']}@{$single_connection['hostname']} (Connected in ".number_format($time_spent0)."s)";
                    break;
                }
                else
                {
                    
$this->connections[] = "<span style=\"color: red\">[FAILED] [".strtoupper($type)."] {$single_connection['username']}@{$single_connection['hostname']}</span>";
                }
            }
        }

        
// No write server was specified (simple connection or just multiple servers) - mirror write link
        
if(!array_key_exists('write'$connections))
        {
            
$this->write_link = &$this->read_link;
        }

        
// Have no read connection?
        
if(!$this->read_link)
        {
            
$this->error("[READ] Unable to connect to MySQL server");
            return 
false;
        }
        
// No write?
        
else if(!$this->write_link)
        {
            
$this->error("[WRITE] Unable to connect to MySQL server");
            return 
false;
        }

        
// Select databases
        
if(!$this->select_db($config['database']))
        {
            return -
1;
        }

        
$this->current_link = &$this->read_link;
        return 
$this->read_link;
    }

    
/**
     * Selects the database to use.
     *
     * @param string The database name.
     * @return boolean True when successfully connected, false if not.
     */
    
function select_db($database)
    {
        global 
$mybb;
        
        
$master_success = @mysqli_select_db($this->read_link$database) or $this->error("[READ] Unable to select database"$this->read_link);
        if(
$this->write_link)
        {
            
$slave_success = @mysqli_select_db($this->write_link$database) or $this->error("[WRITE] Unable to select slave database"$this->write_link);
            
            
$success = ($master_success && $slave_success true false);
        }
        else
        {
            
$success $master_success;
        }
        
        if(
$success && $this->db_encoding)
        {
            
$this->query("SET NAMES '{$this->db_encoding}'");
            
            if(
$slave_success && count($this->connections) > 1)
            {
                
$this->write_query("SET NAMES '{$this->db_encoding}'");
            }
        }
        return 
$success;
    }

    
/**
     * Query the database.
     *
     * @param string The query SQL.
     * @param boolean 1 if hide errors, 0 if not.
     * @param integer 1 if executes on slave database, 0 if not.
     * @return resource The query data.
     */
    
function query($string$hide_errors=0$write_query=0)
    {
        global 
$pagestarttime$db$mybb;

        
$this->get_execution_time();

        
// Only execute write queries on slave server
        
if($write_query && $this->write_link)
        {
            
$this->current_link = &$this->write_link;
            
$query = @mysqli_query($this->write_link$string);
        }
        else
        {
            
$this->current_link = &$this->read_link;
            
$query = @mysqli_query($this->read_link$string);
        }

        if(
$this->error_number() && !$hide_errors)
        {
            
$this->error($string);
            exit;
        }
        
        
$query_time $this->get_execution_time();
        
$this->query_time += $query_time;
        
$this->query_count++;
        
        if(
$mybb->debug_mode)
        {
            
$this->explain_query($string$query_time);
        }
        return 
$query;
    }
    
    
/**
     * Execute a write query on the slave database
     *
     * @param string The query SQL.
     * @param boolean 1 if hide errors, 0 if not.
     * @return resource The query data.
     */
    
function write_query($query$hide_errors=0)
    {
        return 
$this->query($query$hide_errors1);
    }

    
/**
     * Explain a query on the database.
     *
     * @param string The query SQL.
     * @param string The time it took to perform the query.
     */
    
function explain_query($string$qtime)
    {
        global 
$plugins;
        if(
$plugins->current_hook)
        {
            
$debug_extra "<div style=\"float_right\">(Plugin Hook: {$plugins->current_hook})</div>";
        }
        if(
preg_match("#^\s*select#i"$string))
        {
            
$query mysqli_query($this->current_link"EXPLAIN $string");
            
$this->explain .= "<table style=\"background-color: #666;\" width=\"95%\" cellpadding=\"4\" cellspacing=\"1\" align=\"center\">\n".
                
"<tr>\n".
                
"<td colspan=\"8\" style=\"background-color: #ccc;\">{$debug_extra}<div><strong>#".$this->query_count." - Select Query</strong></div></td>\n".
                
"</tr>\n".
                
"<tr>\n".
                
"<td colspan=\"8\" style=\"background-color: #fefefe;\"><span style=\"font-family: Courier; font-size: 14px;\">".$string."</span></td>\n".
                
"</tr>\n".
                
"<tr style=\"background-color: #efefef;\">\n".
                
"<td><strong>table</strong></td>\n".
                
"<td><strong>type</strong></td>\n".
                
"<td><strong>possible_keys</strong></td>\n".
                
"<td><strong>key</strong></td>\n".
                
"<td><strong>key_len</strong></td>\n".
                
"<td><strong>ref</strong></td>\n".
                
"<td><strong>rows</strong></td>\n".
                
"<td><strong>Extra</strong></td>\n".
                
"</tr>\n";

            while(
$table mysqli_fetch_assoc($query))
            {
                
$this->explain .=
                    
"<tr bgcolor=\"#ffffff\">\n".
                    
"<td>".$table['table']."</td>\n".
                    
"<td>".$table['type']."</td>\n".
                    
"<td>".$table['possible_keys']."</td>\n".
                    
"<td>".$table['key']."</td>\n".
                    
"<td>".$table['key_len']."</td>\n".
                    
"<td>".$table['ref']."</td>\n".
                    
"<td>".$table['rows']."</td>\n".
                    
"<td>".$table['Extra']."</td>\n".
                    
"</tr>\n";
            }
            
$this->explain .=
                
"<tr>\n".
                
"<td colspan=\"8\" style=\"background-color: #fff;\">Query Time: ".$qtime."</td>\n".
                
"</tr>\n".
                
"</table>\n".
                
"<br />\n";
        }
        else
        {
            
$this->explain .= "<table style=\"background-color: #666;\" width=\"95%\" cellpadding=\"4\" cellspacing=\"1\" align=\"center\">\n".
                
"<tr>\n".
                
"<td style=\"background-color: #ccc;\">{$debug_extra}<div><strong>#".$this->query_count." - Write Query</strong></div></td>\n".
                
"</tr>\n".
                
"<tr style=\"background-color: #fefefe;\">\n".
                
"<td><span style=\"font-family: Courier; font-size: 14px;\">".htmlspecialchars_uni($string)."</span></td>\n".
                
"</tr>\n".
                
"<tr>\n".
                
"<td bgcolor=\"#ffffff\">Query Time: ".$qtime."</td>\n".
                
"</tr>\n".
                
"</table>\n".
                
"<br />\n";
        }

        
$this->querylist[$this->query_count]['query'] = $string;
        
$this->querylist[$this->query_count]['time'] = $qtime;
    }


    
/**
     * Return a result array for a query.
     *
     * @param resource The query data.
     * @param constant The type of array to return.
     * @return array The array of results.
     */
    
function fetch_array($query)
    {
        
$array mysqli_fetch_assoc($query);
        return 
$array;
    }

    
/**
     * Return a specific field from a query.
     *
     * @param resource The query ID.
     * @param string The name of the field to return.
     * @param int The number of the row to fetch it from.
     */
    
function fetch_field($query$field$row=false)
    {
        if(
$row !== false)
        {
            
$this->data_seek($query$row);
        }
        
$array $this->fetch_array($query);
        return 
$array[$field];
    }

    
/**
     * Moves internal row pointer to the next row
     *
     * @param resource The query ID.
     * @param int The pointer to move the row to.
     */
    
function data_seek($query$row)
    {
        return 
mysqli_data_seek($query$row);
    }

    
/**
     * Return the number of rows resulting from a query.
     *
     * @param resource The query data.
     * @return int The number of rows in the result.
     */
    
function num_rows($query)
    {
        return 
mysqli_num_rows($query);
    }

    
/**
     * Return the last id number of inserted data.
     *
     * @return int The id number.
     */
    
function insert_id()
    {
        
$id mysqli_insert_id($this->current_link);
        return 
$id;
    }

    
/**
     * Close the connection with the DBMS.
     *
     */
    
function close()
    {
        @
mysqli_close($this->read_link);
        if(
$this->write_link)
        {
            @
mysqli_close($this->write_link);
        }
    }

    
/**
     * Return an error number.
     *
     * @return int The error number of the current error.
     */
    
function error_number()
    {
        if(
$this->current_link)
        {
            return 
mysqli_errno($this->current_link);            
        }
        else
        {
            return 
mysqli_connect_errno();
        }
    }

    
/**
     * Return an error string.
     *
     * @return string The explanation for the current error.
     */
    
function error_string()
    {
        if(
$this->current_link)
        {
            return 
mysqli_error($this->current_link);            
        }
        else
        {
            return 
mysqli_connect_error();
        }
    }

    
/**
     * Output a database error.
     *
     * @param string The string to present as an error.
     */
    
function error($string="")
    {
        if(
$this->error_reporting)
        {
            if(
class_exists("errorHandler"))
            {
                global 
$error_handler;
                
                if(!
is_object($error_handler))
                {
                    require_once 
MYBB_ROOT."inc/class_error.php";
                    
$error_handler = new errorHandler();
                }
                
                
$error = array(
                    
"error_no" => $this->error_number(),
                    
"error" => $this->error_string(),
                    
"query" => $string
                
);
                
$error_handler->error(MYBB_SQL$error);
            }
            else
            {
                
trigger_error("<strong>[SQL] [".$this->error_number()."] ".$this->error_string()."</strong><br />{$string}"E_USER_ERROR);
            }
        }
        else
        {
            return 
false;
        }
    }


    
/**
     * Returns the number of affected rows in a query.
     *
     * @return int The number of affected rows.
     */
    
function affected_rows()
    {
        return 
mysqli_affected_rows($this->current_link);
    }


    
/**
     * Return the number of fields.
     *
     * @param resource The query data.
     * @return int The number of fields.
     */
    
function num_fields($query)
    {
        return 
mysqli_num_fields($query);
    }

    
/**
     * Lists all functions in the database.
     *
     * @param string The database name.
     * @param string Prefix of the table (optional)
     * @return array The table list.
     */
    
function list_tables($database$prefix='')
    {
        if(
$prefix)
        {
            
$query $this->query("SHOW TABLES FROM `$database` LIKE '".$this->escape_string($prefix)."%'");
        }
        else
        {
            
$query $this->query("SHOW TABLES FROM `$database`");
        }
        
        while(list(
$table) = mysqli_fetch_array($query))
        {
            
$tables[] = $table;
        }
        return 
$tables;
    }

    
/**
     * Check if a table exists in a database.
     *
     * @param string The table name.
     * @return boolean True when exists, false if not.
     */
    
function table_exists($table)
    {
        
// Execute on master server to ensure if we've just created a table that we get the correct result
        
$query $this->write_query("
            SHOW TABLES 
            LIKE '
{$this->table_prefix}$table'
        "
);
        
$exists $this->num_rows($query);
        
        if(
$exists 0)
        {
            return 
true;
        }
        else
        {
            return 
false;
        }
    }

    
/**
     * Check if a field exists in a database.
     *
     * @param string The field name.
     * @param string The table name.
     * @return boolean True when exists, false if not.
     */
    
function field_exists($field$table)
    {
        
$query $this->write_query("
            SHOW COLUMNS 
            FROM 
{$this->table_prefix}$table 
            LIKE '
$field'
        "
);
        
$exists $this->num_rows($query);
        
        if(
$exists 0)
        {
            return 
true;
        }
        else
        {
            return 
false;
        }
    }

    
/**
     * Add a shutdown query.
     *
     * @param resource The query data.
     * @param string An optional name for the query.
     */
    
function shutdown_query($query$name=0)
    {
        global 
$shutdown_queries;
        if(
$name)
        {
            
$shutdown_queries[$name] = $query;
        }
        else
        {
            
$shutdown_queries[] = $query;
        }
    }

    
/**
     * Performs a simple select query.
     *
     * @param string The table name to be queried.
     * @param string Comma delimetered list of fields to be selected.
     * @param string SQL formatted list of conditions to be matched.
     * @param array List of options, order by, order direction, limit, limit start.
     * @return resource The query data.
     */
    
    
function simple_select($table$fields="*"$conditions=""$options=array())
    {
        
$query "SELECT ".$fields." FROM ".$this->table_prefix.$table;
        
        if(
$conditions != "")
        {
            
$query .= " WHERE ".$conditions;
        }
        
        if(isset(
$options['order_by']))
        {
            
$query .= " ORDER BY ".$options['order_by'];
            if(isset(
$options['order_dir']))
            {
                
$query .= " ".my_strtoupper($options['order_dir']);
            }
        }
        
        if(isset(
$options['limit_start']) && isset($options['limit']))
        {
            
$query .= " LIMIT ".$options['limit_start'].", ".$options['limit'];
        }
        else if(isset(
$options['limit']))
        {
            
$query .= " LIMIT ".$options['limit'];
        }
        
        return 
$this->query($query);
    }
    
    
/**
     * Build an insert query from an array.
     *
     * @param string The table name to perform the query on.
     * @param array An array of fields and their values.
     * @return int The insert ID if available
     */
    
function insert_query($table$array)
    {
        if(!
is_array($array))
        {
            return 
false;
        }
        
$fields "`".implode("`,`"array_keys($array))."`";
        
$values implode("','"$array);
        
$this->write_query("
            INSERT 
            INTO 
{$this->table_prefix}{$table} (".$fields.") 
            VALUES ('"
.$values."')
        "
);
        return 
$this->insert_id();
    }
    
    
/**
     * Build one query for multiple inserts from a multidimensional array.
     *
     * @param string The table name to perform the query on.
     * @param array An array of inserts.
     * @return int The insert ID if available
     */
    
function insert_query_multiple($table$array)
    {
        if(!
is_array($array))
        {
            return 
false;
        }
        
// Field names
        
$fields array_keys($array[0]);
        
$fields "`".implode("`,`"$fields)."`";

        
$insert_rows = array();
        foreach(
$array as $values)
        {
            
$insert_rows[] = "('".implode("','"$values)."')";
        }
        
$insert_rows implode(", "$insert_rows);

        
$this->write_query("
            INSERT 
            INTO 
{$this->table_prefix}{$table} ({$fields}
            VALUES 
{$insert_rows}
        "
);
    }

    
/**
     * Build an update query from an array.
     *
     * @param string The table name to perform the query on.
     * @param array An array of fields and their values.
     * @param string An optional where clause for the query.
     * @param string An optional limit clause for the query.
     * @param boolean An option to quote incoming values of the array.
     * @return resource The query data.
     */
    
function update_query($table$array$where=""$limit=""$no_quote=false)
    {
        if(!
is_array($array))
        {
            return 
false;
        }
        
        
$comma "";
        
$query "";
        
$quote "'";
        
        if(
$no_quote == true)
        {
            
$quote "";
        }
        
        foreach(
$array as $field => $value)
        {
            
$query .= $comma."`".$field."`={$quote}{$value}{$quote}";
            
$comma ', ';
        }
        
        if(!empty(
$where))
        {
            
$query .= " WHERE $where";
        }
        
        if(!empty(
$limit))
        {
            
$query .= " LIMIT $limit";
        }

        return 
$this->write_query("
            UPDATE 
{$this->table_prefix}$table
            SET 
$query
        "
);
    }

    
/**
     * Build a delete query.
     *
     * @param string The table name to perform the query on.
     * @param string An optional where clause for the query.
     * @param string An optional limit clause for the query.
     * @return resource The query data.
     */
    
function delete_query($table$where=""$limit="")
    {
        
$query "";
        if(!empty(
$where))
        {
            
$query .= " WHERE $where";
        }
        if(!empty(
$limit))
        {
            
$query .= " LIMIT $limit";
        }
        return 
$this->write_query("DELETE FROM {$this->table_prefix}$table $query");
    }

    
/**
     * Escape a string according to the MySQL escape format.
     *
     * @param string The string to be escaped.
     * @return string The escaped string.
     */
    
function escape_string($string)
    {
        if(
function_exists("mysqli_real_escape_string") && $this->read_link)
        {
            
$string mysqli_real_escape_string($this->read_link$string);
        }
        else
        {
            
$string addslashes($string);
        }
        return 
$string;
    }
    
    
/**
     * Frees the resources of a MySQLi query.
     *
     * @param object The query to destroy.
     * @return boolean Returns true on success, false on faliure
     */
    
function free_result($query)
    {
        return 
mysqli_free_result($query);
    }
    
    
/**
     * Escape a string used within a like command.
     *
     * @param string The string to be escaped.
     * @return string The escaped string.
     */
    
function escape_string_like($string)
    {
        return 
$this->escape_string(str_replace(array('%''_') , array('\\%' '\\_') , $string));
    }

    
/**
     * Gets the current version of MySQL.
     *
     * @return string Version of MySQL.
     */
    
function get_version()
    {
        if(
$this->version)
        {
            return 
$this->version;
        }
        
$query $this->query("SELECT VERSION() as version");
        
$ver $this->fetch_array($query);
        if(
$ver['version'])
        {
            
$version explode("."$ver['version'], 3);
            
$this->version intval($version[0]).".".intval($version[1]).".".intval($version[2]);
        }
        return 
$this->version;
    }

    
/**
     * Optimizes a specific table.
     *
     * @param string The name of the table to be optimized.
     */
    
function optimize_table($table)
    {
        
$this->write_query("OPTIMIZE TABLE ".$this->table_prefix.$table."");
    }
    
    
/**
     * Analyzes a specific table.
     *
     * @param string The name of the table to be analyzed.
     */
    
function analyze_table($table)
    {
        
$this->write_query("ANALYZE TABLE ".$this->table_prefix.$table."");
    }

    
/**
     * Show the "create table" command for a specific table.
     *
     * @param string The name of the table.
     * @return string The MySQL command to create the specified table.
     */
    
function show_create_table($table)
    {
        
$query $this->write_query("SHOW CREATE TABLE ".$this->table_prefix.$table."");
        
$structure $this->fetch_array($query);
        
        return 
$structure['Create Table'];
    }

    
/**
     * Show the "show fields from" command for a specific table.
     *
     * @param string The name of the table.
     * @return string Field info for that table
     */
    
function show_fields_from($table)
    {
        
$query $this->write_query("SHOW FIELDS FROM ".$this->table_prefix.$table."");
        while(
$field $this->fetch_array($query))
        {
            
$field_info[] = $field;
        }
        return 
$field_info;
    }

    
/**
     * Returns whether or not the table contains a fulltext index.
     *
     * @param string The name of the table.
     * @param string Optionally specify the name of the index.
     * @return boolean True or false if the table has a fulltext index or not.
     */
    
function is_fulltext($table$index="")
    {
        
$structure $this->show_create_table($table);
        if(
$index != "")
        {
            if(
preg_match("#FULLTEXT KEY (`?)$index(`?)#i"$structure))
            {
                return 
true;
            }
            else
            {
                return 
false;
            }
        }
        if(
preg_match('#FULLTEXT KEY#i'$structure))
        {
            return 
true;
        }
        return 
false;
    }

    
/**
     * Returns whether or not this database engine supports fulltext indexing.
     *
     * @param string The table to be checked.
     * @return boolean True or false if supported or not.
     */

    
function supports_fulltext($table)
    {
        
$version $this->get_version();
        
$query $this->write_query("SHOW TABLE STATUS LIKE '{$this->table_prefix}$table'");
        
$status $this->fetch_array($query);
        
$table_type my_strtoupper($status['Engine']);
        if(
$version >= '3.23.23' && $table_type == 'MYISAM')
        {
            return 
true;
        }
        return 
false;
    }

    
/**
     * Returns whether or not this database engine supports boolean fulltext matching.
     *
     * @param string The table to be checked.
     * @return boolean True or false if supported or not.
     */
    
function supports_fulltext_boolean($table)
    {
        
$version $this->get_version();
        
$supports_fulltext $this->supports_fulltext($table);
        if(
$version >= '4.0.1' && $supports_fulltext == true)
        {
            return 
true;
        }
        return 
false;
    }
    
    
/**
     * Checks to see if an index exists on a specified table
     *
     * @param string The name of the table.
     * @param string The name of the index.
     */
    
function index_exists($table$index)
    {
        
$index_exists false;
        
$query $this->write_query("SHOW INDEX FROM {$this->table_prefix}{$table}");
        while(
$ukey $this->fetch_array($query))
        {
            if(
$ukey['Key_name'] == $index)
            {
                
$index_exists true;
                break;
            }
        }
        
        if(
$index_exists)
        {
            return 
true;
        }
        
        return 
false;
    }

    
/**
     * Creates a fulltext index on the specified column in the specified table with optional index name.
     *
     * @param string The name of the table.
     * @param string Name of the column to be indexed.
     * @param string The index name, optional.
     */
    
function create_fulltext_index($table$column$name="")
    {
        
$this->write_query("ALTER TABLE {$this->table_prefix}$table ADD FULLTEXT $name ($column)");
    }

    
/**
     * Drop an index with the specified name from the specified table
     *
     * @param string The name of the table.
     * @param string The name of the index.
     */
    
function drop_index($table$name)
    {
        
$this->write_query("ALTER TABLE {$this->table_prefix}$table DROP INDEX $name");
    }
    
    
/**
     * Drop an table with the specified table
     *
     * @param boolean hard drop - no checking
     * @param boolean use table prefix
     */
    
function drop_table($table$hard=false$table_prefix=true)
    {
        if(
$table_prefix == false)
        {
            
$table_prefix "";
        }
        else
        {
            
$table_prefix $this->table_prefix;
        }
        
        if(
$hard == false)
        {
            
$this->write_query('DROP TABLE IF EXISTS '.$table_prefix.$table);
        }
        else
        {
            
$this->write_query('DROP TABLE '.$table_prefix.$table);
        }
    }
    
    
/**
     * Replace contents of table with values
     *
     * @param string The table
     * @param array The replacements
     */
    
function replace_query($table$replacements=array())
    {
        
$values '';
        
$comma '';
        foreach(
$replacements as $column => $value)
        {
            
$values .= $comma."`".$column."`='".$value."'";
            
            
$comma ',';
        }
        
        if(empty(
$replacements))
        {
             return 
false;
        }
        
        return 
$this->write_query("REPLACE INTO {$this->table_prefix}{$table} SET {$values}");
    }
    
    
/**
     * Drops a column
     *
     * @param string The table
     * @param string The column name
     */
    
function drop_column($table$column)
    {
        return 
$this->write_query("ALTER TABLE {$this->table_prefix}{$table} DROP {$column}");
    }
    
    
/**
     * Adds a column
     *
     * @param string The table
     * @param string The column name
     * @param string the new column definition
     */
    
function add_column($table$column$definition)
    {
        return 
$this->write_query("ALTER TABLE {$this->table_prefix}{$table} ADD {$column} {$definition}");
    }
    
    
/**
     * Modifies a column
     *
     * @param string The table
     * @param string The column name
     * @param string the new column definition
     */
    
function modify_column($table$column$new_definition)
    {
        return 
$this->write_query("ALTER TABLE {$this->table_prefix}{$table} MODIFY {$column} {$new_definition}");
    }
    
    
/**
     * Renames a column
     *
     * @param string The table
     * @param string The old column name
     * @param string the new column name
     * @param string the new column definition
     */
    
function rename_column($table$old_column$new_column$new_definition)
    {
        return 
$this->write_query("ALTER TABLE {$this->table_prefix}{$table} CHANGE {$old_column} {$new_column} {$new_definition}");
    }

    
/**
     * Sets the table prefix used by the simple select, insert, update and delete functions
     *
     * @param string The new table prefix
     */
    
function set_table_prefix($prefix)
    {
        
$this->table_prefix $prefix;
    }
    
    
/**
     * Fetched the total size of all mysql tables or a specific table
     *
     * @param string The table (optional)
     * @return integer the total size of all mysql tables or a specific table
     */
    
function fetch_size($table='')
    {
        if(
$table != '')
        {
            
$query $this->query("SHOW TABLE STATUS LIKE '".$this->table_prefix.$table."'");
        }
        else
        {
            
$query $this->query("SHOW TABLE STATUS");
        }
        
$total 0;
        while(
$table $this->fetch_array($query))
        {
            
$total += $table['Data_length']+$table['Index_length'];
        }
        return 
$total;
    }

    
/**
     * Fetch a list of database character sets this DBMS supports
     *
     * @return array Array of supported character sets with array key being the name, array value being display name. False if unsupported
     */
    
function fetch_db_charsets()
    {
        if(
$this->link && version_compare($this->get_version(), "4.1""<"))
        {
            return 
false;
        }
        return array(
            
'big5' => 'Big5 Traditional Chinese',
            
'dec8' => 'DEC West European',
            
'cp850' => 'DOS West European',
            
'hp8' => 'HP West European',
            
'koi8r' => 'KOI8-R Relcom Russian',
            
'latin1' => 'cp1252 West European',
            
'latin2' => 'ISO 8859-2 Central European',
            
'swe7' => '7bit Swedish',
            
'ascii' => 'US ASCII',
            
'ujis' => 'EUC-JP Japanese',
            
'sjis' => 'Shift-JIS Japanese',
            
'hebrew' => 'ISO 8859-8 Hebrew',
            
'tis620' => 'TIS620 Thai',
            
'euckr' => 'EUC-KR Korean',
            
'koi8u' => 'KOI8-U Ukrainian',
            
'gb2312' => 'GB2312 Simplified Chinese',
            
'greek' => 'ISO 8859-7 Greek',
            
'cp1250' => 'Windows Central European',
            
'gbk' => 'GBK Simplified Chinese',
            
'latin5' => 'ISO 8859-9 Turkish',
            
'armscii8' => 'ARMSCII-8 Armenian',
            
'utf8' => 'UTF-8 Unicode',
            
'ucs2' => 'UCS-2 Unicode',
            
'cp866' => 'DOS Russian',
            
'keybcs2' => 'DOS Kamenicky Czech-Slovak',
            
'macce' => 'Mac Central European',
            
'macroman' => 'Mac West European',
            
'cp852' => 'DOS Central European',
            
'latin7' => 'ISO 8859-13 Baltic',
            
'cp1251' => 'Windows Cyrillic',
            
'cp1256' => 'Windows Arabic',
            
'cp1257' => 'Windows Baltic',
            
'binary' => 'Binary pseudo charset',
            
'geostd8' => 'GEOSTD8 Georgian',
            
'cp932' => 'SJIS for Windows Japanese',
            
'eucjpms' => 'UJIS for Windows Japanese',
        );
    }

    
/**
     * Fetch a database collation for a particular database character set
     *
     * @param string The database character set
     * @return string The matching database collation, false if unsupported
     */
    
function fetch_charset_collation($charset)
    {
        
$collations = array(
            
'big5' => 'big5_chinese_ci',
            
'dec8' => 'dec8_swedish_ci',
            
'cp850' => 'cp850_general_ci',
            
'hp8' => 'hp8_english_ci',
            
'koi8r' => 'koi8r_general_ci',
            
'latin1' => 'latin1_swedish_ci',
            
'latin2' => 'latin2_general_ci',
            
'swe7' => 'swe7_swedish_ci',
            
'ascii' => 'ascii_general_ci',
            
'ujis' => 'ujis_japanese_ci',
            
'sjis' => 'sjis_japanese_ci',
            
'hebrew' => 'hebrew_general_ci',
            
'tis620' => 'tis620_thai_ci',
            
'euckr' => 'euckr_korean_ci',
            
'koi8u' => 'koi8u_general_ci',
            
'gb2312' => 'gb2312_chinese_ci',
            
'greek' => 'greek_general_ci',
            
'cp1250' => 'cp1250_general_ci',
            
'gbk' => 'gbk_chinese_ci',
            
'latin5' => 'latin5_turkish_ci',
            
'armscii8' => 'armscii8_general_ci',
            
'utf8' => 'utf8_general_ci',
            
'ucs2' => 'ucs2_general_ci',
            
'cp866' => 'cp866_general_ci',
            
'keybcs2' => 'keybcs2_general_ci',
            
'macce' => 'macce_general_ci',
            
'macroman' => 'macroman_general_ci',
            
'cp852' => 'cp852_general_ci',
            
'latin7' => 'latin7_general_ci',
            
'cp1251' => 'cp1251_general_ci',
            
'cp1256' => 'cp1256_general_ci',
            
'cp1257' => 'cp1257_general_ci',
            
'binary' => 'binary',
            
'geostd8' => 'geostd8_general_ci',
            
'cp932' => 'cp932_japanese_ci',
            
'eucjpms' => 'eucjpms_japanese_ci',
        );
        if(
$collations[$charset])
        {
            return 
$collations[$charset];
        }
        return 
false;
    }

    
/**
     * Fetch a character set/collation string for use with CREATE TABLE statements. Uses current DB encoding
     *
     * @return string The built string, empty if unsupported
     */
    
function build_create_table_collation()
    {
        if(!
$this->db_encoding)
        {
            return 
'';
        }

        
$collation $this->fetch_charset_collation($this->db_encoding);
        if(!
$collation)
        {
            return 
'';
        }
        return 
" CHARACTER SET {$this->db_encoding} COLLATE {$collation}";
    }

    
/**
     * Time how long it takes for a particular piece of code to run. Place calls above & below the block of code.
     *
     * @return float The time taken
     */
    
function get_execution_time()
    {
        static 
$time_start;

        
$time microtime(true);


        
// Just starting timer, init and return
        
if(!$time_start)
        {
            
$time_start $time;
            return;
        }
        
// Timer has run, return execution time
        
else
        {
            
$total $time-$time_start;
            if(
$total 0$total 0;
            
$time_start 0;
            return 
$total;
        }
    }
}

?>
آماده سازی (ساخت شی و تنظیمات کانکشن :
کد php:
<?php

error_reporting
(E_ALL E_NOTICE);

require_once 
"db_mysqli.php";

$config['database']['type'] = 'mysqli';
$config['database']['database'] = 'db1';
$config['database']['table_prefix'] = '';
$config['database']['hostname'] = 'localhost';
$config['database']['username'] = 'root';
$config['database']['password'] = '';
$config['database']['encoding'] = 'utf8';


$db = new DB_MySQLi;
$db->connect($config['database']);
$db->set_table_prefix($config['database']['table_prefix']);
$db->type $config['database']['type'];

?>

مثال :
انتخاب
کد php:
<?php
$query 
$db->query("select * from tbl1");
while(
$user $db->fetch_array($query))
    {
    echo (
$user['col2']);
    echo(
'<br>');
    }
?>
کد php:
<?php
$options 
= array(
        
"limit" => 1
    
);
    
$pid=1;
    
$query $db->simple_select("tbl1""*""col1='".$pid."'",  $options);
    
?>
ثبت
کد php:
<?php
$fields 
= array(
        
"col1" => 1,
        
"col2" => $db->escape_string($_POST["newname"])
                );
$db->insert_query("tbl1"$fields);
?>
آپدیت
کد php:
<?php
$update_sql 
= array("col2" => "hamed");
$db->update_query("tbl1"$update_sql"col1='1'");
?>
حذف
کد php:
<?php
$db
->delete_query("tbl1""col1='' OR col1='1'");
?>

حامد ارفعی

موفقيت، پيش رفتن است، نه به نقطه ي پايان رسيدن.(آنتوني رابينز)


تریگرها در SQL server

آیا میدانید SQL ای
۰۶-فروردین-۱۳۹۲, ۱۴:۱۰:۰۸
وب سایت ارسال‌ها
پاسخ
تشکر شده توسط : hadikh73, babyy, aleas, Ghoghnus, aKaReZa75, javaweb
babyy آفلاین
بازنشسته
*****

ارسال‌ها: 3,095
موضوع‌ها: 141
تاریخ عضویت: مرداد ۱۳۸۷

تشکرها : 35081
( 26090 تشکر در 9068 ارسال )
ارسال: #3
JSON
کتابخانه‌ی json :

(البته خود php چنین کتابخانه برای دیکد و انکود داره اما بعضو اوغات در بعضی از سرور ها یا فعال نیست یا ورژنشون قدیکه این به درد میخوره)

کد php:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Converts to and from JSON format.
 *
 * JSON (javascirpt Object Notation) is a lightweight data-interchange
 * format. It is easy for humans to read and write. It is easy for machines
 * to parse and generate. It is based on a subset of the javascirpt
 * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
 * This feature can also be found in  Python. JSON is a text format that is
 * completely language independent but uses conventions that are familiar
 * to programmers of the C-family of languages, including C, C++, C#, Java,
 * javascirpt, Perl, TCL, and many others. These properties make JSON an
 * ideal data-interchange language.
 *
 * This package provides a simple encoder and decoder for JSON notation. It
 * is intended for use with client-side javascirpt applications that make
 * use of HTTPRequest to perform server communication functions - data can
 * be encoded into JSON notation for use in a client-side javascirpt, or
 * decoded from incoming javascirpt requests. JSON format is native to
 * javascirpt, and can be directly eval()'ed with no further parsing
 * overhead
 *
 * All strings should be in ASCII or UTF-8 format!
 *
 * LICENSE: Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met: Redistributions of source code must retain the
 * above copyright notice, this list of conditions and the following
 * disclaimer. Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
 * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 * @category
 * @package     Services_JSON
 * @author      Michal Migurski <mike-json@teczno.com>
 * @author      Matt Knapp <mdknapp[at]gmail[dot]com>
 * @author      Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
 * @copyright   2005 Michal Migurski
 * @version     CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @link        http://pear.php.net/pepr/pepr-proposal-show.php?id=198
 */

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_SLICE',   1);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_STR',  2);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_ARR',  3);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_OBJ',  4);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_CMT'5);

/**
 * Behavior switch for Services_JSON::decode()
 */
define('SERVICES_JSON_LOOSE_TYPE'16);

/**
 * Behavior switch for Services_JSON::decode()
 */
define('SERVICES_JSON_SUPPRESS_ERRORS'32);

/**
 * Converts to and from JSON format.
 *
 * Brief example of use:
 *
 * <code>
 * // create a new instance of Services_JSON
 * $json = new Services_JSON();
 *
 * // convert a complexe value to JSON notation, and send it to the browser
 * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
 * $output = $json->encode($value);
 *
 * print($output);
 * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
 *
 * // accept incoming POST data, assumed to be in JSON notation
 * $input = file_get_contents('php://input', 1000000);
 * $value = $json->decode($input);
 * </code>
 */
class Services_JSON
{
   
/**
    * constructs a new JSON instance
    *
    * @param    int     $use    object behavior flags; combine with boolean-OR
    *
    *                           possible values:
    *                           - SERVICES_JSON_LOOSE_TYPE:  loose typing.
    *                                   "{...}" syntax creates associative arrays
    *                                   instead of objects in decode().
    *                           - SERVICES_JSON_SUPPRESS_ERRORS:  error suppression.
    *                                   Values which can't be encoded (e.g. resources)
    *                                   appear as NULL instead of throwing errors.
    *                                   By default, a deeply-nested resource will
    *                                   bubble up with an error, so all return values
    *                                   from encode() should be checked with isError()
    */
    
function Services_JSON($use 0)
    {
        
$this->use $use;
    }

   
/**
    * convert a string from one UTF-16 char to one UTF-8 char
    *
    * Normally should be handled by mb_convert_encoding, but
    * provides a slower PHP-only method for installations
    * that lack the multibye string extension.
    *
    * @param    string  $utf16  UTF-16 character
    * @return   string  UTF-8 character
    * @access   private
    */
    
function utf162utf8($utf16)
    {
        
// oh please oh please oh please oh please oh please
        
if(function_exists('mb_convert_encoding')) {
            return 
mb_convert_encoding($utf16'UTF-8''UTF-16');
        }

        
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});

        switch(
true) {
            case ((
0x7F $bytes) == $bytes):
                
// this case should never be reached, because we are in ASCII range
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                
return chr(0x7F $bytes);

            case (
0x07FF $bytes) == $bytes:
                
// return a 2-byte UTF-8 character
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                
return chr(0xC0 | (($bytes >> 6) & 0x1F))
                     . 
chr(0x80 | ($bytes 0x3F));

            case (
0xFFFF $bytes) == $bytes:
                
// return a 3-byte UTF-8 character
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                
return chr(0xE0 | (($bytes >> 12) & 0x0F))
                     . 
chr(0x80 | (($bytes >> 6) & 0x3F))
                     . 
chr(0x80 | ($bytes 0x3F));
        }

        
// ignoring UTF-32 for now, sorry
        
return '';
    }

   
/**
    * convert a string from one UTF-8 char to one UTF-16 char
    *
    * Normally should be handled by mb_convert_encoding, but
    * provides a slower PHP-only method for installations
    * that lack the multibye string extension.
    *
    * @param    string  $utf8   UTF-8 character
    * @return   string  UTF-16 character
    * @access   private
    */
    
function utf82utf16($utf8)
    {
        
// oh please oh please oh please oh please oh please
        
if(function_exists('mb_convert_encoding')) {
            return 
mb_convert_encoding($utf8'UTF-16''UTF-8');
        }

        switch(
strlen($utf8)) {
            case 
1:
                
// this case should never be reached, because we are in ASCII range
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                
return $utf8;

            case 
2:
                
// return a UTF-16 character from a 2-byte UTF-8 char
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                
return chr(0x07 & (ord($utf8{0}) >> 2))
                     . 
chr((0xC0 & (ord($utf8{0}) << 6))
                         | (
0x3F ord($utf8{1})));

            case 
3:
                
// return a UTF-16 character from a 3-byte UTF-8 char
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                
return chr((0xF0 & (ord($utf8{0}) << 4))
                         | (
0x0F & (ord($utf8{1}) >> 2)))
                     . 
chr((0xC0 & (ord($utf8{1}) << 6))
                         | (
0x7F ord($utf8{2})));
        }

        
// ignoring UTF-32 for now, sorry
        
return '';
    }

   
/**
    * encodes an arbitrary variable into JSON format
    *
    * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
    *                           see argument 1 to Services_JSON() above for array-parsing behavior.
    *                           if var is a strng, note that encode() always expects it
    *                           to be in ASCII or UTF-8 format!
    *
    * @return   mixed   JSON string representation of input var or an error if a problem occurs
    * @access   public
    */
    
function encode($var)
    {
        switch (
gettype($var)) {
            case 
'boolean':
                return 
$var 'true' 'false';

            case 
'NULL':
                return 
'null';

            case 
'integer':
                return (int) 
$var;

            case 
'double':
            case 
'float':
                return (float) 
$var;

            case 
'string':
                
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
                
$ascii '';
                
$strlen_var strlen($var);

               
/*
                * Iterate over every character in the string,
                * escaping with a slash or encoding to UTF-8 where necessary
                */
                
for ($c 0$c $strlen_var; ++$c) {

                    
$ord_var_c ord($var{$c});

                    switch (
true) {
                        case 
$ord_var_c == 0x08:
                            
$ascii .= '\b';
                            break;
                        case 
$ord_var_c == 0x09:
                            
$ascii .= '\t';
                            break;
                        case 
$ord_var_c == 0x0A:
                            
$ascii .= '\n';
                            break;
                        case 
$ord_var_c == 0x0C:
                            
$ascii .= '\f';
                            break;
                        case 
$ord_var_c == 0x0D:
                            
$ascii .= '\r';
                            break;

                        case 
$ord_var_c == 0x22:
                        case 
$ord_var_c == 0x2F:
                        case 
$ord_var_c == 0x5C:
                            
// double quote, slash, slosh
                            
$ascii .= '\\'.$var{$c};
                            break;

                        case ((
$ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
                            
// characters U-00000000 - U-0000007F (same as ASCII)
                            
$ascii .= $var{$c};
                            break;

                        case ((
$ord_var_c 0xE0) == 0xC0):
                            
// characters U-00000080 - U-000007FF, mask 110XXXXX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            
$char pack('C*'$ord_var_cord($var{$c 1}));
                            
$c += 1;
                            
$utf16 $this->utf82utf16($char);
                            
$ascii .= sprintf('\u%04s'bin2hex($utf16));
                            break;

                        case ((
$ord_var_c 0xF0) == 0xE0):
                            
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            
$char pack('C*'$ord_var_c,
                                         
ord($var{$c 1}),
                                         
ord($var{$c 2}));
                            
$c += 2;
                            
$utf16 $this->utf82utf16($char);
                            
$ascii .= sprintf('\u%04s'bin2hex($utf16));
                            break;

                        case ((
$ord_var_c 0xF8) == 0xF0):
                            
// characters U-00010000 - U-001FFFFF, mask 11110XXX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            
$char pack('C*'$ord_var_c,
                                         
ord($var{$c 1}),
                                         
ord($var{$c 2}),
                                         
ord($var{$c 3}));
                            
$c += 3;
                            
$utf16 $this->utf82utf16($char);
                            
$ascii .= sprintf('\u%04s'bin2hex($utf16));
                            break;

                        case ((
$ord_var_c 0xFC) == 0xF8):
                            
// characters U-00200000 - U-03FFFFFF, mask 111110XX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            
$char pack('C*'$ord_var_c,
                                         
ord($var{$c 1}),
                                         
ord($var{$c 2}),
                                         
ord($var{$c 3}),
                                         
ord($var{$c 4}));
                            
$c += 4;
                            
$utf16 $this->utf82utf16($char);
                            
$ascii .= sprintf('\u%04s'bin2hex($utf16));
                            break;

                        case ((
$ord_var_c 0xFE) == 0xFC):
                            
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            
$char pack('C*'$ord_var_c,
                                         
ord($var{$c 1}),
                                         
ord($var{$c 2}),
                                         
ord($var{$c 3}),
                                         
ord($var{$c 4}),
                                         
ord($var{$c 5}));
                            
$c += 5;
                            
$utf16 $this->utf82utf16($char);
                            
$ascii .= sprintf('\u%04s'bin2hex($utf16));
                            break;
                    }
                }

                return 
'"'.$ascii.'"';

            case 
'array':
               
/*
                * As per JSON spec if any array key is not an integer
                * we must treat the the whole array as an object. We
                * also try to catch a sparsely populated associative
                * array with numeric keys here because some JS engines
                * will create an array with empty indexes up to
                * max_index which can cause memory issues and because
                * the keys, which may be relevant, will be remapped
                * otherwise.
                *
                * As per the ECMA and JSON specification an object may
                * have any string as a property. Unfortunately due to
                * a hole in the ECMA specification if the key is a
                * ECMA reserved word or starts with a digit the
                * parameter is only accessible using ECMAScript's
                * bracket notation.
                */

                // treat as a JSON object
                
if (is_array($var) && count($var) && (array_keys($var) !== range(0sizeof($var) - 1))) {
                    
$properties array_map(array($this'name_value'),
                                            
array_keys($var),
                                            
array_values($var));

                    foreach(
$properties as $property) {
                        if(
Services_JSON::isError($property)) {
                            return 
$property;
                        }
                    }

                    return 
'{' join(','$properties) . '}';
                }

                
// treat it like a regular array
                
$elements array_map(array($this'encode'), $var);

                foreach(
$elements as $element) {
                    if(
Services_JSON::isError($element)) {
                        return 
$element;
                    }
                }

                return 
'[' join(','$elements) . ']';

            case 
'object':
                
$vars get_object_vars($var);

                
$properties array_map(array($this'name_value'),
                                        
array_keys($vars),
                                        
array_values($vars));

                foreach(
$properties as $property) {
                    if(
Services_JSON::isError($property)) {
                        return 
$property;
                    }
                }

                return 
'{' join(','$properties) . '}';

            default:
                return (
$this->use SERVICES_JSON_SUPPRESS_ERRORS)
                    ? 
'null'
                    
: new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
        }
    }

   
/**
    * array-walking function for use in generating JSON-formatted name-value pairs
    *
    * @param    string  $name   name of key to use
    * @param    mixed   $value  reference to an array element to be encoded
    *
    * @return   string  JSON-formatted name-value pair, like '"name":value'
    * @access   private
    */
    
function name_value($name$value)
    {
        
$encoded_value $this->encode($value);

        if(
Services_JSON::isError($encoded_value)) {
            return 
$encoded_value;
        }

        return 
$this->encode(strval($name)) . ':' $encoded_value;
    }

   
/**
    * reduce a string by removing leading and trailing comments and whitespace
    *
    * @param    $str    string      string value to strip of comments and whitespace
    *
    * @return   string  string value stripped of comments and whitespace
    * @access   private
    */
    
function reduce_string($str)
    {
        
$str preg_replace(array(

                
// eliminate single line comments in '// ...' form
                
'#^\s*//(.+)$#m',

                
// eliminate multi-line comments in '/* ... */' form, at start of string
                
'#^\s*/\*(.+)\*/#Us',

                
// eliminate multi-line comments in '/* ... */' form, at end of string
                
'#/\*(.+)\*/\s*$#Us'

            
), ''$str);

        
// eliminate extraneous space
        
return trim($str);
    }

   
/**
    * decodes a JSON string into appropriate variable
    *
    * @param    string  $str    JSON-formatted string
    *
    * @return   mixed   number, boolean, string, array, or object
    *                   corresponding to given JSON input string.
    *                   See argument 1 to Services_JSON() above for object-output behavior.
    *                   Note that decode() always returns strings
    *                   in ASCII or UTF-8 format!
    * @access   public
    */
    
function decode($str)
    {
        
$str $this->reduce_string($str);

        switch (
strtolower($str)) {
            case 
'true':
                return 
true;

            case 
'false':
                return 
false;

            case 
'null':
                return 
null;

            default:
                
$m = array();

                if (
is_numeric($str)) {
                    
// Lookie-loo, it's a number

                    // This would work on its own, but I'm trying to be
                    // good about returning integers where appropriate:
                    // return (float)$str;

                    // Return float or int, as appropriate
                    
return ((float)$str == (integer)$str)
                        ? (integer)
$str
                        
: (float)$str;

                } elseif (
preg_match('/^("|\').*(\1)$/s'$str$m) && $m[1] == $m[2]) {
                    
// STRINGS RETURNED IN UTF-8 FORMAT
                    
$delim substr($str01);
                    
$chrs substr($str1, -1);
                    
$utf8 '';
                    
$strlen_chrs strlen($chrs);

                    for (
$c 0$c $strlen_chrs; ++$c) {

                        
$substr_chrs_c_2 substr($chrs$c2);
                        
$ord_chrs_c ord($chrs{$c});

                        switch (
true) {
                            case 
$substr_chrs_c_2 == '\b':
                                
$utf8 .= chr(0x08);
                                ++
$c;
                                break;
                            case 
$substr_chrs_c_2 == '\t':
                                
$utf8 .= chr(0x09);
                                ++
$c;
                                break;
                            case 
$substr_chrs_c_2 == '\n':
                                
$utf8 .= chr(0x0A);
                                ++
$c;
                                break;
                            case 
$substr_chrs_c_2 == '\f':
                                
$utf8 .= chr(0x0C);
                                ++
$c;
                                break;
                            case 
$substr_chrs_c_2 == '\r':
                                
$utf8 .= chr(0x0D);
                                ++
$c;
                                break;

                            case 
$substr_chrs_c_2 == '\\"':
                            case 
$substr_chrs_c_2 == '\\\'':
                            case 
$substr_chrs_c_2 == '\\\\':
                            case 
$substr_chrs_c_2 == '\\/':
                                if ((
$delim == '"' && $substr_chrs_c_2 != '\\\'') ||
                                   (
$delim == "'" && $substr_chrs_c_2 != '\\"')) {
                                    
$utf8 .= $chrs{++$c};
                                }
                                break;

                            case 
preg_match('/\\\u[0-9A-F]{4}/i'substr($chrs$c6)):
                                
// single, escaped unicode character
                                
$utf16 chr(hexdec(substr($chrs, ($c 2), 2)))
                                       . 
chr(hexdec(substr($chrs, ($c 4), 2)));
                                
$utf8 .= $this->utf162utf8($utf16);
                                
$c += 5;
                                break;

                            case (
$ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
                                
$utf8 .= $chrs{$c};
                                break;

                            case (
$ord_chrs_c 0xE0) == 0xC0:
                                
// characters U-00000080 - U-000007FF, mask 110XXXXX
                                //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                                
$utf8 .= substr($chrs$c2);
                                ++
$c;
                                break;

                            case (
$ord_chrs_c 0xF0) == 0xE0:
                                
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                                
$utf8 .= substr($chrs$c3);
                                
$c += 2;
                                break;

                            case (
$ord_chrs_c 0xF8) == 0xF0:
                                
// characters U-00010000 - U-001FFFFF, mask 11110XXX
                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                                
$utf8 .= substr($chrs$c4);
                                
$c += 3;
                                break;

                            case (
$ord_chrs_c 0xFC) == 0xF8:
                                
// characters U-00200000 - U-03FFFFFF, mask 111110XX
                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                                
$utf8 .= substr($chrs$c5);
                                
$c += 4;
                                break;

                            case (
$ord_chrs_c 0xFE) == 0xFC:
                                
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                                
$utf8 .= substr($chrs$c6);
                                
$c += 5;
                                break;

                        }

                    }

                    return 
$utf8;

                } elseif (
preg_match('/^\[.*\]$/s'$str) || preg_match('/^\{.*\}$/s'$str)) {
                    
// array, or object notation

                    
if ($str{0} == '[') {
                        
$stk = array(SERVICES_JSON_IN_ARR);
                        
$arr = array();
                    } else {
                        if (
$this->use SERVICES_JSON_LOOSE_TYPE) {
                            
$stk = array(SERVICES_JSON_IN_OBJ);
                            
$obj = array();
                        } else {
                            
$stk = array(SERVICES_JSON_IN_OBJ);
                            
$obj = new stdClass();
                        }
                    }

                    
array_push($stk, array('what'  => SERVICES_JSON_SLICE,
                                           
'where' => 0,
                                           
'delim' => false));

                    
$chrs substr($str1, -1);
                    
$chrs $this->reduce_string($chrs);

                    if (
$chrs == '') {
                        if (
reset($stk) == SERVICES_JSON_IN_ARR) {
                            return 
$arr;

                        } else {
                            return 
$obj;

                        }
                    }

                    
//print("\nparsing {$chrs}\n");

                    
$strlen_chrs strlen($chrs);

                    for (
$c 0$c <= $strlen_chrs; ++$c) {

                        
$top end($stk);
                        
$substr_chrs_c_2 substr($chrs$c2);

                        if ((
$c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
                            
// found a comma that is not inside a string, array, etc.,
                            // OR we've reached the end of the character list
                            
$slice substr($chrs$top['where'], ($c $top['where']));
                            
array_push($stk, array('what' => SERVICES_JSON_SLICE'where' => ($c 1), 'delim' => false));
                            
//print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");

                            
if (reset($stk) == SERVICES_JSON_IN_ARR) {
                                
// we are in an array, so just push an element onto the stack
                                
array_push($arr$this->decode($slice));

                            } elseif (
reset($stk) == SERVICES_JSON_IN_OBJ) {
                                
// we are in an object, so figure
                                // out the property name and set an
                                // element in an associative array,
                                // for now
                                
$parts = array();
                                
                                if (
preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis'$slice$parts)) {
                                    
// "name":value pair
                                    
$key $this->decode($parts[1]);
                                    
$val $this->decode($parts[2]);

                                    if (
$this->use SERVICES_JSON_LOOSE_TYPE) {
                                        
$obj[$key] = $val;
                                    } else {
                                        
$obj->$key $val;
                                    }
                                } elseif (
preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis'$slice$parts)) {
                                    
// name:value pair, where name is unquoted
                                    
$key $parts[1];
                                    
$val $this->decode($parts[2]);

                                    if (
$this->use SERVICES_JSON_LOOSE_TYPE) {
                                        
$obj[$key] = $val;
                                    } else {
                                        
$obj->$key $val;
                                    }
                                }

                            }

                        } elseif (((
$chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
                            
// found a quote, and we are not inside a string
                            
array_push($stk, array('what' => SERVICES_JSON_IN_STR'where' => $c'delim' => $chrs{$c}));
                            
//print("Found start of string at {$c}\n");

                        
} elseif (($chrs{$c} == $top['delim']) &&
                                 (
$top['what'] == SERVICES_JSON_IN_STR) &&
                                 ((
strlen(substr($chrs0$c)) - strlen(rtrim(substr($chrs0$c), '\\'))) % != 1)) {
                            
// found a quote, we're in a string, and it's not escaped
                            // we know that it's not escaped becase there is _not_ an
                            // odd number of backslashes at the end of the string so far
                            
array_pop($stk);
                            
//print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");

                        
} elseif (($chrs{$c} == '[') &&
                                 
in_array($top['what'], array(SERVICES_JSON_SLICESERVICES_JSON_IN_ARRSERVICES_JSON_IN_OBJ))) {
                            
// found a left-bracket, and we are in an array, object, or slice
                            
array_push($stk, array('what' => SERVICES_JSON_IN_ARR'where' => $c'delim' => false));
                            
//print("Found start of array at {$c}\n");

                        
} elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
                            
// found a right-bracket, and we're in an array
                            
array_pop($stk);
                            
//print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");

                        
} elseif (($chrs{$c} == '{') &&
                                 
in_array($top['what'], array(SERVICES_JSON_SLICESERVICES_JSON_IN_ARRSERVICES_JSON_IN_OBJ))) {
                            
// found a left-brace, and we are in an array, object, or slice
                            
array_push($stk, array('what' => SERVICES_JSON_IN_OBJ'where' => $c'delim' => false));
                            
//print("Found start of object at {$c}\n");

                        
} elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
                            
// found a right-brace, and we're in an object
                            
array_pop($stk);
                            
//print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");

                        
} elseif (($substr_chrs_c_2 == '/*') &&
                                 
in_array($top['what'], array(SERVICES_JSON_SLICESERVICES_JSON_IN_ARRSERVICES_JSON_IN_OBJ))) {
                            
// found a comment start, and we are in an array, object, or slice
                            
array_push($stk, array('what' => SERVICES_JSON_IN_CMT'where' => $c'delim' => false));
                            
$c++;
                            
//print("Found start of comment at {$c}\n");

                        
} elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
                            
// found a comment end, and we're in one now
                            
array_pop($stk);
                            
$c++;

                            for (
$i $top['where']; $i <= $c; ++$i)
                                
$chrs substr_replace($chrs' '$i1);

                            
//print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");

                        
}

                    }

                    if (
reset($stk) == SERVICES_JSON_IN_ARR) {
                        return 
$arr;

                    } elseif (
reset($stk) == SERVICES_JSON_IN_OBJ) {
                        return 
$obj;

                    }

                }
        }
    }

    
/**
     * @todo Ultimately, this should just call PEAR::isError()
     */
    
function isError($data$code null)
    {
        if (
class_exists('pear')) {
            return 
PEAR::isError($data$code);
        } elseif (
is_object($data) && (get_class($data) == 'services_json_error' ||
                                 
is_subclass_of($data'services_json_error'))) {
            return 
true;
        }

        return 
false;
    }
}

if (
class_exists('PEAR_Error')) {

    class 
Services_JSON_Error extends PEAR_Error
    
{
        function 
Services_JSON_Error($message 'unknown error'$code null,
                                     
$mode null$options null$userinfo null)
        {
            
parent::PEAR_Error($message$code$mode$options$userinfo);
        }
    }

} else {

    
/**
     * @todo Ultimately, this class shall be descended from PEAR_Error
     */
    
class Services_JSON_Error
    
{
        function 
Services_JSON_Error($message 'unknown error'$code null,
                                     
$mode null$options null$userinfo null)
        {

        }
    }

}
    
?>

مثال:

کد php:
$json_obj  = new Services_JSON();
        
$json_echo $json_obj->encode($json);
        
$json_echo $json_obj->decode($json); 
۰۶-فروردین-۱۳۹۲, ۲۰:۱۸:۳۲
وب سایت ارسال‌ها
پاسخ
تشکر شده توسط : hadikh73, Ghoghnus, aKaReZa75, javaweb
lord_viper غایب
مدیر کل انجمن
*****

ارسال‌ها: 3,949
موضوع‌ها: 352
تاریخ عضویت: بهمن ۱۳۸۴

تشکرها : 5193
( 9875 تشکر در 2650 ارسال )
ارسال: #4
RE: کلاس‌های مفید php
babyy جان کلاس اون اداپتر رو هم لطف کنی عالی میشه

[تصویر:  xshon.png]
از آن نماز که خود هیچ از آن نمی فهمی خدا چه فایده و بهره اکتساب کند
تفاخری نبود مر خدای عالم را که چون تو ابلهی او را خدا حساب کند
۰۸-فروردین-۱۳۹۲, ۱۷:۲۶:۲۶
وب سایت ارسال‌ها
پاسخ
تشکر شده توسط : babyy, aKaReZa75
babyy آفلاین
بازنشسته
*****

ارسال‌ها: 3,095
موضوع‌ها: 141
تاریخ عضویت: مرداد ۱۳۸۷

تشکرها : 35081
( 26090 تشکر در 9068 ارسال )
ارسال: #5
RE: کلاس‌های مفید php
(۰۸-فروردین-۱۳۹۲, ۱۷:۲۶:۲۶)lord_viper نوشته است: babyy جان کلاس اون اداپتر رو هم لطف کنی عالی میشه

چشم لرد گرامی جان Biggrin
فقط اینکه من دسترسی ندارم پست اولی رو ویرایش کنم اینو بزارم توش؛
هرکی میتونه اینکارو کنه متشکر میشم


فایل‌(های) پیوست شده
.zip   database-adapter-2013-03-17.zip (اندازه: 7.35 KB / تعداد دفعات دریافت: 57)
۰۸-فروردین-۱۳۹۲, ۲۲:۳۱:۱۷
وب سایت ارسال‌ها
پاسخ
تشکر شده توسط : omid_phoenix, lord_viper, aKaReZa75, javaweb
hamed_Arfaee آفلاین
مدیر بخش
*****

ارسال‌ها: 1,334
موضوع‌ها: 231
تاریخ عضویت: تير ۱۳۸۳

تشکرها : 1250
( 2634 تشکر در 730 ارسال )
ارسال: #6
RE: کلاس‌های مفید php
(۰۸-فروردین-۱۳۹۲, ۲۲:۳۱:۱۷)babyy نوشته است: فقط اینکه من دسترسی ندارم پست اولی رو ویرایش کنم اینو بزارم توش؛
منم نتونستم پیوستتو اونجا لینک بدم بجاش هر دو کلاس رو اونجا کپی کردم :)


کلاس تقویم شمسی :
[تصویر:  calendar-1.png]

لینک

محض احتیاط اینجاهم آپلود میکنم


فایل‌(های) پیوست شده
.zip   jalali-date-2011-04-02.zip (اندازه: 103.58 KB / تعداد دفعات دریافت: 74)

حامد ارفعی

موفقيت، پيش رفتن است، نه به نقطه ي پايان رسيدن.(آنتوني رابينز)


تریگرها در SQL server

آیا میدانید SQL ای
۰۹-فروردین-۱۳۹۲, ۱۳:۰۴:۵۸
وب سایت ارسال‌ها
پاسخ
تشکر شده توسط : omid_phoenix, babyy, lord_viper, hadikh73, aKaReZa75, javaweb
babyy آفلاین
بازنشسته
*****

ارسال‌ها: 3,095
موضوع‌ها: 141
تاریخ عضویت: مرداد ۱۳۸۷

تشکرها : 35081
( 26090 تشکر در 9068 ارسال )
ارسال: #7
RE: کلاس‌های مفید php
کلاسی برای session


مثال:


کد php:
// Require the class file
require('SmartSession.php');

// All methods should be called before send anything to browser (any echo).
// You do not need to call session_start for any operation.
// You could configure session before any operation (call session_set_cookie_params or session_name).

// Example how to set a value to session
SmartSession::getInstance()->set('example'123);

// Example how to get a value from session by key
$value SmartSession::getInstance()->get('example');

// Example how to check whether a key exists
$exists SmartSession::getInstance()->has('example');

// Example how to unset a value from session by key
SmartSession::getInstance()->del('example');

// Example how to persist session data
// Note: You can get/set/del session data after calling saveSession,
// but it is better if you call saveSession after all manipulations.
SmartSession::getInstance()->saveSession();

// Example how to clear session data
SmartSession::getInstance()->clearSession(); 
۲۴-اردیبهشت-۱۳۹۲, ۲۰:۰۴:۳۷
وب سایت ارسال‌ها
پاسخ
تشکر شده توسط : lord_viper, omid_phoenix, aKaReZa75, javaweb, rochelleup1
babyy آفلاین
بازنشسته
*****

ارسال‌ها: 3,095
موضوع‌ها: 141
تاریخ عضویت: مرداد ۱۳۸۷

تشکرها : 35081
( 26090 تشکر در 9068 ارسال )
ارسال: #8
RE: کلاس‌های مفید php
مشخص کردن اطلاعات آیپی (کشور شهر و ...)
در واقع همون GEOIP رو میتونید توسط این سایت ببینید!

در مورد GEOIP اینحا توضیحات دادم

این کلاس با استفاده از این سایت اطلاعات رو میگیره و نشون میده!
کد php:
http://www.freegeoip.net/xml/ 
در این حالت اطلاعات آیپی که دارین رو نشون میده؛ و اگه اطلاعات واسه هر آیپی دیگه‌ای میخوایین رو؛ به این صورت عمل میکنیم:
کد php:
http://www.freegeoip.net/xml/67.205.76.146 

کد php:
<?php
/****************************************************************/
/*          This class handles netGeo location actions            */
/*                                                                */
/*            All that you need to do is use the function            */
/*            called    getNetGeo(), the function can take an Ip    */
/*            as a parameter or if left out, the service will        */
/*            use your Ip.                                        */
/*            Examples are in the bottom of this file                */
/*                                                                */
/*          Copyright: Frederik Yssing - Pinch                    */
/*          frederik.yssing@pinchlabs.dk                        */
/****************************************************************/
class netGeo{
    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 
getNetGeo($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($urlfalse$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;
    }    
}    

$netGeo = new netGeo();
// Using you local IP
$netGeo->getNetGeo($_SERVER['REMOTE_ADDR']);
echo 
$netGeo->Ip.'<br />';
echo 
$netGeo->CountryCode.'<br />';
echo 
$netGeo->CountryName.'<br />';
echo 
$netGeo->RegionCode.'<br />';
echo 
$netGeo->RegionName.'<br />';
echo 
$netGeo->City.'<br />';
echo 
$netGeo->ZipCode.'<br />';
echo 
$netGeo->Latitude.'<br />';
echo 
$netGeo->Longitude.'<br />';
echo 
$netGeo->MetroCode.'<br />';
echo 
$netGeo->AreaCode.'<br />';

//Letting the service find the proper Ip
$netGeo->getNetGeo();
echo 
$netGeo->Ip.'<br />';
echo 
$netGeo->CountryCode.'<br />';
echo 
$netGeo->CountryName.'<br />';
echo 
$netGeo->RegionCode.'<br />';
echo 
$netGeo->RegionName.'<br />';
echo 
$netGeo->City.'<br />';
echo 
$netGeo->ZipCode.'<br />';
echo 
$netGeo->Latitude.'<br />';
echo 
$netGeo->Longitude.'<br />';
echo 
$netGeo->MetroCode.'<br />';
echo 
$netGeo->AreaCode.'<br />';
?>

منبع
(آخرین ویرایش در این ارسال: ۲۷-اردیبهشت-۱۳۹۲, ۱۱:۴۶:۰۷، توسط babyy.)
۲۷-اردیبهشت-۱۳۹۲, ۱۱:۴۵:۰۹
وب سایت ارسال‌ها
پاسخ
تشکر شده توسط : omid_phoenix, aKaReZa75, javaweb, lord_viper, hamed_Arfaee, rochelleup1
babyy آفلاین
بازنشسته
*****

ارسال‌ها: 3,095
موضوع‌ها: 141
تاریخ عضویت: مرداد ۱۳۸۷

تشکرها : 35081
( 26090 تشکر در 9068 ارسال )
ارسال: #9
RE: کلاس‌های مفید php
چک کردن وجود دامین با استفاده از whois

کلاس:
کد php:
<?PHP
/**
 * @category ServerTools
 * @package Whois
 * @author Peter Reza Moghaddam <r324.moghaddam@gmail.com>
 * @author Peter Schmalfeldt <peter@manifestinteractive.com>
 * @link http://www.moghaddam24.ir
 * @link http://www.manifestinteractive.com
 */

/**
 * Begin Document
 */

class Whois
{

    
/**
     * fsockopen port
     *
     * @var    string
     * @access private
     */
    
private $port 43;

    
/**
     * fsockopen Error Number
     *
     * @var    string
     * @access private
     */
    
private $errno;

    
/**
     * fsockopen Error String
     *
     * @var    string
     * @access private
     */
    
private $errstr;

    
/**
     * fsockopen Time Out
     *
     * @var    string
     * @access private
     */
    
private $timeout 10;

    
/**
     * Selected Server from $whoisservers based on TLD from $domain
     *
     * @var    string
     * @access private
     */
    
private $whoisserver;

    
/**
     * Available Whois Servers
     *
     * @var    array
     * @access private
     */
    
private $whoisservers = array(
        
"ac" => "whois.nic.ac",
        
"ae" => "whois.nic.ae",
        
"aero" => "whois.aero",
        
"af" => "whois.nic.af",
        
"ag" => "whois.nic.ag",
        
"al" => "whois.ripe.net",
        
"am" => "whois.amnic.net",
        
"arpa" => "whois.iana.org",
        
"as" => "whois.nic.as",
        
"asia" => "whois.nic.asia",
        
"at" => "whois.nic.at",
        
"au" => "whois.aunic.net",
        
"az" => "whois.ripe.net",
        
"ba" => "whois.ripe.net",
        
"be" => "whois.dns.be",
        
"bg" => "whois.register.bg",
        
"bi" => "whois.nic.bi",
        
"biz" => "whois.biz",
        
"bj" => "whois.nic.bj",
        
"br" => "whois.registro.br",
        
"bt" => "whois.netnames.net",
        
"by" => "whois.ripe.net",
        
"bz" => "whois.belizenic.bz",
        
"ca" => "whois.cira.ca",
        
"cat" => "whois.cat",
        
"cc" => "whois.nic.cc",
        
"cd" => "whois.nic.cd",
        
"ch" => "whois.nic.ch",
        
"ci" => "whois.nic.ci",
        
"ck" => "whois.nic.ck",
        
"cl" => "whois.nic.cl",
        
"cn" => "whois.cnnic.net.cn",
        
"com" => "whois.verisign-grs.com",
        
"coop" => "whois.nic.coop",
        
"cx" => "whois.nic.cx",
        
"cy" => "whois.ripe.net",
        
"cz" => "whois.nic.cz",
        
"de" => "whois.denic.de",
        
"dk" => "whois.dk-hostmaster.dk",
        
"dm" => "whois.nic.cx",
        
"dz" => "whois.ripe.net",
        
"edu" => "whois.educause.edu",
        
"ee" => "whois.eenet.ee",
        
"eg" => "whois.ripe.net",
        
"es" => "whois.ripe.net",
        
"eu" => "whois.eu",
        
"fi" => "whois.ficora.fi",
        
"fo" => "whois.ripe.net",
        
"fr" => "whois.nic.fr",
        
"gb" => "whois.ripe.net",
        
"gd" => "whois.adamsnames.com",
        
"ge" => "whois.ripe.net",
        
"gg" => "whois.channelisles.net",
        
"gi" => "whois2.afilias-grs.net",
        
"gl" => "whois.ripe.net",
        
"gm" => "whois.ripe.net",
        
"gov" => "whois.nic.gov",
        
"gr" => "whois.ripe.net",
        
"gs" => "whois.nic.gs",
        
"gw" => "whois.nic.gw",
        
"gy" => "whois.registry.gy",
        
"hk" => "whois.hkirc.hk",
        
"hm" => "whois.registry.hm",
        
"hn" => "whois2.afilias-grs.net",
        
"hr" => "whois.ripe.net",
        
"hu" => "whois.nic.hu",
        
"ie" => "whois.domainregistry.ie",
        
"il" => "whois.isoc.org.il",
        
"in" => "whois.inregistry.net",
        
"info" => "whois.afilias.info",
        
"int" => "whois.iana.org",
        
"io" => "whois.nic.io",
        
"iq" => "vrx.net",
        
"ir" => "whois.nic.ir",
        
"is" => "whois.isnic.is",
        
"it" => "whois.nic.it",
        
"je" => "whois.channelisles.net",
        
"jobs" => "jobswhois.verisign-grs.com",
        
"jp" => "whois.jprs.jp",
        
"ke" => "whois.kenic.or.ke",
        
"kg" => "www.domain.kg",
        
"ki" => "whois.nic.ki",
        
"kr" => "whois.nic.or.kr",
        
"kz" => "whois.nic.kz",
        
"la" => "whois.nic.la",
        
"li" => "whois.nic.li",
        
"lt" => "whois.domreg.lt",
        
"lu" => "whois.dns.lu",
        
"lv" => "whois.nic.lv",
        
"ly" => "whois.nic.ly",
        
"ma" => "whois.iam.net.ma",
        
"mc" => "whois.ripe.net",
        
"md" => "whois.ripe.net",
        
"me" => "whois.meregistry.net",
        
"mg" => "whois.nic.mg",
        
"mil" => "whois.nic.mil",
        
"mn" => "whois.nic.mn",
        
"mobi" => "whois.dotmobiregistry.net",
        
"ms" => "whois.adamsnames.tc",
        
"mt" => "whois.ripe.net",
        
"mu" => "whois.nic.mu",
        
"museum" => "whois.museum",
        
"mx" => "whois.nic.mx",
        
"my" => "whois.mynic.net.my",
        
"na" => "whois.na-nic.com.na",
        
"name" => "whois.nic.name",
        
"net" => "whois.verisign-grs.net",
        
"nf" => "whois.nic.nf",
        
"nl" => "whois.domain-registry.nl",
        
"no" => "whois.norid.no",
        
"nu" => "whois.nic.nu",
        
"nz" => "whois.srs.net.nz",
        
"org" => "whois.pir.org",
        
"pl" => "whois.dns.pl",
        
"pm" => "whois.nic.pm",
        
"pr" => "whois.uprr.pr",
        
"pro" => "whois.registrypro.pro",
        
"pt" => "whois.dns.pt",
        
"re" => "whois.nic.re",
        
"ro" => "whois.rotld.ro",
        
"ru" => "whois.ripn.net",
        
"sa" => "whois.nic.net.sa",
        
"sb" => "whois.nic.net.sb",
        
"sc" => "whois2.afilias-grs.net",
        
"se" => "whois.iis.se",
        
"sg" => "whois.nic.net.sg",
        
"sh" => "whois.nic.sh",
        
"si" => "whois.arnes.si",
        
"sk" => "whois.ripe.net",
        
"sm" => "whois.ripe.net",
        
"st" => "whois.nic.st",
        
"su" => "whois.ripn.net",
        
"tc" => "whois.adamsnames.tc",
        
"tel" => "whois.nic.tel",
        
"tf" => "whois.nic.tf",
        
"th" => "whois.thnic.net",
        
"tj" => "whois.nic.tj",
        
"tk" => "whois.dot.tk",
        
"tl" => "whois.nic.tl",
        
"tm" => "whois.nic.tm",
        
"tn" => "whois.ripe.net",
        
"to" => "whois.tonic.to",
        
"tp" => "whois.nic.tl",
        
"tr" => "whois.nic.tr",
        
"travel" => "whois.nic.travel",
        
"tv" => "tvwhois.verisign-grs.com",
        
"tw" => "whois.twnic.net.tw",
        
"ua" => "whois.net.ua",
        
"ug" => "whois.co.ug",
        
"uk" => "whois.nic.uk",
        
"us" => "whois.nic.us",
        
"uy" => "nic.uy",
        
"uz" => "whois.cctld.uz",
        
"va" => "whois.ripe.net",
        
"vc" => "whois2.afilias-grs.net",
        
"ve" => "whois.nic.ve",
        
"vg" => "whois.adamsnames.tc",
        
"wf" => "whois.nic.wf",
        
"ws" => "whois.website.ws",
        
"yt" => "whois.nic.yt",
        
"yu" => "whois.ripe.net");

    
/**
     * Domain Name (URL or IP Address)
     *
     * @var    string
     * @access public
     */
    
public $domain;

    
/**
     * Full URL
     *
     * @var    string
     * @access public
     */
    
public $url;

    
/**
     * Domain Array containing Domain and TLD
     *
     * @var    array
     * @access public
     */
    
public $domainarray;

    
/**
     * Returned Whois Text
     *
     * @var    string
     * @access public
     */
    
public $data;

    
/**
     * Constructor
     *
     * Create Google Translate Object and Convert $string
     * <code>
     * <?php
     * $whois = new Whois("example.com");
     * echo $whois->domain;                    // 'example.com'
     * echo $whois->url;                     // 'http://example.com'
     * echo $whois->domainarray[0];            // 'com'
     * echo $whois->domainarray[1];            // 'example'
     * echo $whois->data;                     // [ ... whois data ... ] 
     *
     * $whoisFull = new Whois("http://www.example.com");
     * echo $whoisFull->domain;                // 'example.com'
     * echo $whoisFull->url;                 // 'http://www.example.com'
     * echo $whoisFull->domainarray[0];        // 'com'
     * echo $whoisFull->domainarray[1];        // 'example'
     * echo $whoisFull->data;                 // [ ... whois data ... ] 
     *
     * $whoisIP = new Whois("123.45.678.90");
     * echo $whoisIP->domain;                // '123.45.678.90'
     * echo $whoisIP->url;                     // 'http://123.45.678.90'
     * echo $whoisIP->domainarray[0];        // NULL
     * echo $whoisIP->domainarray[1];        // NULL
     * echo $whoisIP->data;                 // [ ... whois data ... ] 
     * ?>
     * </code>
     *
     * @param     string $domain URL or IP Address
     * @access     public
     */

    
function checkDomain($domain)
    {

        
$this->domain $domain;
        
$this->domain rtrim($this->domain"/");
        
$this->domain preg_replace('/http:\/\//'''$this->domain);

        
$this->url = (substr($this->domain07) != 'http://') ? 'http://' $this->
            
domain $this->domain;

        if (!
preg_match('/(\d+).(\d+).(\d+).(\d+)/'$this->domain)) {
            
$this->domainarray split("\."$this->domain);
            
$this->domainarray array_reverse($this->domainarray);
            
$this->domain $this->domainarray[1] . '.' $this->domainarray[0];
        }

        if (
strlen($this->domain) > 0) {
            foreach (
$this->whoisservers as $tld => $server) {
                if (
substr($this->domain, -strlen($tld)) == $tld) {
                    
$this->whoisserver $server;
                    break;
                }
            }
            if (!
$this->whoisserver) {
                if (
preg_match('/(\d+).(\d+).(\d+).(\d+)/'$this->domain))
                    
$this->whoisserver "whois.arin.net";
                else
                    
$this->data "Error: No appropriate Whois server found for {$this->domain} domain!";
            }

            if (
$result $this->queryServer()) {
                
preg_match("/Whois Server: (.*)/"$result$matches);
                
$secondary $matches[1];
                if (
$secondary) {
                    
$this->whoisserver $secondary;
                    
$result $this->queryServer();
                }
                
$this->data $result;
            } else {
                
$this->data "Error: No results retrieved from $whoisserver server for {$this->domain} domain!";
            }
        }
    }

    
/**
     * Query Selected Whois Server
     *
     * @access private
     */
    
private function queryServer()
    {
        
$out "";
        
$fp = @fsockopen($this->whoisserver$this->port$this->errno$this->errstr$this->
            
timeout);
        
fputs($fp$this->domain "\r\n");
        while (!
feof($fp))
            
$out .= fgets($fp);
        
fclose($fp);
        if (
strlen($out) > 0)
            return 
$out;
        else
            return 
false;
    }
    
    
/**
     * Simple Whois With Details
     *
     */
    
function checkExist()
    {
        
//compare what has been returned by the server
        
if (eregi("Can't get information"$this->data) || eregi("No entries found"$this->data) ||
            
eregi("NOT FOUND"$this->data) || eregi("No match"$this->data)) {
            return 
0;
        } else {
            return 
nl2br($this->data);
        }
    }
    
    
/**
     * Simple Whois WithOut Details
     *
     */
    
function existOrNo()
    {
        
//compare what has been returned by the server
        
if (eregi("Can't get information"$this->data) || eregi("No entries found"$this->data) ||
            
eregi("NOT FOUND"$this->data) || eregi("No match"$this->data)) {
            return 
0;
        } else {
            return 
1;
        }
    }
}
?>

مثال:

کد php:
<?php

/**
 * -------------------------------------
 * @Author      Reza Moghaddam
 * @URL         moghaddam24.ir
 * @Email       r324.moghaddam@gmail.com
 * -------------------------------------
 */

include_once 'whois.class.php';


$whois = new Whois();
$whois->checkDomain("your-domain.com");

/*
if ( $whois->checkExist() ){
    echo $whois->checkExist();
}else{
    echo "Available For Register";
}
*/

if ( $whois->existOrNo() ){
    echo 
"Dont Available";
}else{
    echo 
"Available For Register";
}

?>

منبع
۲۷-اردیبهشت-۱۳۹۲, ۱۲:۵۳:۱۹
وب سایت ارسال‌ها
پاسخ
تشکر شده توسط : omid_phoenix, aKaReZa75, lord_viper, javaweb, hamed_Arfaee
babyy آفلاین
بازنشسته
*****

ارسال‌ها: 3,095
موضوع‌ها: 141
تاریخ عضویت: مرداد ۱۳۸۷

تشکرها : 35081
( 26090 تشکر در 9068 ارسال )
ارسال: #10
RE: کلاس‌های مفید php
برای کار با ftp :

کلاس :

کد php:
<?php
/*********************************************************************************
**
** class FTP
** rev 2013-08-07 Mark Kintigh
**
** Common class to interface with an FTP server
** ______________________________________________________________________________
**
** $this->server == FTP server's name
** $this->logon_user == User name for the FTP logon
** $this->logon_pswd == User name's password for the FTP logon
** $this->transfer_mode == Current/default transfer mode for FTP file transfers
** $this->lconnected() == Returns the current status of the FTP connection
** $this->connect(["server", 'user", "password]) == Returns if a connection to
**      the FTP server was successful.  Optionally, a new server, user name, and
**      password can be given
** $this->pasivemode(<true/false>) == Set the passive mode for the FTP connection;
**      true = passive, false = active.
** $this->close() == Attempts to close the connection to the FTP server
** $this->makedir("directory") == Attempts to create a directory on the remote
**      FTP host.  This will create an entire path of folders if necessary.
**      Returns the success or failure of the attempt.
** $this->lpwd() == Returns the local, present working directory
** $this->pwd() == Returns the remote (FTP), present working directory
** $this->lcd("directory") == Attempts to change the local directory; returns the
**      success or failure
** $this->cd("directory") == Attempts to change the remote directory; returns the
**      success or failure
** $this->isdir("directory") == Returns if the given name is a directory or not;
**      this can be the full path or relative to the present working directory
** $this->dir(["new directory"]) == Returns an array of file and folder names
**      from the FTP server (empty array if error/not connected/etc).  Optionally
**      a new folder path can be given
** $this->dirfind($filespecs) == Returns an array of files and folder names from
**      the FTP server that match the given file specifications (empty array if
**      error/not connected/etc)
** $this->dirdetails(["directory"]) == Returns an array of arrays with details
**      about each of the directory entries.  The subarray contains the following:
**           [x]['name'] == File/directory name for this entry
**           [x]['dir'] == T/F; true = subdirectory, false = file
**           [x]['size'] == Human readable version of the file size (blank if
**                 directory)
**           [x]['chmod'] == Unix permissions (blank if Windows server)
**           [x]['date'] == Date of the file
**           [x]['raw'] == the raw array of information that the above was built
**                 from
**      Optionally a new folder path can be given
** $this->get($filename[,$mode=NULL]) == Attempt to download a file.  The file
**      name can contain a path as well.  Optionally the transfer mode is give.
** $this->mget($filespecs[, $mode=NULL]) == Attempt to download a group of files
**      from server.  The file  name can contain a path as well.  Optionally the
**      transfer mode is give.
** $this->getdir($path[, $recursive=true[, $mode=NULL]]) == Attempts to download
**      an entire directory from an FTP server.  Optionally you can download just
**      the files in the first folder or (default) the entire tree.  You can also
**      change/set the download mode as well.
** $this->getdirfilter($path[[[, $fliter="*"[, $recursive=true[, $mode=NULL]]])
**      Attempts to download a list of files matching a given pattern from a
**      directory from an FTP server.  Optionally you can download just the files
**      in the first folder or (default) the entire tree.  You can also change/set
**      the download mode as well.
** $this->put($filename[, $dest=""[,$mode=NULL]]) == Attempts to upload a single
**      file to the FTP server.  Optionally it will upload it in a destination
**      directory.  You can also change/set the upload mode as well.
** $this->mput($filespecs="*"[, $dest=""[, $mode=NULL]]) == Attempts to upload a
**      file(s) to the FTP server.  Optionally it will upload it in a destination
**      directory.  You can also change/set the upload mode as well.
** $this->putdir($srcdir[, $destdir=""[, $mode=NULL]]) == Attempts to upload a
**      folder to the FTP server.  Optionally it will upload it in a destination
**      directory.  You can also change/set the upload mode as well.
** $this->del($file) == Attempts to delete a file on the FTP host.  Returns
**      success or failure.
** $this->deldir($dir) == Attempts to delete a folder on the FTP host.  Returns
**      success or failure.
** $this->exists($path) == Checks to see if a file exists.  Returns T/F.
** $this->existsdir($path)  == Checks to see if a file or folder exists.  Returns
**      T/F.
** $this->movetoserver($file[, $dest=""[, $mode=NULL]]) == Combines the tasks of
**      uploading a file, verifying it was uploading, then removing it from the
**      local server.  Returns success or failure.
** $this->movefromserver($file[, $mode=NULL]) == Combines the tasks of downloading
**      a file, verifying it was downloaded, then removing it from the FTP server.
**      Returns success or failure.
** $this->rename($oldname, $newname) == Will attempt to rename the given file on
**      the remote host to a new name.  Returns success / failure.
** $this->chmod($mode, $filename) == Will attempt to set permissions on a file on
**      the host.  Returns success or failure.  This ONLY works on a Linux/UNIX
**      host because it call the external "chmod" command to set these values.
**      Limitations on how the mode is passed depends on the FTP host; best bet is
**      to use the 3 octal numbers instead of something like "u+rw,g+w,o+r".
** $this->translatecommand($commandline) == Will attempt to translate the string
**      into the operation for this class and execute it -- used for translating
**      scripts.  Returns success or failure.
**
*********************************************************************************/
class FTP {
    
//
    // Public variables
    //
    
public $server "";
    public 
$logon_user "";
    public 
$logon_pswd "";
    public 
$transfer_mode FTP_BINARY;
    
//
    // Private, global variables
    //
    
private $lconnected false;
    private 
$conn;
    private 
$port 21;
    
    
//----------------------------------------------------------------------------
    
public function __construct($newserver=""$newuser=""$newpswd="") {
        
$this->server trim($newserver);
        
$this->logon_user trim($newuser);
        
$this->logon_pswd trim($newpswd);
        
$this->checkforport();
    }
    
    
//----------------------------------------------------------------------------
    
private function checkforport() {
        
//
        // Check the set server's name for a port number (standard
        // "ftp.some.com:2121" configuration)
        //
        
if(strpos($this->server":")>-1) {
            
$a split(":"$this->server2);
            
$this->server trim($a[0]);
            
$this->port intval($a[1])>intval($a[1]) : 21;
            unset(
$a);
        }
    }

    
//----------------------------------------------------------------------------
    
private function connected() {
        
//
        // Return the current status of the FTP connection
        //
        
return $this->lconnected;
    }
    
    
//----------------------------------------------------------------------------
    
public function connect($newserver=""$newuser=""$newpswd="") {
        
//
        // Attempt to connect to an FTP server
        // __________
        //
        // If the 3 optional parameters are all set, change to the new server
        //
        
if(strlen(trim($newserver))>&& strlen(trim($newuser))>&& 
            
strlen(trim($newpswd))>0) {
            
$this->server trim($newserver);
            
$this->logon_user trim($newuser);
            
$this->logon_pswd trim($newpswd);
            
$this->checkforport();
        }
        
//
        // If there is already an open connection close it
        //
        
if($this->lconnected$this->close();
        
//
        // Try to connect to the FTP server and then try to login
        //
        
$this->conn ftp_connect($this->server$this->port);
        
$result ftp_login($this->conn$this->logon_user$this->logon_pswd);
        if(!
$this->conn || !$result) {
            
$this->lconnected false;
            return 
false;
        } else {
            
$this->lconnected true;
            return 
true;
        }
    }

    
//----------------------------------------------------------------------------
    
public function pasivemode($isPassive=true) {
        
//
        // Set the passive mode for the connection
        //
        
if(!$this->lconnected) return false;
        return 
ftp_pasv($this->conn$isPassive);
    }

    
//----------------------------------------------------------------------------
    
public function close() {
        
//
        // If there is a connection open close it
        //
        
if($this->conn) {
            
ftp_close($this->conn);
            
$this->lconnected false;
        }
    }

    
//----------------------------------------------------------------------------
    
public function makedir($dirname) {
        if(!
$this->lconnected) return false;
        
$pwd $this->pwd();
        
$cur $pwd;
        
//
        // Determine if this is just creating one folder or a series of folders
        //
        
$temp str_replace("\\","/",$dirname);
        
//
        // If the path start with the root, then change out the path to root
        //
        
if(substr($temp,0,1)=="/") {
            
$temp substr($temp,1);
            
$this->cd("/");
            
$cur "/";
        }
        if(
strpos($temp,"/")>-1) {
            
//
            // Has a full path, so verify that the folders exist or create the
            // desired folder
            //
            
$ret true;
            
//
            // For each of the parts
            //
            
foreach(split("/",$temp) as $part) {
                
//
                // Add this part to the current path
                //
                
$cur .= "/$part";
                
//
                // Try to change to the folder
                //
                
if(!$this->cd($cur)) {
                    
//
                    // It did not change, so try to create the folder
                    //
                    
if(ftp_mkdir($this->conn$cur)) {
                        
//
                        // Successfully created the folder, so change to it
                        //
                        
$this->cd($cur);
                    } else {
                        
//
                        // Fail the creation of the path
                        //
                        
$ret false;
                    }
                }
            }
            
//
            // Return to the original folder and return the results
            //
            
$this->cd($pwd);
            return 
$ret;
        } else {
            
//
            // Just try to create the folder
            //
            
return ftp_mkdir($this->conn$dirname);
        }
    }

    
//----------------------------------------------------------------------------
    
public function lpwd() {
        
//
        // Return local present working directory
        //
        
return getcwd();
    }
    
    
//----------------------------------------------------------------------------
    
public function pwd() {
        
//
        // Return the remote present working directory
        //
        
if(!$this->lconnected) return "";
        return 
ftp_pwd($this->conn);
    }
    
    
//----------------------------------------------------------------------------
    
public function lcd($ldir) {
        
//
        // Local change directory; return success/faliure
        //
        
if(is_dir($ldir)) {
            return @
chdir($ldir);
        } else {
            return 
false;
        }
    }

    
//----------------------------------------------------------------------------
    
public function cd($rdir) {
        
//
        // Change the remote directory, if possible, and return
        // success/failure
        //
        
if(!$this->lconnected) return false;
        return @
ftp_chdir($this->conn$rdir);
    }
    
    
//----------------------------------------------------------------------------
    
public function isdir($foldername) {
        
//
        // Check to see if the given folder name is a directory.  If
        // it fails the first time, try again after adding the present
        // working directory
        //
        
if(!$this->lconnected) return false;
        
$pwd $this->pwd();
        
$ret $this->cd($foldername);
        if(!
$ret) {
            
$tmp "$pwd/$foldername";
            
$ret $this->cd($foldername);
        }
        
$this->cd($pwd);
        return 
$ret;
    }
    
    
//----------------------------------------------------------------------------
    
public function dir($newdir="") {
        if(!
$this->lconnected) return array();
        
$pwd $this->pwd();
        
//
        // If the user wants a different directory, try to change to
        // that directory
        //
        
if(strlen(trim($newdir))>0) {
            if(
$this->cd($newdir)) {
                
$pwd $this->pwd();
            }
        }
        
$list ftp_nlist($this->conn$pwd);
        
//
        // Strip the path off of the file names
        //
        
for($x=0$x<count($list); $x++) {
            
$list[$x] = substr($list[$x], strlen($pwd));
            
//
            // Remove any leading "\" and "/" characters
            //
            
if(strcmp(substr($list[$x],0,1),"\\")==0)
                
$list[$x] = substr($list[$x],1);
            if(
strcmp(substr($list[$x],0,1),"/")==0)
                
$list[$x] = substr($list[$x],1);
        }
        return 
$list;
    }
    
    
//----------------------------------------------------------------------------
    
public function dirfilter($filespecs="*.*") {
        if(!
$this->lconnected) return array();
        
$pwd $this->pwd();
        
$list = @ftp_nlist($this->conn"$pwd/" trim($filespecs));
        
//
        // Strip the path off of the file names
        //
        
for($x=0$x<count($list); $x++) {
            
$list[$x] = substr($list[$x], strlen($pwd));
            
//
            // Remove any leading "\" and "/" characters
            //
            
if(strcmp(substr($list[$x],0,1),"\\")==0)
                
$list[$x] = substr($list[$x],1);
            if(
strcmp(substr($list[$x],0,1),"/")==0)
                
$list[$x] = substr($list[$x],1);
        }
        return 
$list;
    }

    
//----------------------------------------------------------------------------
    
public function dirdetails($newdir="") {
        if(!
$this->lconnected) return array();
        
$pwd $this->pwd();
        
//
        // If the user wants a different directory, try to change to
        // that directory
        //
        
if(strlen(trim($newdir))>0) {
            if(
$this->cd($newdir)) {
                
$pwd $this->pwd();
            }
        }
        
$list ftp_rawlist($this->conn$this->pwd(), false);
        
$ret = array();
        if(empty(
$list)) return $ret;
        foreach(
$list as $fil) {
            
$info = array(
                
'name'=>'',
                
'dir'=>false,
                
'size'=>'',
                
'chmod'=>'',
                
'date'=>'',
                
'raw'=>NULL
                
);
            if(
strpos("0123456789",substr($fil,0,1))>-1) {
                
//
                // Windows FTP host
                //
                
$split preg_split("/[\s]+/"$fil);
                if(
count($split)>3) {
                    
$split preg_split("/[\s]+/"$fil4);
                    
$info['name'] = str_replace(":"""trim($split[3]));
                    if(
strcmp("<DIR>",trim($split[2]))==0) {
                        
$info['dir'] = true;
                    } else {
                        
$info['dir'] = false;
                        
$info['size'] = $this->byteconvert($split[2]);
                    }
                    
$info['date'] = strtotime(str_replace("-","/""{$split[0]} "
                        
str_replace("P"," P",
                            
str_replace("A"," A",strtoupper($split[1])))));
                    
$info['raw'] = $split;
                }
            } elseif(
strlen(trim($fil))>0) {
                
//
                // UNIX FTP host
                //
                
$split preg_split("/[\s]+/"$fil);
                if(
count($split)>8) {
                    
$split preg_split("/[\s]+/"$fil9);
                    
$info['name'] = trim($split[8]);
                    
$info['dir'] = ($split[0]{0}=='d');
                    
$info['size'] = $this->byteconvert($split[4]);
                    
$info['chmod'] = $this->chmodnum($split[0]);
                    
$info['date'] = strtotime("{$split[6]} {$split[5]} {$split[7]}");
                    
$info['raw'] = $split;
                }
            }
            if(
strlen(trim($info['name']))>0) {
                
array_push($ret,$info);
            }
            unset(
$info);
        }
        
//
        // Strip the path off of the file names
        //
        
return $ret;
    }

    
//----------------------------------------------------------------------------
    
private function stringMatchWithWildcard($source,$pattern) {
        
$pattern preg_quote($pattern,'/');        
        
$pattern str_replace'\*' '.*'$pattern);   
        return 
preg_match'/^' $pattern '$/i' $source );
    }

    
//----------------------------------------------------------------------------
    
public function dirdetailsfilter($filespecs="*"$newdir="") {
        if(!
$this->lconnected) return array();
        
$pwd $this->pwd();
        
//
        // If the user wants a different directory, try to change to
        // that directory
        //
        
if(strlen(trim($newdir))>0) {
            if(
$this->cd($newdir)) {
                
$pwd $this->pwd();
            }
        }
        
$list ftp_rawlist($this->conn$this->pwd(), false);
        
$ret = array();
        if(empty(
$list)) return $ret;
        foreach(
$list as $fil) {
            
$info = array(
                
'name'=>'',
                
'dir'=>false,
                
'size'=>'',
                
'chmod'=>'',
                
'date'=>'',
                
'raw'=>NULL
                
);
            if(
strpos("0123456789",substr($fil,0,1))>-1) {
                
//
                // Windows FTP host
                //
                
$split preg_split("/[\s]+/"$fil);
                if(
count($split)>3) {
                    
$split preg_split("/[\s]+/"$fil4);
                    
$info['name'] = str_replace(":"""trim($split[3]));
                    if(
strcmp("<DIR>",trim($split[2]))==0) {
                        
$info['dir'] = true;
                    } else {
                        
$info['dir'] = false;
                        
$info['size'] = $this->byteconvert($split[2]);
                    }
                    
$info['date'] = strtotime(str_replace("-","/""{$split[0]} "
                        
str_replace("P"," P",
                            
str_replace("A"," A",strtoupper($split[1])))));
                    
$info['raw'] = $split;
                }
            } elseif(
strlen(trim($fil))>0) {
                
//
                // UNIX FTP host
                //
                
$split preg_split("/[\s]+/"$fil);
                if(
count($split)>8) {
                    
$split preg_split("/[\s]+/"$fil9);
                    
$info['name'] = trim($split[8]);
                    
$info['dir'] = ($split[0]{0}=='d');
                    
$info['size'] = $this->byteconvert($split[4]);
                    
$info['chmod'] = $this->chmodnum($split[0]);
                    
$info['date'] = strtotime("{$split[6]} {$split[5]} {$split[7]}");
                    
$info['raw'] = $split;
                }
            }
            if(
$this->stringMatchWithWildcard(trim($info['name']), $filespecs)) {
                
array_push($ret,$info);
            }
        }
        
//
        // Strip the path off of the file names
        //
        
return $ret;
    }

    
//----------------------------------------------------------------------------
    
private function byteconvert($bytes) {
        
$symbol = array('B''KB''MB''GB''TB''PB''EB''ZB''YB');
        
$exp floorlog($bytes) / log(1024) );
        return @
sprintf'%.2f ' $symbol$exp ], 
            (
$bytes pow(1024floor($exp))) );
    }

    
//----------------------------------------------------------------------------
    
private function chmodnum($chmod) {
        
$trans = array('-' => '0''r' => '4''w' => '2''x' => '1');
        
$chmod substr(strtr($chmod$trans), 1);
        
$array str_split($chmod3);
        return 
array_sum(str_split($array[0])) . array_sum(str_split($array[1]))
            . 
array_sum(str_split($array[2]));
    }

    
//----------------------------------------------------------------------------
    
public function get($filename,$mode=NULL) {
        if(!
$this->lconnected) return false;
        
//
        // Check to see if the user wants to use a specific transfer method,
        // otherwise assume that they want to use the class' default mode
        //
        
$usemode $this->transfer_mode;
        if(
$mode==FTP_BINARY || $mode==FTP_ASCII$usemode $mode;
        
//
        // Check to see if there is a path as part of the file name and, if so,
        // split off the file name to use it as the local file name too
        //
        
if(strpos($filename,"\\")>-1) {
            
$parts explode("\\",$filename);
            
$localname array_pop($parts);
            unset(
$parts);
        } elseif(
strpos($filename,"/")>-1) {
            
$parts explode("/",$filename);
            
$localname array_pop($parts);
            unset(
$parts);
        } else {
            
$localname $filename;
        }
        
//
        // Try to get the file
        //
        
if(ftp_get($this->conn$localname$filename$usemode)) {
            return 
true;
        } else {
            return 
false;
        }
    }
    
    
//----------------------------------------------------------------------------
    
public function mget($filespecs$mode=NULL) {
        if(!
$this->lconnected) return false;
        
$pwd $this->pwd();
        
$remotepath $pwd;
        
//
        // Check to see if the user wants to use a specific transfer method,
        // otherwise assume that they want to use the class' default mode
        //
        
$usemode $this->transfer_mode;
        if(
$mode==FTP_BINARY || $mode==FTP_ASCII$usemode $mode;
        
//
        // Check to see if there is a path as part of the file specs and, if so,
        // split off the filespecs and the folder path
        //
        
if(strpos($filespecs,"\\")>-1) {
            
$parts explode("\\",$filename);
            
$localspecs array_pop($parts);
            
$remotepath implode("\\",$parts);
            unset(
$parts);
        } elseif(
strpos($filespecs,"/")>-1) {
            
$parts explode("/",$filename);
            
$localspecs array_pop($parts);
            
$remotepath implode("/",$parts);
            unset(
$parts);
        } else {
            
$localspecs $filespecs;
        }
        
//
        // The the present working directory on the FTP server is not the same as
        // the desired location, try to change to that folder.  If that does not
        // work then exit with failure here (not accessable/does not exist).
        //
        
if(strcmp($pwd,$remotepath)!=0) if(!$this->cd($remotepath)) return false;
        
//
        // Process each of the files
        //
        
$success 0;
        
$found 0;
        foreach(
$this->dirdetailsfilter($localspecs$remotepath) as $info) {
            
//
            // If this is NOT a folder
            //
            
if(!$info['dir']) {
                
$found++;
                if(
$this->get($info['name'], $usemode)) {
                    
$success++;
                }
            }
        }
        
//
        // The the present working directory on the FTP server is not the same as
        // the desired location, try to return to the old directory.
        //
        
if(strcmp($pwd,$remotepath)!=0$this->cd($pwd);
        
//
        // Determine what to return
        // * If nothing found, return -1
        // * If found = success, return 1
        // * Otherwise, return 0
        //
        
if($found==0) {
            return -
1;
        } elseif(
$found==$success) {
            return 
1;
        } else {
            return 
0;
        }
    }

    
//----------------------------------------------------------------------------
    
function getdir($path$recursive=true$mode=NULL) {
        if(!
$this->lconnected) return false;
        
$pwd $this->pwd();
        
$ret true;
        
//
        // Check to see if the user wants to use a specific transfer method,
        // otherwise assume that they want to use the class' default mode
        //
        
$usemode $this->transfer_mode;
        if(
$mode==FTP_BINARY || $mode==FTP_ASCII$usemode $mode;
        
$parts explode("/"str_replace("\\","/",$path));
        
//
        // Stip the desired folder name off of the given path
        //
        
$foldername array_pop($parts);
        unset(
$parts);
        if(!
is_dir($foldername)) mkdir($foldername);
        if(
$this->lcd($foldername)) {
            
//
            // What kind of get is this -- single folder or recursive
            //
            
if($recursive) {
                if(
$this->cd($path)) {
                    
//
                    // In the subfolder, so read the directory
                    //
                    
$files $this->dirdetails();
                    foreach(
$files as $fil) {
                        if(
$fil['dir']==true) {
                            
//
                            // This is a folder, so recursively call the function
                            // __________
                            //
                            // 1 -- get the current local path
                            // 2 -- recursively call this function
                            // 3 -- return to the current remote path
                            // 4 -- return to the local path before the recursion
                            //
                            
$olddir $this->lpwd();
                            
$this->getdir($path "/" trim($fil['name']),
                                
$recursive$usemode);
                            
$this->cd($path);
                            
$this->lcd($olddir);
                        } else {
                            
//
                            // Download the file
                            //
                            
if(!$this->get($path "/" $fil['name'], $usemode)) {
                                
$ret false;
                            }
                        }
                    }
                } else {
                    
//
                    // Could not change to the desired path on the FTP server, so
                    // this operation has failed
                    //
                    
$ret=false;
                }
            } else {
                
//
                // Just download the files in the given folder; this will recreate
                // the folder name in the current path.  If it already exists it will
                // just add files to the existing folder.
                
if($this->cd($path)) {
                    
//
                    // In the subfolder, so read the directory
                    //
                    
$files $this->dirdetails();
                    foreach(
$files as $fil) {
                        
//
                        // If this entry is not a directory...
                        //
                        
if($fil['dir']==false) {
                            
//
                            // ...download the file
                            //
                            
if(!$this->get($fil['name'], $usemode)) {
                                
$ret false;
                            }
                        }
                    }
                } else {
                    
//
                    // Could not change to the desired path on the FTP server, so
                    // this operation has failed
                    //
                    
$ret=false;
                }
            }
        } else {
            
//
            // Could not change to the desired path on the local machine, so
            // this operation has failed
            //
            
$ret=false;
        }
        
//
        // Return to the original path
        //
        
$this->cd($pwd);
        return 
$ret;
    }

    
//----------------------------------------------------------------------------
    
function getdirfilter($path$fliter="*"$recursive=true$mode=NULL) {
        if(!
$this->lconnected) return false;
        
$pwd $this->pwd();
        
$ret true;
        
//
        // Check to see if the user wants to use a specific transfer method,
        // otherwise assume that they want to use the class' default mode
        //
        
$usemode $this->transfer_mode;
        if(
$mode==FTP_BINARY || $mode==FTP_ASCII$usemode $mode;
        
$parts explode("/"str_replace("\\","/",$path));
        
//
        // Stip the desired folder name off of the given path
        //
        
$foldername array_pop($parts);
        unset(
$parts);
        if(!
is_dir($foldername)) mkdir($foldername);
        if(
$this->lcd($foldername)) {
            
//
            // What kind of get is this -- single folder or recursive
            //
            
if($recursive) {
                if(
$this->cd($path)) {
                    
//
                    // In the subfolder, so read the directory
                    //
                    
$files $this->dirdetailsfilter($fliter);
                    if(!empty(
$files)) {
                        foreach(
$files as $fil) {
                            if(
$fil['dir']==true) {
                                
//
                                // This is a folder, so recursively call the function
                                // __________
                                //
                                // 1 -- get the current local path
                                // 2 -- recursively call this function
                                // 3 -- return to the current remote path
                                // 4 -- return to the local path before the recursion
                                //
                                
$olddir $this->lpwd();
                                
$this->getdirfilter($path "/" trim($fil['name']),
                                    
$fliter$recursive$usemode);
                                
$this->cd($path);
                                
$this->lcd($olddir);
                            } else {
                                
//
                                // Download the file
                                //
                                
if(!$this->get($path "/" $fil['name'], $usemode)) {
                                    
$ret false;
                                }
                            }
                        }
                    } else {
                        
//
                        // Nothing matched
                        //
                        
$ret=false;
                    }
                } else {
                    
//
                    // Could not change to the desired path on the FTP server, so
                    // this operation has failed
                    //
                    
$ret=false;
                }
            } else {
                
//
                // Just download the files in the given folder; this will recreate
                // the folder name in the current path.  If it already exists it will
                // just add files to the existing folder.
                
if($this->cd($path)) {
                    
//
                    // In the subfolder, so read the directory
                    //
                    
$files $this->dirdetails();
                    foreach(
$files as $fil) {
                        
//
                        // If this entry is not a directory...
                        //
                        
if($fil['dir']==false) {
                            
//
                            // ...download the file
                            //
                            
if(!$this->get($fil['name'], $usemode)) {
                                
$ret false;
                            }
                        }
                    }
                } else {
                    
//
                    // Could not change to the desired path on the FTP server, so
                    // this operation has failed
                    //
                    
$ret=false;
                }
            }
        } else {
            
//
            // Could not change to the desired path on the local machine, so
            // this operation has failed
            //
            
$ret=false;
        }
        
//
        // Return to the original path
        //
        
$this->cd($pwd);
        return 
$ret;
    }

    
//----------------------------------------------------------------------------
    
public function put($filename$dest="",$mode=NULL) {
        if(!
$this->lconnected) return false;
        
$pwd $this->pwd();
        
//
        // Check to see if the user wants to use a specific transfer method,
        // otherwise assume that they want to use the class' default mode
        //
        
$usemode $this->transfer_mode;
        if(
$mode==FTP_BINARY || $mode==FTP_ASCII$usemode $mode;
        
//
        // Check to see if there was a destination location given.  If so, change
        // to that location.  If that fails, return to the present working 
        // directory and return false.
        //
        
if(strlen($dest)>0) {
            if(!
$this->cd($dest)) {
                
$this->cd($pwd);
                return -
1;
            }
        }
        
//
        // Check to see if there is a path as part of the file name and, if so,
        // split off the file name to use it as the local file name too
        //
        
if(strpos($filename,"\\")>-1) {
            
$parts explode("\\",$filename);
            
$localname array_pop($parts);
            unset(
$parts);
        } elseif(
strpos($filename,"/")>-1) {
            
$parts explode("/",$filename);
            
$localname array_pop($parts);
            unset(
$parts);
        } else {
            
$localname $filename;
        }
        
//
        // Try to put the file
        //
        
$ret false;
        if(
ftp_put($this->conn$localname$filename$usemode)) {
            return 
false;
        }
        
$this->cd($pwd);
        return 
$ret;
    }
    
    
//----------------------------------------------------------------------------
    
public function mput($filespecs="*"$dest=""$mode=NULL) {
        if(!
$this->lconnected) return false;
        
$lpwd $this->lpwd();
        
$localpath $lpwd;
        
$pwd $this->pwd();
        
//
        // Check to see if the user wants to use a specific transfer method,
        // otherwise assume that they want to use the class' default mode
        //
        
$usemode $this->transfer_mode;
        if(
$mode==FTP_BINARY || $mode==FTP_ASCII$usemode $mode;
        
//
        // Check to see if there was a destination location given.  If so, change
        // to that location.  If that fails, return to the present working 
        // directory and return false.
        //
        
if(strlen($dest)>0) {
            if(!
$this->cd($dest)) {
                
$this->cd($pwd);
                return -
1;
            }
        }
        
//
        // Check to see if there is a path as part of the file name and, if so,
        // split off the file name to use it as the local file name too.
        //
        
if(strpos($filespecs,"\\")>-1) {
            
$parts explode("\\",$filespecs);
            
$localspecs array_pop($parts);
            
$localpath implode("\\"$parts);
            unset(
$parts);
        } elseif(
strpos($filespecs,"/")>-1) {
            
$parts explode("/",$filespecs);
            
$localspecs array_pop($parts);
            
$localpath implode("/"$parts);
            unset(
$parts);
        } else {
            
$localspecs $filespecs;
        }
        
//
        // The the present working directory on the local server is not the same as
        // the desired location, try to change to that folder.  If that does not
        // work then exit with failure here (not accessable/does not exist).
        //
        
if(strcmp($lpwd,$localpath)!=0) if(!$this->lcd($localpath)) return -1;
        
//
        // Process each of the files
        //
        
$success 0;
        
$found 0;
        
$list glob($filespecs);
        if(empty(
$list)) return 0;
        foreach(
$list as $srcfile) {
            if(!
is_dir($srcfile)) {
                
$found++;
                if(
$this->put($srcfile$usemode)) $success++;
            }
        }
        
//
        // The the present working directory on the local server is not the same as
        // the desired location, try to return to the old directory.
        //
        
if(strcmp($lpwd,$localpath)!=0$this->lcd($lpwd);
        
$this->cd($pwd);
        
//
        // Determine what to return
        // * If nothing found or an error, return -1
        // * If found = success, return 1
        // * Otherwise, return 0
        //
        
if($found==0) {
            return -
1;
        } elseif(
$found==$success) {
            return 
1;
        } else {
            return 
0;
        }
    }

    
//----------------------------------------------------------------------------
    
public function putdir($srcdir$destdir="",$mode=NULL) {
        if(!
$this->lconnected) return false;
        
$ret true;
        
$pwd $this->pwd();
        
//
        // Check to see if the user wants to use a specific transfer method,
        // otherwise assume that they want to use the class' default mode
        //
        
$usemode $this->transfer_mode;
        if(
$mode==FTP_BINARY || $mode==FTP_ASCII$usemode $mode;
        
//
        // Check to see if there was a destdirination location given.  If so, change
        // to that location.  If that fails, return to the present working 
        // directory and return false.
        //
        
if(strlen($destdir)>0) {
            if(!
$this->cd($destdir)) {
                
$this->cd($pwd);
                return -
1;
            }
        }
        
//
        // Try to put the folder
        // __________
        //
        // Load the source directory 
        //
        
$local dir($srcdir);
        
$target strlen(trim($destdir))>trim($destdir) : $pwd;
        while(
$file =  $local->read()) {
            
//
            // Ignore . and .. (prevents a loop)
            //
            
if($file != "." && $file!="..") {
                if(
is_dir("$srcdir/$file")) {
                    
//
                    // This is a directory
                    //
                    
if(!$this->cd("$target/$file")) {
                        
//
                        // Try to create the new folder
                        //
                        
if(!$this->makedir("$target/$file")) {
                            
//
                            // If the folder was not made, fail here and do
                            // not try to upload this folder
                            //
                            
$ret false;
                        } else {
                            
//
                            // Recursively call this function to add the files
                            //
                            
$this->putdir("$srcdir/$file""$target/$file",
                                
$usemode);
                        }
                    } else {
                        
//
                        // Recursively call this function to add the files
                        //
                        
$this->putdir("$srcdir/$file""$target/$file",
                            
$usemode);
                    }
                } else {
                    
//
                    // Try to upload the file to the server
                    //
                    
if(!$this->put("$srcdir/$file""$target"$usemode)) {
                        
$ret false;
                    }
                }
            }
        }
        
$local->close();
        
$this->cd($pwd);
        return 
$ret;
    }

    
//----------------------------------------------------------------------------
    
public function del($file) {
        if(!
$this->lconnected) return false;
        if(
strpos($file,"*")>-|| strpos($file,"?")>-1) {
            
//
            // Name has wildcards, so delete multiple files
            //
            
$pwd $this->pwd();
            
$remotepath $pwd;
            
//
            // Check to see if there is a path as part of the file specs and, if so,
            // split off the filespecs and the folder path
            //
            
if(strpos($file,"\\")>-1) {
                
$parts explode("\\",$file);
                
$localspecs array_pop($parts);
                
$remotepath implode("\\",$parts);
                unset(
$parts);
            } elseif(
strpos($file,"/")>-1) {
                
$parts explode("/",$file);
                
$localspecs array_pop($parts);
                
$remotepath implode("/",$parts);
                unset(
$parts);
            } else {
                
$localspecs $file;
            }
            
//
            // Get a list of matching files
            //
            
$this->cd($remotepath);
            
$list $this->dirdetailsfilter($localspecs);
            
$ret true;
            foreach(
$list as $fil) {
                if(!
$fil['dir']) {
                    if(!
$this->del($fil['name'])) {
                        
$ret false;
                    }
                }
            }
            
$this->cd($pwd);
            return 
$ret;
        } else {
            
//
            // Just removing one file
            //
            
return ftp_delete($this->conn$file);
        }
    }

    
//----------------------------------------------------------------------------
    
public function deldir($dir) {
        if(!
$this->lconnected) return false;
        if(
strlen(trim($dir))<1) return false;
        
$pwd $this->pwd();
        
//
        // Make sure the folder exists
        //
        
$ret true;
        
$dir str_replace("\\","/",$dir);
        if(
substr($dir,0,1)!="/"$dir "$pwd/$dir";
        if(!
$this->existsdir($dir)) return false;
        if(!(@
ftp_rmdir($this->conn$dir) || @ftp_delete($this->conn$dir))) {
            
//
            // If this fails, then the folder has files in it still
            //
            
$list = @ftp_nlist($this->conn$dir);
            
//
            // Call this function again for each of the entries within this folder
            //
            
foreach($list as $name) {
                if(
$name !="." && $name!="..") {
                    if(!
$this->deldir($name)) $ret false;
                }
            }
            
//
            // Try removing this folder again
            //
            
if(!$this->deldir($dir)) $ret false;
        }
        if(!
$this->cd($pwd)) $this->cd("/");
        return 
$ret;
    }

    
//----------------------------------------------------------------------------
    
public function exists($path) {
        
//
        // File existance check
        //
        
if(!$this->lconnected) return false;
        
$list $this->dirdetails($path);
        
$ret count($list)>true false;
        unset(
$list);
        return 
$ret;
    }
    
    
//----------------------------------------------------------------------------
    
public function existsdir($path) {
        
//
        // File or folder existance check
        //
        
if(!$this->lconnected) return false;
        
$path str_replace("\\","/",$path);
        if(
$path == "/") return true;
        
$parts split("/",$path);
        
$last array_pop($parts);
        
$base implode("/"$parts);
        unset(
$parts);
        
$list $this->dirdetailsfilter($last$base);
        
$ret count($list)>true false;
        unset(
$list);
        return 
$ret;
    }

    
//----------------------------------------------------------------------------
    
public function movetoserver($file$dest=""$mode=NULL) {
        if(!
$this->lconnected) return false;
        
//
        // Try to put the file on the host
        //
        
$ret $this->put($file,$dest,$mode);
        
//
        // If the put operation was successful, delete the file
        //
        
if($retunlink($file);
        return 
$ret;
    }

    
//----------------------------------------------------------------------------
    
public function movefromserver($file$mode=NULL) {
        if(!
$this->lconnected) return false;
        
//
        // Try to get the file from the server
        //
        
$ret $this->get($file,$mode);
        
//
        // If the get operation was successful, delete the file from the FTP host
        //
        
if($ret$this->del($file);
        return 
$ret;
    }

    
//----------------------------------------------------------------------------
    
public function rename($oldname$newname) {
        if(!
$this->lconnected) return false;
        
//
        // Call the native rename command and return its results
        //
        
return ftp_rename($this->conn$oldname$newname);
    }
    
    
//----------------------------------------------------------------------------
    
public function chmod($mode$filename) {
        if(!
$this->lconnected) return false;
        
$mod trim($mode);
        
$fil str_replace("\\","/",trim($filename));
        return 
ftp_site($this->conn"chmod $mod $fil");
    }
    
    
//----------------------------------------------------------------------------
    
public function translatecommand($commandline) {
        
$commandline trim(str_replace("\\""/"$commandline));
        if(
strlen($commandline)<1) return false;
        
//
        // Ignore comment lines
        //
        
if(substr($commandline,0,1)=="#") return true;
        
$commandline $this->replacetokens($commandline);
        
//
        // Process the actual FTP command
        //
        
$ret false;
        
$parts split(" "$commandline2);
        echo 
var_dump($parts) . "\n";
        if(isset(
$parts[0])) {
            switch(
trim($parts[0])) {
                case 
'chmod':
                    
$list split(" "$parts[1], 2);
                    
$mod = isset($list[0]) ? trim($list[0]) : "";
                    
$fil = isset($list[1]) ? trim($list[1]) : "";
                    if(
strlen($mod)>&& strlen($fil)>0) {
                        
$ret $this->chmod($mod$fil);
                    } else {
                        
$ret false;
                    }
                    break;
                case 
'ren':
                case 
'rename':
                    
$list split(" "$parts[1], 2);
                    
$old = isset($list[0]) ? trim($list[0]) : "";
                    
$new = isset($list[1]) ? trim($list[1]) : "";
                    if(
strlen($old)>&& strlen($new)>0) {
                        
$ret $this->rename($old$new);
                    } else {
                        
$ret false;
                    }
                    break;
                case 
'put':
                    
$ret $this->put($parts[1]);
                    break;
                case 
'mput':
                    
$list split(" "$parts[1]);
                    foreach(
$list as $s) {
                        if(
$this->mput($s)) $ret true;
                    }
                    break;
                case 
'mget':
                    
$list split(" "$parts[1]);
                    foreach(
$list as $s) {
                        if(
$this->mget($s)) $ret true;
                    }
                    break;
                case 
'mkdir':
                    if(
$this->conn) {
                        
$ret $this->makedir($parts[1]);
                    } else {
                        
$ret false;
                    }
                    break;
                case 
'mget':
                    
$ret $this->mget($parts[1]);
                    break;
                case 
'get':
                    
$ret $this->get($parts[1]);
                    break;
                case 
'rmdir':
                    
$ret $this->deldir($parts[1]);
                    break;
                case 
'mdel':
                case 
'mdelete':
                    
$list split(" "$parts[1]);
                    foreach(
$list as $s) {
                        if(
$this->del($s)) $ret true;
                    }
                    break;
                case 
'del':
                case 
'delete':
                    
$ret $this->del($parts[1]);
                    break;
                case 
'lcd':
                    
$ret $this->lcd($parts[1]);
                    break;
                case 
'cd':
                    
$ret $this->cd($parts[1]);
                    break;
                case 
'binary':
                    
$this->transfer_mode FTP_BINARY;
                    
$ret true;
                    break;
                case 
'ascii':
                    
$this->transfer_mode FTP_ASCII;
                    
$ret true;
                    break;
                case 
'close':
                case 
'quit':
                case 
'bye':
                    
$this->close();
                    
$ret true;
                    break;
            }
        }
        return 
$ret;
    }
    
    
//----------------------------------------------------------------------------
    
private function replacetokens($cmd) {
        
$ret $cmd;
        
$ret str_replace("%d%"date("d",strtotime("now")), $ret);
        
$ret str_replace("%D%"date("D",strtotime("now")), $ret);
        
$ret str_replace("%j%"date("j",strtotime("now")), $ret);
        
$ret str_replace("%l%"date("l",strtotime("now")), $ret);
        
$ret str_replace("%N%"date("N",strtotime("now")), $ret);
        
$ret str_replace("%S%"date("S",strtotime("now")), $ret);
        
$ret str_replace("%w%"date("w",strtotime("now")), $ret);
        
$ret str_replace("%z%"date("z",strtotime("now")), $ret);
        
$ret str_replace("%W%"date("W",strtotime("now")), $ret);
        
$ret str_replace("%F%"date("F",strtotime("now")), $ret);
        
$ret str_replace("%m%"date("m",strtotime("now")), $ret);
        
$ret str_replace("%M%"date("M",strtotime("now")), $ret);
        
$ret str_replace("%n%"date("n",strtotime("now")), $ret);
        
$ret str_replace("%t%"date("t",strtotime("now")), $ret);
        
$ret str_replace("%L%"date("L",strtotime("now")), $ret);
        
$ret str_replace("%o%"date("o",strtotime("now")), $ret);
        
$ret str_replace("%Y%"date("Y",strtotime("now")), $ret);
        
$ret str_replace("%y%"date("y",strtotime("now")), $ret);
        
$ret str_replace("%a%"date("a",strtotime("now")), $ret);
        
$ret str_replace("%A%"date("A",strtotime("now")), $ret);
        
$ret str_replace("%B%"date("B",strtotime("now")), $ret);
        
$ret str_replace("%g%"date("g",strtotime("now")), $ret);
        
$ret str_replace("%G%"date("G",strtotime("now")), $ret);
        
$ret str_replace("%h%"date("h",strtotime("now")), $ret);
        
$ret str_replace("%H%"date("H",strtotime("now")), $ret);
        
$ret str_replace("%i%"date("i",strtotime("now")), $ret);
        
$ret str_replace("%s%"date("s",strtotime("now")), $ret);
        
$ret str_replace("%u%"date("u",strtotime("now")), $ret);
        
$ret str_replace("%e%"date("e",strtotime("now")), $ret);
        
$ret str_replace("%I%"date("I",strtotime("now")), $ret);
        
$ret str_replace("%O%"date("O",strtotime("now")), $ret);
        
$ret str_replace("%P%"date("P",strtotime("now")), $ret);
        
$ret str_replace("%T%"date("T",strtotime("now")), $ret);
        
$ret str_replace("%Z%"date("Z",strtotime("now")), $ret);
        
$ret str_replace("%c%"date("c",strtotime("now")), $ret);
        
$ret str_replace("%r%"date("r",strtotime("now")), $ret);
        
$ret str_replace("%U%"date("U",strtotime("now")), $ret);
        
$ret str_replace("%LONGDATE%"date("l, F j, Y"strtotime("now")),
            
$ret);
        
$ret str_replace("%SHORTDATE%"date("n/j/Y",strtotime("now")), $ret);
        
$ret str_replace("%LONGTIME%"date("g:i:s A"strtotime("now")), $ret);
        
$ret str_replace("%SHORTTIME%"date("H:i:s",strtotime("now")), $ret);
        
$ret str_replace("%DATESTAMP%"strtotime("now"), $ret);
        return 
$ret;
    }

}

?>


کد php:
http://www.phpclasses.org/package/8186-PHP-Access-files-in-FTP-servers.html 
۲۱-مرداد-۱۳۹۲, ۰۰:۲۳:۳۸
وب سایت ارسال‌ها
پاسخ
تشکر شده توسط : lord_viper, Ambassador, omid_phoenix
babyy آفلاین
بازنشسته
*****

ارسال‌ها: 3,095
موضوع‌ها: 141
تاریخ عضویت: مرداد ۱۳۸۷

تشکرها : 35081
( 26090 تشکر در 9068 ارسال )
ارسال: #11
RE: کلاس‌های مفید php
کلاسی برای ایجاد فایل ورد (word docX)


فایل‌(های) پیوست شده
.zip   vs-template-docx-2013-07-31.zip (اندازه: 33.71 KB / تعداد دفعات دریافت: 44)
۲۵-مرداد-۱۳۹۲, ۲۲:۵۵:۱۹
وب سایت ارسال‌ها
پاسخ
تشکر شده توسط : Ambassador, lord_viper, omid_phoenix


موضوعات مرتبط با این موضوع...
موضوع نویسنده پاسخ بازدید آخرین ارسال
Question [سوال] اعتبار سنجی فرم آپلود عکس با استفاده از یک کلاس crafcrab 2 2,619 ۱۳-آبان-۱۳۹۴, ۰۹:۴۸:۵۹
آخرین ارسال: lord_viper

پرش به انجمن:


کاربرانِ درحال بازدید از این موضوع: 1 مهمان

صفحه‌ی تماس | IranVig | بازگشت به بالا | | بایگانی | پیوند سایتی RSS