کلاس PHP دسترسی به پایگاه داده MySQL :

<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */


class dbAccess {

       var $db_connect_id;
       var $query_result;
       var $row = array();
       var $rowset = array();
       var $num_queries = 0;

       //
       // Constructor
       //
       function dbAccess($sqlserver, $sqluser, $sqlpassword, $database, $persistency = true) {

               $this->persistency = $persistency;
               $this->user = $sqluser;
               $this->password = $sqlpassword;
               $this->server = $sqlserver;
               $this->dbname = $database;

               if($this->persistency) {
                       $this->db_connect_id = @mysql_pconnect($this->server, $this->user, $this->password);
               } else {
                       $this->db_connect_id = @mysql_connect($this->server, $this->user, $this->password);
               }
               if($this->db_connect_id) {
                       if($database != "")     {
                               $this->dbname = $database;
                               $dbselect = @mysql_select_db($this->dbname);
                               if(!$dbselect) {
                                       @mysql_close($this->db_connect_id);
                                       $this->db_connect_id = $dbselect;
                               }
                       }
                       return $this->db_connect_id;
               } else {
                       return false;
               }
       }

       //
       // Other base methods
       //
       function destroy() {
               if($this->db_connect_id) {
                       if($this->query_result) {
                               @mysql_free_result($this->query_result);
                       }
                       $result = @mysql_close($this->db_connect_id);
                       return $result;
               } else {
                       return false;
               }
       }

       //
       // Base query method
       //
       function query($query = "", $transaction = FALSE) {
               // Remove any pre-existing queries
               unset($this->query_result);
               if($query != "") {
                       $this->num_queries++;
                       $this->query_result = @mysql_query($query, $this->db_connect_id);
               }
               if($this->query_result) {
                       unset($this->row[$this->query_result]);
                       unset($this->rowset[$this->query_result]);
                       return $this->query_result;
               } else {
                       return ( $transaction == END_TRANSACTION ) ? true : false;
               }
       }

       //
       // Other query methods
       //
       function numrows($query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $result = @mysql_num_rows($query_id);
                       return $result;
               } else {
                       return false;
               }
       }
       function affectedrows() {
               if($this->db_connect_id) {
                       $result = @mysql_affected_rows($this->db_connect_id);
                       return $result;
               } else {
                       return false;
               }
       }
       function numfields($query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $result = @mysql_num_fields($query_id);
                       return $result;
               } else {
                       return false;
               }
       }
       function fieldname($offset, $query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $result = @mysql_field_name($query_id, $offset);
                       return $result;
               } else {
                       return false;
               }
       }
       function fieldtype($offset, $query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $result = @mysql_field_type($query_id, $offset);
                       return $result;
               } else {
                       return false;
               }
       }
       function fetchrow($query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $this->row[$query_id] = @mysql_fetch_array($query_id);
                       return $this->row[$query_id];
               } else {
                       return false;
               }
       }
       function fetchrowset($query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                   $result = array();
                       unset($this->rowset[$query_id]);
                       unset($this->row[$query_id]);
                       while($this->rowset[$query_id] = @mysql_fetch_array($query_id)) {
                               $result[] = $this->rowset[$query_id];
                       }
                       return $result;
               } else {
                       return false;
               }
       }
       function fetchfield($field, $rownum = -1, $query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       if($rownum > -1) {
                               $result = @mysql_result($query_id, $rownum, $field);
                       } else {
                               if(empty($this->row[$query_id]) && empty($this->rowset[$query_id])) {
                                       if($this->fetchrow()) {
                                               $result = $this->row[$query_id][$field];
                                       }
                               } else {
                                       if($this->rowset[$query_id]) {
                                               $result = $this->rowset[$query_id][$field];
                                       } else if($this->row[$query_id]) {
                                               $result = $this->row[$query_id][$field];
                                       }
                               }
                       }
                       return $result;
               } else {
                       return false;
               }
       }
       function rowseek($rownum, $query_id = 0){
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $result = @mysql_data_seek($query_id, $rownum);
                       return $result;
               } else {
                       return false;
               }
       }
       function nextid(){
               if($this->db_connect_id) {
                       $result = @mysql_insert_id($this->db_connect_id);
                       return $result;
               } else {
                       return false;
               }
       }
       function freeresult($query_id = 0){
               if(!$query_id) {
                       $query_id = $this->query_result;
               }

               if ( $query_id ) {
                       unset($this->row[$query_id]);
                       unset($this->rowset[$query_id]);

                       @mysql_free_result($query_id);

                       return true;
               } else {
                       return false;
               }
       }
       function error($query_id = 0) {
               $result["message"] = @mysql_error($this->db_connect_id);
               $result["code"] = @mysql_errno($this->db_connect_id);

               return $result;
       }
}
?>

 

 

