Posts Tagged ‘PHP’

Simple timer class for benchmarking in PHP

Wednesday, February 3rd, 2010

Here’s a simple timer class that I wrote to help with benchmarking tests while running PHP code, in order to see how quick code is running, although it can be used for any timer functionality really. I have clearly documented the code below, along with an example of how to use the timer

Timer Class Download

/*******************************************************************************
*                                     Timer class                              *
*                             Created: 27th January 2010                       *
*                             ©Copyright Jay Gilford 2010                      *
*                              http://www.jaygilford.com                       *
*                            email: jay [at] jaygilford.com                    *
*******************************************************************************/


class timer {
    private $_start = 0;
    private $_elapsed = 0;
    private $_running = false;
    
    /**
     * timer::construct()
     * set the timer running of $start is true
     * 
     * @param bool $start
     * @return true
     */
    public function __construct($start = false) {
        // If true is passed, start the timer immediately
        if($start === true)
            $this->start();
            
        return true;
    }
    
    /**
     * timer::start()
     * start the timer
     * 
     * @return true
     */
    public function start() {
        // Reset timer
        $this->reset(false);
        // Set status to running
        $this->_running = true;
        // Set timer running
        $this->_start = $this->_time();
            
        return true;
    }
    
    /**
     * timer::stop()
     * stops the timer and returns the total time elapsed
     * 
     * @return mixed
     */
    public function stop() {
        // If the timer isn't running return false
        if($this->_running === false)
            return false;
        
        // Set the final elapsed time and stop the timer
        $this->_elapsed = $this->_get_elapsed();
        $this->_running = false;
        $this->_start = 0;
        
        // Return the timers total elapsed time
        return $this->_elapsed;
    }
    
    /**
     * timer::pause()
     * pauses/unpauses the timer
     * 
     * @return NULL
     */
    public function pause() {
        // If the timer isn't running return false
        if($this->_running === false)
            return false;

        // If the timer is paused set the timer from the current time
        if($this->_start == 0) {
            $this->_start = $this->_time();
            
        // Otherwise add the currently elapsed time to the total
        // elapsed time and pause the timer
        }else{
            $this->_elapsed = $this->_get_elapsed();
            $this->_start = 0;
        }
    }
    
    /**
     * timer::elapsed()
     * returns the total time elapsed since the timer started
     * 
     * @return float
     */
    public function elapsed() {
        return $this->_get_elapsed();
    }
    
    /**
     * timer::reset()
     * resets the timers variables back to default
     * 
     * @param bool $start
     * @return
     */
    public function reset($start = false) {
        // Reset all variables
        $this->_start = 0;
        $this->_elapsed = 0;
        $this->_running = false;
        
        // If $start is true restart the timer immediately
        if($start === true)
            $this->start();
        
        return true;        
    }
    
    /**
     * timer::_time()
     * returns the current unix time (with milliseconds)
     * 
     * @return float
     */
    private function _time() {
    	$time = explode(' ', microtime());
    	$time =  (float)$time[1] + $time[0];
        return $time;
    }
    
    /**
     * timer::_get_elapsed()
     * Returns the current elapsed time
     * 
     * @return float
     */
    private function _get_elapsed() {
        if($this->_running === false || $this->_start == 0)
            return $this->_elapsed;
        
        return $this->_elapsed + ($this->_time() - $this->_start);
    }
}

Here is a simple example of how to use the class for working out SQL execution times

include 'timer.class.php';
$db_timer = new timer();

// Connect to database here and create the query to be run
mysql_connect('localhost', 'root', '');
mysql_select_db('database');


$query = "SELECT * FROM table";

// Start timer before executing query
$db_timer->start();
$result = mysql_query($query);

// Pause timer
$db_timer->pause();

// Echo out the selected data
while($row = mysql_fetch_assoc($result)) {
    echo print_r($row, true);
}

// Create another query
$query = "SELECT * FROM table2";

// Unpause the timer
$db_timer->pause();

// Execute the query
$result = mysql_query($query);

// Stop the timer and get the total execution time
$total_time = $db_timer->stop();

// Display details
echo 'SQL queries took '.$total_time.' seconds to execute in total';

If you have any questions or comments including possible improvements feel free to comment or send me a message via the contact page

Using the PHP Document Object Model (DOM) to get all page links

Wednesday, January 27th, 2010

Further to the article I wrote about parsing links from a html page, here is a more elegant and accurate solution to getting every link using the Document Object Model (DOM)

/**
 * @author Jay Gilford
 */

/**
 * get_links()
 * 
 * @param string $url
 * @return array
 */
