array_map Perform Function on Each Item of an Array

by in , 0

array_map() takes two arguments. The first argument is the function to perform on the second argument (which is an array). Returns a new array.

$original = array('<p>Paragraph</p>', '<strong>Bold</strong>');
$new = array_map('strip_tags', $original);

// $new is now array('Paragraph', 'Bold');

How to Parse JSON in php

by in , 0

<?php
   $json ='{"id":1,"name":"foo","interest":["wordpress","php"]} ';

   $obj=json_decode($json);

   echo $obj->interest[1]; //prints php
?>

Pagination Function PHP example

by in , 0

function pagination($item_count, $limit, $cur_page, $link)
{
       $page_count = ceil($item_count/$limit);
       $current_range = array(($cur_page-2 < 1 ? 1 : $cur_page-2), ($cur_page+2 > $page_count ? $page_count : $cur_page+2));

       // First and Last pages
       $first_page = $cur_page > 3 ? '<a href="'.sprintf($link, '1').'">1</a>'.($cur_page < 5 ? ', ' : ' ... ') : null;
       $last_page = $cur_page < $page_count-2 ? ($cur_page > $page_count-4 ? ', ' : ' ... ').'<a href="'.sprintf($link, $page_count).'">'.$page_count.'</a>' : null;

       // Previous and next page
       $previous_page = $cur_page > 1 ? '<a href="'.sprintf($link, ($cur_page-1)).'">Previous</a> | ' : null;
       $next_page = $cur_page < $page_count ? ' | <a href="'.sprintf($link, ($cur_page+1)).'">Next</a>' : null;

       // Display pages that are in range
       for ($x=$current_range[0];$x <= $current_range[1]; ++$x)
               $pages[] = '<a href="'.sprintf($link, $x).'">'.($x == $cur_page ? '<strong>'.$x.'</strong>' : $x).'</a>';

       if ($page_count > 1)
               return '<p class="pagination"><strong>Pages:</strong> '.$previous_page.$first_page.implode(', ', $pages).$last_page.$next_page.'</p>';
}

Usage:

pagination(
   total amount of item/rows/whatever,
   limit of items per page,
   current page number,
   url
);

Example:

pagination(45, 20, 1, 'http://example.com/userlist/%d.html');

Output HTML:

<p class="pagination">
   <strong>Pages:</strong>
   <a href="http://example.com/userlist/1.html"><strong>1</strong></a>,
   <a href="http://example.com/userlist/2.html">2</a>,
   <a href="http://example.com/userlist/3.html">3</a>
   | <a href="http://example.com/userlist/2.html">Next</a>
</p>

Tutorial Output Buffering

by in , 0

<?php
 
  // Start buffering
  ob_start();

  // Output stuff (probably not this simple, might be custom CMS functions...
  echo 'Print to the screen!!!';

  // Get value of buffering so far
  $getContent = ob_get_contents();

  // Stop buffering
  ob_end_clean();

  // Do stuff to $getContent as needed

  // Use it
  echo 'Now: ' . $getContent;

?>

Tutorial Options to Truncate Strings

by in , 0

Technique #1: Simple

function myTruncate($string, $limit, $break=".", $pad="...") {
        if(strlen($string) <= $limit) return $string; 
        if(false !== ($breakpoint = strpos($string, $break, $limit))) { 
            if($breakpoint < strlen($string) - 1) { 
                $string = substr($string, 0, $breakpoint) . $pad; } 
            } return $string; 
}

Technique #2: Simple

function ellipsis($text, $max=100, $append='&hellip;') {
       if (strlen($text) <= $max) return $text;
       $out = substr($text,0,$max);
       if (strpos($text,' ') === FALSE) return $out.$append;
       return preg_replace('/\w+$/','',$out).$append;
}

Usage:

<?php
$text = "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.";
echo ellipsis($text,100);
?>

Technique #3: More Options

Options to use PHP's php_tidy to fix up broken HTML, or to strip HTML entirely.

function summarise( $input, $break = " ", $end_text = "...", $limit = 255, $tidy_html = 1, $strip_html = 0 ) {
               if ( strlen( $input ) >= $limit ) {
                       $breakpoint = strpos( $input, $break, $limit );
                       $input = substr( $input, 0, $breakpoint ) . $end_text;
               }
               if ( $tidy_html == 1 ) {
                       ob_start(  );
                       $tidy = new tidy;
                       $config = array( 'indent' => true, 'output-xhtml' => true, 'wrap' => 200, 'clean' => true, 'show-body-only' => true );
                       $tidy->parseString( $input, $config, 'utf8' );
                       $tidy->cleanRepair(  );
                       $input = $tidy;
               }
               if ( $strip_html == 1 ) {
                       $input = strip_tags( $input );
               }
               return $input;
}

Technique #4: Without a function

<?php

$long_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$max_length = 40; // we want to show only 40 characters.

if (strlen($long_text) > $max_length)
{
 $short_text = (substr($long_text,0,$max_length-1)); // make it $max_length chars long
 $short_text .= "..."; // add an ellipses ... at the end
 $short_text .= "<a href='http://example.com/page.html'>Read more</a>"; // add a link
 echo $short_text;
}
else
{
// string is already less than $max_length, so display the string as is
echo $long_text;
}

?>

Reference URL

Tutorial MySQL Restore Class

by in , 0

<?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 );
       }
}

?>

Tutorial MySQL Database Access Class

by in , 0

<?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;
       }
}
?>