ادامه مطلب

کلاس PHP بازگردانی دیتابیس MySQL :

 

<?php

define('MSR_VERSION', '1.0.0');
define('__SEP__', "/*sep*/" );

define('MSR_STRING', 0);
define('MSR_FILE', 1);
set_time_limit( 600 );


class MySQL_Restore {

 var $server           = 'localhost';
 var $port             = 3306;
 var $username         = 'root';
 var $password         = '';
 var $database         = '';
 var $link_id          = -1;
 var $connected        = false;
 var $queries          = array();
 var $error            = '';

 var $debug            = false;
 var $log_folder       = "";
 var $log_file_name    = "";

   function MySQL_Restore() {
       $this->log_file_name = "restore_" . date( "Ymd_his" ) . ".log";
   }

   function Execute( $param, $mode = MSR_STRING, $is_compressed = false, $split_only = false ) {
       if ( $this->debug ) {
               $this->saveLog( "[start reading file]" );
       }
           if ( $mode == MSR_FILE ) {
               if (!($sql = $this->_ReadFromFile($param, $is_compressed))) {
                   $this->error = 'Can\'t read backup file.';
                   return false;
               }
           } else {
               $sql = ($is_compressed ? gzuncompress($param) : $param);
           }
       if ( $this->debug ) {
           $this->saveLog( "[file readed]" );
       }

           return $this->_Restore( $sql, $split_only );
   }


   function _Connect() {
           $value = false;
           if ( !$this->connected ) {
               $host = $this->server . ':' . $this->port;
               $this->link_id = mysql_pconnect( $host, $this->username, $this->password );
           }
           if ( $this->link_id ) {
               if ( empty( $this->database ) ) {
                   $value = true;
               } elseif ( $this->link_id !== -1 ) {
                   $value = mysql_select_db($this->database, $this->link_id);
               } else {
                   $value = mysql_select_db($this->database);
               }
           }
           if (!$value) {
               $this->error = mysql_error();
           }
           return $value;
   }

   function _Disconnect() {
       if ( $this->link_id ) {
               mysql_close( $this->link_id );
       }
   }