function get_links($url) {
    
    // Create a new DOM Document to hold our webpage structure
    $xml = new DOMDocument();
    
    // Load the url's contents into the DOM (the @ supresses any errors from invalid XML)
    @$xml->loadHTMLFile($url);
    
    // Empty array to hold all links to return
    $links = array();
    
    //Loop through each  and  tag in the dom and add it to the link array
    foreach($xml->getElementsByTagName('a') as $link) {
        $links[] = array('url' => $link->getAttribute('href'), 'text' => $link->nodeValue);
    }
    
    //Return the links
    return $links;
}

The code above is clearly documented as to how it all works. To call the function simply use
$links = get_links('http://www.example.com');
changing the website link to the page you require the links off. You could also expand this code to give you further details for the links such as the no follow attributes and so forth

If you have any questions about this feel free to contact me as always

Also please note that this requires PHP 5 in order for you to be able to use the DOMDocument

Number to text converting PHP class

Monday, November 2nd, 2009

One thing that gets asked quite a bit on forums is how to convert a number into words in PHP, so I thought I’d write a small class that can do this
Number to text Class Download
Here is the code for the class

class num2text {
    private $_original = 0;
    private $_parsed_number_text = '';
    private $_single_nums = array(1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 =>
        'Nine', );

    private $_teen_nums = array(0 => 'Ten', 1 => 'Eleven', 2 => 'Twelve', 3 => 'Thirteen', 4 => 'Fourteen', 5 => 'Fifteen', 6 => 'Sixteen', 7 =>
        'Seventeen', 8 => 'Eighteen', 9 => 'Nineteen', );

    private $_tens_nums = array(2 => 'Twenty', 3 => 'Thirty', 4 => 'Forty', 5 => 'Fifty', 6 => 'Sixty', 7 => 'Seventy', 8 => 'Eighty', 9 =>
        'Ninety', );

    private $_chunks_nums = array(1 => 'Thousand', 2 => 'Million', 3 => 'Billion', 4 => 'Trillion', 5 => 'Quadrillion', 6 => 'Quintrillion', 7 =>
        'Sextillion', 8 => 'Septillion', 9 => 'Octillion', 9 => 'Nonillion', 9 => 'Decillion', );

    function __construct($number) {
        $this->_original = trim($number);
        $this->parse();
    }
    
    public function parse($new_number = NULL) {
        if($new_number !== NULL) {
            $this->_original = trim($new_number);
        }
        if($this->_original == 0) return 'Zero';
        
        $num = str_split($this->_original, 1);
        krsort($num);
        $chunks = array_chunk($num, 3);
        krsort($chunks);
        
        $final_num = array();
        foreach ($chunks as $k => $v) {
            ksort($v);
            $temp = trim($this->_parse_num(implode('', $v)));
            if($temp != '') {
                $final_num[$k] = $temp;
                if (isset($this->_chunks_nums[$k]) && $this->_chunks_nums[$k] != '') {
                    $final_num[$k] .= ' '.$this->_chunks_nums[$k];
                }
            }
        }
        $this->_parsed_number_text = implode(', ', $final_num);
        return $this->_parsed_number_text;
    }
    
    public function __toString() {
        return $this->_parsed_number_text;
    }

    private function _parse_num($num) {
        $temp = array();
        if (isset($num[2])) {
            if (isset($this->_single_nums[$num[2]])) {
                $temp['h'] = $this->_single_nums[$num[2]].' Hundred';
            }
        }

        if (isset($num[1])) {
            if ($num[1] == 1) {
                $temp['t'] = $this->_teen_nums[$num[0]];
            } else {
                if (isset($this->_tens_nums[$num[1]])) {
                    $temp['t'] = $this->_tens_nums[$num[1]];
                }
            }
        }
        
        if (!isset($num[1]) || $num[1] != 1) {
            if (isset($this->_single_nums[$num[0]])) {
                if (isset($temp['t'])) {
                    $temp['t'] .= ' '.$this->_single_nums[$num[0]];
                } else {
                    $temp['u'] = $this->_single_nums[$num[0]];
                }
            }
        }
        return implode(' and ', $temp);
    }
}

Using this class is as simple as using two lines of code such as

$n2s = new num2string('123456');
echo $n2s;

Should you wish to parse more than one string after this, you can use

echo $n2s->parse('87654321');

It really is that simple to use
Please be aware that in order for all numbers to work, you must enter them as strings

how to get all links from a web page

Monday, October 26th, 2009

A question that gets asked all the time on forums is “How do I get all links on a web page” inside of <a> tags, so here’s some code with full commenting for each line

/**
 * @author Jay Gilford
 */

// regular expression pattern to match all links on a page
$pattern = '%]+href="(?P[^"]+)"[^>*]*>(?P[^< ]+)%si';

// Webpage URL to get links from
$url = 'http://www.jaygilford.com/';

// Fetch contents of whole page
$page_content = file_get_contents($url);

