TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack (3) Thread Tools Search this Thread Display Modes
Old 09-12-2007, 01:29 PM   3 links from elsewhere to this Post. Click to view. #1 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default Memory Management with Declare

I'm sure it's happened with the best of us. A script suddenly gets stuck in a loop and saps all the memory from the server. However, aside from programmer-induced loops, memory errors can also be a good way for a hacker to gain insightful information in to the way your application is setup.

Not only that, but it'd be really nice to monitor how much memory your scripts are consuming, would it not? This is where declare steps into the door way and makes its presence felt.

The declare construct allows you to execute a function every so many ticks. A tick is loosely defined as every line a low level action takes place. Thus when a mathematical equation takes place, or a value being assigned to a variable - even a curly brace to end if or while statements is considered a tick.

A simple tick can be setup like so:

PHP Code:
function talkphp_example()
{
    echo 
'TalkPHP is the place to be for PHP discussions.<br />';
}

register_tick_function('talkphp_example');

declare(
ticks 1)
{
    
$iA 1;
    
$iB $iA 4.5;
    
$iC = ($iB $iA) * 8;

The 2 lines you may not be familiar with are the following:
  • register_tick_function: Specifies the function to call on every tick.
  • declare(ticks = 1): Declared for the block of code that follows as indicated by the curly braces. The ticks specifies the amount of lines to wait for before executing the tick register function, in our case talkphp_example.

Putting it to some use

The usefulness of declare may not be apparent immediately. However, it has some nice advantages when you wish to monitor something. Such as in our case, memory management. There are some other purposes I've thought of (or, in admission, read about):
  • Memory management
  • CPU Management
  • Sustain Database Connection
  • Flow Control Management (Using __LINE__)

Let's take a look at our memory management function for the declare construct:

PHP Code:
define('MEMORY_MAX'50000); // Bytes
    
function memory_profiler($bReturn false)
{
    static 
$iMemory 0;
    
    if(
$bReturn)
    {
        return 
$iMemory ' bytes';
    }
    
    if((
$iTmpMemory memory_get_usage()) > $iMemory)
    {
        if(
$iTmpMemory >= MEMORY_MAX)
        {
            die(
'Consumed too much memory');
        }
        
        
$iMemory $iTmpMemory;
    }

This will keep a tab on the memory being consumed by the script and die when the script consumes too much as specified by the define. Although PHP, by default, may consume 8 megabytes - this is rather a lot and somewhat unnecessary for any non-GD or any other server intensive actions.

We then specify our tick function as well as our declare construct for the chunk of code we wish to monitor:

PHP Code:
register_tick_function('memory_profiler');

declare(
ticks 1)
{
    
$szText 'We adore TalkPHP.com';
    
$szText str_replace('We''I'$szText);
    
$szText $szText '!';

Once you have done this the tick function will be called 4 times:
  • Tick 1: $szText = 'We adore TalkPHP.com';
  • Tick 2: $szText = str_replace('We', 'I', $szText);
  • Tick 3: $szText = $szText . '!';
  • Tick 4: }

Any programming outside of the declare block will not count towards our memory management handling. Thus to make the declare global we would use the declare construct like so:

PHP Code:
declare(ticks 1);

$iA 1;
$iB $iA 4.5;
$iC = ($iB $iA) * 8
To display the total amount of memory our script sucked from our system like a blood-hungry vampire, we can display it at the bottom using the following:

PHP Code:
echo memory_profiler(true); 
Instead of the unfriendly die, a header may be a more user-friendly way to inform the user something unexpected has occurred and the script is consuming too much memory. This can be done like so:

PHP Code:
header('location: http://www.talkphp.com/memory_limit.html');
exit(); 
Note: Don't forget to use a FQDN (fully qualified domain name) in the header() as it's a new request entirely. Also, do not forget to specify to exit the script after the header. The header is sent to the client but it's entirely up to the browser to act on the header issued.

Performance Concerns and Closure

Just remember that calling this function inside a declare is a nice addition, but keep in mind the performance issues that may arise if your tick function contains server intensive actions. The declare function can be exceedingly powerful for absolutely all sorts of various things. Your task for today? Dream up some weird and wonderful uses and get back to us!
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.

Last edited by Wildhoney : 09-12-2007 at 02:05 PM.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 09-12-2007, 02:04 PM   #2 (permalink)
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 437
Thanks: 22
Karl is on a distinguished road
Default

Great article. I imagine it'll come in handy for some of the complex scripts I write. Cheers.
Karl is offline  
Reply With Quote
Old 10-18-2007, 03:44 PM   #3 (permalink)
The Prestige
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
sketchMedia is on a distinguished road
Default

very useful code, thanks
sketchMedia is offline  
Reply With Quote
Reply


LinkBacks (?)
LinkBack to this Thread: http://www.talkphp.com/advanced-php-programming/1089-memory-management-declare.html
Posted By For Type Date
StumbleUpon - Wildhoney25's web site reviews and blog This thread Refback 01-12-2008 11:37 PM
PHP Miscellaneous Memory Management with Declare Tutorial This thread Refback 01-10-2008 04:33 AM
StumbleUpon - grumpycoder's web site reviews and blog This thread Refback 12-24-2007 12:36 AM

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 10:26 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design