   function _Query( $sql ) {
       if ( $this->link_id !== -1 ) {
           $result = mysql_query( $sql, $this->link_id );
       } else {
           $result = mysql_query( $sql );
       }
       if ( !$result ) {
           $this->error = mysql_error();
       }
       return $result;
   }


// The logic from phpMyAdmin source
   function _Decompose( &$ret, $sql ) {
       $sql = rtrim( $sql, "\n\r" );
       $sql_len = strlen( $sql );
       $char = '';
       $string_start = '';
       $in_string = false;
       $nothing = true;
       $time0 = time();
       for ( $i = 0; $i < $sql_len; ++$i ) {
           $char = $sql[$i];
           if ( $in_string ) {
               for (;;) {
                   $i = strpos( $sql, $string_start, $i );
                   if ( !$i ) {
                       $ret[] = $sql;
                       return true;
                   } elseif ( $string_start == '`' || $sql[$i - 1] != '\\' ) {
                       $string_start = '';
                       $in_string = false;
                       break;
                   } else {
                       $j = 2;
                       $escaped_backslash = false;
                       while ( $i - $j > 0 && $sql[$i - $j] == '\\' ) {
                           $escaped_backslash = !$escaped_backslash;
                           $j++;
                       }
                       if ( $escaped_backslash ) {
                           $string_start = '';
                           $in_string = false;
                           break;
                       } else {
                           $i++;
                       }
                   }
               }
           } else if ( ($char == '-' && $sql_len > $i + 2 && $sql[$i + 1] == '-' && $sql[$i + 2] <= ' ') || $char == '#' || ($char == '/' && $sql_len > $i + 1 && $sql[$i + 1] == '*') ) {
               $comm_end = ($char == '/' ? '*/' : "\n");
               $i = strpos($sql, $comm_end, $i);
               if ( $i === false ) {
                   break;
               }
               if ($char == '/') {
                   $i++;
               }
           } else if ($char == ';') {
               $ret[] = array( 'query' => substr( $sql, 0, $i ), 'empty' => $nothing );
               $nothing = true;
               $sql = ltrim(substr($sql, min($i + 1, $sql_len)));
               $sql_len = strlen($sql);
               if ( $sql_len ) {
                   $i = -1;
               } else {
                   return true;
               }
           } else if (($char == '"') || ($char == '\'') || ($char == '`')) {
               $in_string = true;
               $nothing = false;
               $string_start = $char;
           } elseif ($nothing) {
               $nothing = false;
           }
           $time1 = time();
           if ($time1 >= $time0 + 30) {
               $time0 = $time1;
               @header('X-pmaPing: Pong');
           }
       }
       if (!empty($sql) && preg_match('@[^[:space:]]+@', $sql)) {
           $ret[] = array('query' => $sql, 'empty' => $nothing);
       }
       return true;
   }


   function _Restore($sql, $split_only) {
       if ( $this->debug ) {
           $this->saveLog( "[start restoring]" );
       }
       if ( $this->debug ) {
           $this->saveLog( "[connecting to DB...]" );
       }

       if (!$this->_Connect()) {
           return false;
       }
       if ( $this->debug ) {
           $this->saveLog( "[connected to DB]" );
       }
       if ( $this->debug ) {
           $this->saveLog( "[decomposing...]" );
       }
       $queries = array();
       $errors = '';

// check if is this our backup
       if ( strpos( $sql, __SEP__ ) !== false ) {
               if ( $this->debug ) {
                   $this->saveLog( "[founding our backup file]" );
               }
           $queries = explode( __SEP__, $sql );
           if ( count( $queries ) ) {
                   if ( $this->debug ) {
                       $this->saveLog( "[decomposed]" );
                   }
                   if (!$split_only) {
                       foreach ($queries as $query) {
                               $query = trim( $query );
                               if ( !empty( $query ) ) {
                                   if (!$this->_Query( $query ) ) {
                                       $errors .= $this->error . '<br />';
                                   }
                                       if ( $this->debug ) {
                                  $this->saveLog( $query );
                           }
                               }
                       }
                   }
           }
       } else {
           if ( $this->debug ) {
               $this->saveLog( "[common sql file founded]" );
           }
               if (!$this->_Decompose( $queries, $sql ) ) {
                   return false;
               }
               if ( $this->debug ) {
                   $this->saveLog( "[decomposed]" );
               }
               foreach ($queries as $query) {
                   if (!$split_only) {
                       if (!$this->_Query( trim( $query['query'] ) ) ) {
                           $errors .= $this->error . '<br /><br />';
                       }
                   }
                   if ( $this->debug ) {
                       $this->saveLog( $query['query'] );
                   }
               }
       }
       if ( $this->debug ) {
           $this->saveLog( "[finished restoring]" );
       }
       $this->_Disconnect();

       if ( !empty( $errors ) ) {
           $this->error = $errors;
           return false;
       }
       return true;
   }