// Get all matches of links and put them into the $matches variable
preg_match_all($pattern, $page_content, $matches);

// Variable to hold all of our urls and their text
$urls = array();

// Loop through each array item
foreach($matches['url'] as $k=>$v) {
    // combine the url and text into it's own key for ease of access
    $urls[$k] = array('url' => $v,'text' => $matches['text'][$k]);
}

// For display purposes only to show the contents of $urls
echo print_r($urls, true);

If you have any questions regarding this feel free to contact me. Details can be found on the about page

Completely customisable PHP pagination class

Monday, January 12th, 2009

If you need to paginate your database results quickly and reliably then this could be the class for you. It allows you complete access to all attributes of the pagination, from the link templates to the results padding, and auto querying.

Simple pagination class download


/*******************************************************************************
*                                  Pagination class                            *
*                             Created: 12th January 2009                       *
*                             Updated: 16th Octember 2011                      *
*                         ©Copyright Jay Gilford 2009 - 2011                   *
*                              http://www.jaygilford.com                       *
*                            email: jay [at] jaygilford.com                    *
*******************************************************************************/
 
class pagination
{
    ################################
    # PRIVATE VARS - DO NOT ALTER  #
    ################################
    private $_query = '';
    private $_current_page = 1;
    private $_padding = 2;
    private $_results_resource;
    private $_output;
 
    ################################
    #       RESULTS VARS           #
    ################################
    public $results_per_page = 10;          #Number of results to display at a time
    public $total_results = 0;              #Total number of records
    public $total_pages = 0;                #Total number of pages
 
    public $link_prefix = '/?page=';        #String for link to go before the page number
    public $link_suffix = '';               #String for link to go after the page number
    public $page_nums_separator = ' | ';    #String to go between the page number links
 
    ################################
    #      ERROR HOLDING VAR       #
    ################################
    public $error = null;
 
    ################################
    # PAGINATION TEMPLATE DEFAULTS #
    ################################
    public $tpl_first = '&laquo; | ';
    public $tpl_last = ' | &raquo; ';
 
    public $tpl_prev = '&lsaquo; | ';
    public $tpl_next = ' | &rsaquo; ';
 
    public $tpl_page_nums = '{page}';
    public $tpl_cur_page_num = '{page}';
 
    /**
     * In the above templates {link} is where the link will be inserted and {page} is
     * where the page numbers will be inserted. Other than that, you can modify them
     * as you please
     *
     * NOTE: You should have a separator of some sort at the right of $tpl_first and
     * $tpl_prev as above in the defaults, and also have a separator of some sort
     * before the $tpl_next and $tpl_last templates
     **/
 
 
    ##################################################################################
 
 
    public function __construct($page, $query)
    {
        #Check page number is a positive integer greater than 0 and assign it to $this->_current_page
        if ((int)$page > 0)
            $this->_current_page = (int)$page;
 
        #Remove any LIMIT clauses in the query string and set if
        $query = trim(preg_replace('/[\s]+LIMIT[\s]+\d+([\s,]*,[^\d]*\d+)?/i', '', $query));
        if (empty($query)) {
            return false;
        } else {
            $this->_query = $query;
        }
    }
 