   function _ReadFromFile($fname, $is_compressed) {
          if ($is_compressed) {
              $sql = gzfile($fname);
          } else {
              $sql = file($fname);
          }
          if ($sql === false) {
             return false;
          }
          return implode('', $sql);
       }

       function saveLog( $str ) {
       $f = @fopen( $this->log_folder . $this->log_file_name, "a" );
       @fwrite( $f, "[" . date( "H:i:s" ). "] " . $str . "\n" );
               @fclose( $f );
       }
}

?>

 

ادامه مطلب

کلاس PHP برای پشتیبان گیری از دیتابیس MySQL :

[syntax type=”html|php|js|css”]

<?php

define(‘MSB_VERSION’, ‘1.0.0’);

define(‘MSB_NL’, “\r\n”);

define(‘MSB_STRING’, 0);
define(‘MSB_DOWNLOAD’, 1);
define(‘MSB_SAVE’, 2);
define(‘__SEP__’, “/*sep*/” );

set_time_limit( 600 );

class MySQL_Backup {
var $server = ‘localhost’;
var $port = 3306;
var $username = ‘root’;
var $password = ”;
var $database = ”;
var $link_id = -1;
var $connected = false;
var $tables = array();
var $drop_tables = true;
var $struct_only = false;
var $comments = true;
var $backup_dir = ”;
var $fname_format = ‘d_m_y__H_i_s’;
var $error = ”;

var $complete_inserts = false;
var $inserts_block = 200;

function Execute($task = MSB_STRING, $fname = ”, $compress = false) {
if ( !( $sql = $this->_Retrieve() ) ) {
return false;
}
if ( $task == MSB_SAVE ) {
if (empty($fname)) {
$fname = $this->backup_dir;
$fname .= date($this->fname_format);
$fname .= ($compress ? ‘.sql.gz’ : ‘.sql’);
}
return $this->_SaveToFile($fname, $sql, $compress);
} elseif ($task == MSB_DOWNLOAD) {
if ( empty( $fname ) ) {
$fname = date($this->fname_format);
$fname .= ($compress ? ‘.sql.gz’ : ‘.sql’);
}
return $this->_DownloadFile($fname, $sql, $compress);
} else {
return $sql;
}
}

function _Connect() {
$value = false;
if (!$this->connected) {
$host = $this->server . ‘:’ . $this->port;
$this->link_id = mysql_connect($host, $this->username, $this->password);
}
if ($this->link_id) {
if (empty($this->database)) {
$value = true;
} elseif ($this->link_id !== -1) {
$value = mysql_select_db($this->database, $this->link_id);
} else {
$value = mysql_select_db($this->database);
}
}
if (!$value) {
$this->error = mysql_error();
}
return $value;
}

function _Query($sql) {
if ($this->link_id !== -1) {
$result = mysql_query($sql, $this->link_id);
} else {
$result = mysql_query($sql);
}
if (!$result) {
$this->error = mysql_error();
}
return $result;
}

function _GetTables() {
$value = array();
if ( !( $result = $this->_Query(‘SHOW TABLES’) ) ) {
return false;
}
while ( $row = mysql_fetch_row( $result ) ) {
if ( empty( $this->tables) || in_array( $row[0], $this->tables ) ) {
$value[] = $row[0];
}
}
if (!sizeof($value)) {
$this->error = ‘No tables found in database.’;
return false;
}
return $value;
}

function _DumpTable( $table ) {
$value = ”;
$this->_Query( ‘LOCK TABLES ‘ . $table . ‘ WRITE’ );
if ( $this->comments ) {
$value .= ‘#’ . MSB_NL;
$value .= ‘# Table structure for table `’ . $table . ‘`’ . MSB_NL;
$value .= ‘#’ . MSB_NL . MSB_NL;
}
if ( $this->drop_tables ) {
$value .= ‘DROP TABLE IF EXISTS `’ . $table . ‘`;’ . __SEP__ . MSB_NL;
}
if ( !( $result = $this->_Query(‘SHOW CREATE TABLE ‘ . $table) ) ) {
return false;
}
$row = mysql_fetch_assoc($result);
$value .= str_replace(“\n”, MSB_NL, $row[‘Create Table’]) . ‘;’ . __SEP__;
$value .= MSB_NL . MSB_NL;
if (!$this->struct_only) {
if ($this->comments) {
$value .= ‘#’ . MSB_NL;
$value .= ‘# Dumping data for table `’ . $table . ‘`’ . MSB_NL;
$value .= ‘#’ . MSB_NL . MSB_NL;
}
$value .= $this->_GetInserts($table);
}
$value .= MSB_NL . MSB_NL;
$this->_Query(‘UNLOCK TABLES’);
return $value;
}

function _GetInserts($table) {
$value = ”;
if (!($result = $this->_Query(‘SELECT * FROM ‘ . $table))) {
return false;
}
if ( $this->complete_inserts ) {
while ($row = mysql_fetch_row($result)) {
$values = ”;
foreach ($row as $data) {
$values .= ‘\” . addslashes($data) . ‘\’, ‘;
}
$values = substr($values, 0, -2);
$value .= ‘INSERT INTO ‘ . $table . ‘ VALUES (‘ . $values . ‘);’ . __SEP__ . MSB_NL;
}
} else {
$blocks_counter = 0;
$blocks = array();
while ($row = mysql_fetch_row($result)) {
$values = array();
foreach ($row as $data) {
$values[] = ‘\” . addslashes($data) . ‘\”;
}
$blocks[] = ‘(‘ . implode( ‘,’, $values ) . ‘)’;

if ( $blocks_counter < $this->inserts_block ) {
$blocks_counter++;
} else {
$value .= ‘INSERT INTO ‘ . $table . ‘ VALUES ‘ . implode( ‘,’, $blocks ) . “;” . __SEP__ . MSB_NL;
$blocks = array();
$blocks_counter = 0;
}
}
if ( count( $blocks ) ) {
$value .= ‘INSERT INTO ‘ . $table . ‘ VALUES ‘ . implode( ‘,’, $blocks ) . “;” . __SEP__ . MSB_NL;
}
}
return $value;
}

function _Retrieve() {
$value = ”;
if (!$this->_Connect()) {
return false;
}
if ($this->comments) {
$value .= ‘#’ . MSB_NL;
$value .= ‘# MySQL database dump’ . MSB_NL;
$value .= ‘# Created by MySQL_Backup class, ver. ‘ . MSB_VERSION . MSB_NL;
$value .= ‘#’ . MSB_NL;
$value .= ‘# Host: ‘ . $this->server . MSB_NL;
$value .= ‘# Generated: ‘ . date(‘M j, Y’) . ‘ at ‘ . date(‘H:i’) . MSB_NL;
$value .= ‘# MySQL version: ‘ . mysql_get_server_info() . MSB_NL;
$value .= ‘# PHP version: ‘ . phpversion() . MSB_NL;
if (!empty($this->database)) {
$value .= ‘#’ . MSB_NL;
$value .= ‘# Database: `’ . $this->database . ‘`’ . MSB_NL;
}
$value .= ‘#’ . MSB_NL . MSB_NL . MSB_NL;
}
if (!($tables = $this->_GetTables())) {
return false;
}
foreach ($tables as $table) {
if (!($table_dump = $this->_DumpTable($table))) {
$this->error = mysql_error();
return false;
}
$value .= $table_dump;
}
return $value;
}

function _SaveToFile($fname, $sql, $compress) {
if ($compress) {
if (!($zf = gzopen($fname, ‘w9’))) {
$this->error = ‘Can\’t create the output file.’;
return false;
}
gzwrite($zf, $sql);
gzclose($zf);
} else {
if (!($f = fopen($fname, ‘w’))) {
$this->error = ‘Can\’t create the output file.’;
return false;
}
fwrite($f, $sql);
fclose($f);
}
return true;
}

function _DownloadFile($fname, $sql, $compress) {
header(‘Content-disposition: filename=’ . $fname);
header(‘Content-type: application/octetstream’);
header(‘Pragma: no-cache’);
header(‘Expires: 0’);
echo ($compress ? gzencode($sql) : $sql);
return true;
}
}

?>

[/syntax]

ادامه مطلب

نمونه تابع ورود کاربر با زبان PHP :

// function to escape data and strip tags
function safestrip($string){
       $string = strip_tags($string);
       $string = mysql_real_escape_string($string);
       return $string;
}

//function to show any messages
function messages() {
   $message = '';
   if($_SESSION['success'] != '') {
       $message = '<span class="success" id="message">'.$_SESSION['success'].'</span>';
       $_SESSION['success'] = '';
   }
   if($_SESSION['error'] != '') {
       $message = '<span class="error" id="message">'.$_SESSION['error'].'</span>';
       $_SESSION['error'] = '';
   }
   return $message;
}

// log user in function
function login($username, $password){

 //call safestrip function
 $user = safestrip($username);
 $pass = safestrip($password);

 //convert password to md5
 $pass = md5($pass);

  // check if the user id and password combination exist in database
  $sql = mysql_query("SELECT * FROM table WHERE username = '$user' AND password = '$pass'")or die(mysql_error());

  //if match is equal to 1 there is a match
  if (mysql_num_rows($sql) == 1) {

                          //set session
                          $_SESSION['authorized'] = true;

                          // reload the page
                         $_SESSION['success'] = 'Login Successful';
                         header('Location: ./index.php');
                         exit;


   } else {
               // login failed save error to a session
               $_SESSION['error'] = 'Sorry, wrong username or password';
  }
}

 