    /**
     * pagination::paginate()
     *
     * Processes all values and query strings and if successful
     * returns a string of html text for use with pagination bar
     *
     * @return string;
     */
    public function paginate()
    {
        $output = '';
 
        #########################################
        # GET TOTAL NUMBER OF RESULTS AND PAGES #
        #########################################
        $result = mysql_query($this->_query);
        if (!$result) {
            $this->error = __line__ . ' - ' . mysql_error();
            return false;
        }
        $this->total_results = mysql_num_rows($result);
        $this->total_pages = ceil($this->total_results / $this->results_per_page);
 
        ########################
        # FREE RESULT RESOURCE #
        ########################
 
        ################################
        # IF TOTAL PAGES <= 1 RETURN 1 #
        ################################
        if ($this->total_pages <= 1)
        {
        	$this->_results_resource = $result;
			$this->_output = '1';
			return $this->_output;
        }
 
        mysql_free_result($result);
 
        ###################################################
        # CHECK CURRENT PAGE ISN'T GREATER THAN MAX PAGES #
        ###################################################
        if ($this->_current_page > $this->total_pages)
            $this->_current_page = $this->total_pages;
 
        ######################################
        # SET FIRST AND LAST PAGE VALUES AND #
        # ERROR CHECK AGAINST INVALID VALUES #
        ######################################
        $start = ($this->_current_page - $this->_padding > 0) ? $this->_current_page - $this->
            _padding : '1';
        $finish = ($this->_current_page + $this->_padding <= $this->total_pages) ? $this->
            _current_page + $this->_padding : $this->total_pages;
 
        ###########################################
        # CREATE LIMIT CLAUSE AND ASSIGN TO QUERY #
        ###########################################
        $limit = ' LIMIT ' . ($this->results_per_page * ($this->_current_page - 1)) .
            ',' . $this->results_per_page;
        $query = $this->_query . $limit;
 
        #############################################
        # RUN QUERY AND ASSIGN TO $_result_resource #
        #############################################
        $result = mysql_query($query);
        if ($result === false) {
            $this->error = __line__ . ' - ' . mysql_error();
            return false;
        }
        $this->_results_resource = $result;
 
        ###########################################
        # ADD FIRST TO OUTPUT IF CURRENT PAGE > 1 #
        ###########################################
        if ($this->_current_page > 1) {
            $output .= preg_replace('/\{link\}/i', 'href="' . $this->link_prefix . '1' . $this->
                link_suffix . '"', $this->tpl_first);
        }
 
        ##########################################
        # ADD PREV TO OUTPUT IF CURRENT PAGE > 1 #
        ##########################################
        if ($this->_current_page > 1) {
            $output .= preg_replace('/\{link\}/i', 'href="' . $this->link_prefix . ($this->
                _current_page - 1) . $this->link_suffix . '"', $this->tpl_prev);
        }
 
        ################################################
        # GET LIST OF LINKED NUMBERS AND ADD TO OUTPUT #
        ################################################
        $nums = array();
        for ($i = $start; $i <= $finish; $i++) {
            if ($i == $this->_current_page) {
                $nums[] = preg_replace('/\{page\}/i', $i, $this->tpl_cur_page_num);
            } else {
                $patterns = array('/\{link\}/i', '/\{page\}/i');
                $replaces = array('href="' . $this->link_prefix . $i . $this->link_suffix . '"', $i);
                $nums[] = preg_replace($patterns, $replaces, $this->tpl_page_nums);
            }
        }
        $output .= implode($this->page_nums_separator, $nums);
 
        ##################################################
        # ADD NEXT TO OUTPUT IF CURRENT PAGE < MAX PAGES #
        ##################################################
        if ($this->_current_page < $this->total_pages) {
            $output .= preg_replace('/\{link\}/i', 'href="' . $this->link_prefix . ($this->
                _current_page + 1) . $this->link_suffix . '"', $this->tpl_next);
        }
 
        ############################################
        # ADD LAST TO OUTPUT IF FINISH < MAX PAGES #
        ############################################
        if ($this->_current_page < $finish) {
            $output .= preg_replace('/\{link\}/i', 'href="' . $this->link_prefix . $this->total_pages . $this->link_suffix . '"', $this->
                tpl_last);
        }
 
        $this->_output = $output;
        return $output;
    }
 
 
    /**
     * pagination::padding()
     *
     * Sets the padding for the pagination string
     *
     * @param int $val
     * @return bool
     */
    public function padding($val)
    {
        if ((int)$val < 1)
            return false;
 
        $this->_padding = (int)$val;
        return true;
    }
 
 
    /**
     * pagination::resource()
     *
     * Returns the resource of the results query
     *
     * @return resource
     */
    function resource()
    {
        return $this->_results_resource;
    }
 
 
    /**
     * pagination::__tostring()
     * returns the last pagination output
     *
     * @return string
     */
    function __tostring()
    {
        if (trim($this->_output)) {
            return trim($this->_output);
        }else{
        	return '';
        }
    }
}

Instructions on class usage:
To create an instance of the class, call it with your current page and the query you want to run
$paginator = new pagination($page_num_variable, 'SELECT * FROM `table_name`');
After that, you need to set up any of the parameters for the class such as
$paginator->results_per_page = 15;
$paginator->padding(5);
$paginator->link_prefix = '/results/page/';
$paginator->link_suffix = '/';
$paginator->page_nums_separator = ' -=- ';

Once you have done that, you can call the paginate method
NOTE: you must be connected to your database in order to run this method as it uses the mysql_query function.
The paginate method returns the string of html for you to insert and sets the $pagination->resource() to be the resource id of the query that is run for the pagination

You can use either the returned paginate() string or echo the variable name of the class and it will generate the pagination
So either$page_links = $paginator->paginate();
And then
echo $page_links; wherever you want the links to go.

Alternatively you can use
$paginator->paginate();
and then
echo $paginator;

When you are using mysql_fetch_array() or mysql_fetch_assoc to get your data from your database, you simply need to replace your old resource handle with $paginator->resource();
Example:

while($row = mysql_fetch_assoc($paginator->resource()))
{
    echo $row['field_name'];
}

If you have any questions, bugs or suggestions regarding this class, feel free to contact me either by comment or via one of the contact methods in the contact section

Jay