ادامه مطلب

کد PHP وارد کردن یک فایل CSV در MySQL :

<?php

$databasehost = "localhost";
$databasename = "test";
$databasetable = "sample";
$databaseusername ="test";
$databasepassword = "";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "filename.csv";


$addauto = 0;


$save = 1;
$outputfile = "output.sql";
/********************************/

if (!file_exists($csvfile)) {
        echo "File not found. Make sure you specified the correct path.\n";
        exit;
}

$file = fopen($csvfile,"r");

if (!$file) {
        echo "Error opening data file.\n";
        exit;
}

$size = filesize($csvfile);

if (!$size) {
        echo "File is empty.\n";
        exit;
}

$csvcontent = fread($file,$size);

fclose($file);

$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
@mysql_select_db($databasename) or die(mysql_error());

$lines = 0;
$queries = "";
$linearray = array();

foreach(split($lineseparator,$csvcontent) as $line) {

        $lines++;

        $line = trim($line," \t");

        $line = str_replace("\r","",$line);

        /************************************
        This line escapes the special character. remove it if entries are already escaped in the csv file
        ************************************/
        $line = str_replace("'","\'",$line);
        /*************************************/

        $linearray = explode($fieldseparator,$line);

        $linemysql = implode("','",$linearray);

        if($addauto)
                $query = "insert into $databasetable values('','$linemysql');";
        else
                $query = "insert into $databasetable values('$linemysql');";

        $queries .= $query . "\n";

        @mysql_query($query);
}

@mysql_close($con);

if ($save) {

        if (!is_writable($outputfile)) {
                echo "File is not writable, check permissions.\n";
        }

        else {
                $file2 = fopen($outputfile,"w");

                if(!$file2) {
                        echo "Error writing to the output file.\n";
                }
                else {
                        fwrite($file2,$queries);
                        fclose($file2);
                }
        }

}

echo "Found a total of $lines records in this csv file.\n";

?>

 

ادامه مطلب

کد PHP دریافت اطلاعات تصویر :

<?php

  list($width, $height, $type, $attr) = getimagesize("url/to/image.jpg");

  echo "عرض تصویر : " . $width;
  echo "طول تصویر :  " . $height;
  echo "نوع تصویر : " . $type;
  echo "صفت : " . $attr;

?>

 

 

ادامه مطلب

کد PHP دریافت آدرس IP کاربر :

 

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
     $ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
     $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
     $ip=$_SERVER['REMOTE_ADDR'];
}

 

ادامه مطلب

تابع PHP دریافت آخرین وضعیت کاربر Twitter :

<?php

function getTwitterStatus($userid){
$url = "https://api.twitter.com/1/statuses/user_timeline/$userid.xml?count=1&include_rts=1callback=?";

$xml = simplexml_load_file($url) or die("could not connect");

       foreach($xml->status as $status){
       $text = $status->text;
       }
       echo $text;
 }

// USAGE
getTwitterStatus("chriscoyier");

?>

 

ادامه مطلب

تابع PHP دریافت اطلاعات جغرافیایی (Geo-IP) یک IP :

 

       $ip='94.219.40.96';
       print_r(geoCheckIP($ip));
       //Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen )

       //Get an array with geoip-infodata
       function geoCheckIP($ip)
       {
               //check, if the provided ip is valid
               if(!filter_var($ip, FILTER_VALIDATE_IP))
               {
                       throw new InvalidArgumentException("IP is not valid");
               }

               //contact ip-server
               $response=@file_get_contents('http://www.netip.de/search?query='.$ip);
               if (empty($response))
               {
                       throw new InvalidArgumentException("Error contacting Geo-IP-Server");
               }

               //Array containing all regex-patterns necessary to extract ip-geoinfo from page
               $patterns=array();
               $patterns["domain"] = '#Domain: (.*?)&nbsp;#i';
               $patterns["country"] = '#Country: (.*?)&nbsp;#i';
               $patterns["state"] = '#State/Region: (.*?)<br#i';
               $patterns["town"] = '#City: (.*?)<br#i';

               //Array where results will be stored
               $ipInfo=array();

               //check response from ipserver for above patterns
               foreach ($patterns as $key => $pattern)
               {
                       //store the result in array
                       $ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
               }

               return $ipInfo;
       }

?>

 

ادامه مطلب

تابع PHP دریافت تاریخ آخرین بروزرسانی فایل :

function getFiledate($file, $format) {
       if (is_file($file)) {
               $filePath = $file;
               if (!realpath($filePath)) {
                       $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
       }
               $fileDate = filemtime($filePath);
               if ($fileDate) {
                       $fileDate = date("$format",$fileDate);
                       return $fileDate;
               }
               return false;
       }
       return false;
}

 

ادامه مطلب

کد PHP پیدا کردن بالاترین عدد نام فایل :

$latest = getNewest("/path/to/folder/*_partname.xml");

function getNewest($xmlfile){
   foreach (glob($xmlfile) as $filename) {
       $c = explode('_', basename($filename));
       $files[$c[0]] = $filename;
   }
   ksort($files, SORT_NUMERIC);
   $latest = array_pop($files);
   if (file_exists($latest)){
       return $latest;
   }
   return false;
}

 

ادامه مطلب

کد PHP گرفتن تعداد مشترکان خوراک FeedBurner با استفاده از cURL :

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://feedburner.google.com/api/awareness/1.0/GetFeedData?id=7qkrmib4r9rscbplq5qgadiiq4');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
$content = curl_exec($ch);
$subscribers = get_match('/circulation="(.*)"/isU',$content);
curl_close($ch);

 

ادامه مطلب