Fatal error: Allowed memory size of 8388608 bytes exhausted

Hits: 4235  

PHP Fatal error: Allowed memory size of X bytes exhausted (tried to allocate Y) in file.php

1. memory_limit globally from php.ini
memory_limit = 64M

2. memory_limit using .htaccess
php_value memory_limit 64M

3. memory_limit inside a php script.
ini_set(‘memory_limit’, ’64M’);

To change the memory limit for one specific script by including a line such as this at the top of the script:


The 12M sets the limit to 64 megabytes. If this doesn’t work, keep increasing the memory limit until your script fits.

You can change permanently for all PHP scripts running on the server by adding a line to the server’s php.ini file:

memory_limit = 64M

Keep in mind that a huge memory limit is a poor substitute for good coding. Some applications like data scrappers are run infrequently and require lots of memory like importing and processing a big data file using RSS, XML, JSON API etc.

Make sure each time script required server memory resources; need to release them when script/process finish first iteration to save memory uses 😉

PHP function might help….

1. unset — Unset a given variable

2. memory_get_usage — Returns the amount of memory allocated to PHP

3. memory_get_peak_usage — Returns the peak of memory allocated by PHP

4. __destruct your object references upon disposing of an object

5. The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. Its goal is to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.

6. Turn PHP scripts into Linux daemons

7. Xdebug’s Profiler is a powerful tool that gives you the ability to analyze your PHP code and determine bottlenecks or generally see which parts of your code are slow and could use a speed boost.

class Memory
public $var='3.1415962654';

$baseMemory = memory_get_usage();

$a=new Memory;
echo sprintf('%8d: ',$i), memory_get_usage() - $baseMemory,"\n";

Fatal error: Allowed memory size of 8388608 bytes exhausted


Quality is not a product.. it is a process



Recursive Function for Nested Categories

Hits: 5419  

Nested Categories over Drop Down

Nested Categories

Categories and its sub categories are always useful while developing simple to huge applications. Here is a simple php code to create multi-leveled nested categories on select box to those categories.

CREATE TABLE `tb_category` (
`pid` int(11) NOT NULL,
`name` varchar(255) NOT NULL



Function lists all items in table tb_category

- id

- pid

- name








function RecursiveCat($pid)


static $level=0;

static $strid="";

static $strname="";

$sql=mysql_query("select * from tb_category where pid = '$pid' order by name ");






for($p=1;$p<($level*-1);$p++) $pad.="&nbsp;&nbsp;&nbsp;- ";

$strname.='<option value="'.$row['id'].'">'.$pad.$row['name'].'</option>';





return $strname;


echo '<select name="cat">';

echo RecursiveCat(0);

echo '</select>';


json_add for php

Hits: 2818  

JSON (JavaScript Object Notation) is a lightweight data-interchange format.

1. Easy for humans to read and write.
2. Easy for machines to parse and generate.
3. Collection of name/value pairs.
4. Used for C, C++, C#, Java, JavaScript, Perl, Python, and many others.
5. Compatible with universal data structures – array, vector, list, or sequence.

json_decode — Decodes a JSON string
json_encode — Returns the JSON representation of a value
json_add — Review below code 😉

function json_add($old, $new) {  // function to add json strings  $old, $new are arrays
        $old_arr = json_decode($old, true);
        if(is_array($old_arr)) {
            $new_arr = array_merge($old_arr, $new);
            return json_encode($new_arr);
        else {
            // it means first column updation
            return json_encode ( $new );

here $json_str is json formated string in which we have to add new $array
json_add($json_str, $array);    

Every opportunity is trouble… Every trouble is opportunity 😉

Override PHP Function

Hits: 3308  

PHP have PECL (PHP Extension & Community Library) function to override built-in functions by replacing them in the symbol table.

bool override_function ( string $function_name , string $function_args , string $function_code )


  1. <?php
  2. override_function(‘strlen’, ‘$string’, ‘return override_strlen($string);’);
  3. function override_strlen($string){
  4. return strlen($string);
  5. }
  6. ?>

The above function “override_function()” require APD i.e. Advanced PHP Debugger.

We can find more about APD here…

Linux users can install apd using below command

# pecl install apd

There is an alternate way to override PHP functions, we can use below class “override” to override any built-in PHP function if PECL is not installed on server 😉


  1. <?php
  2. $or = new override ();
  3. $or->override_function(‘strlen’, ‘override_strlen‘, ‘return override_strlen($string);’);
  4. function override_strlen($string){
  5. return strlen($string);
  6. }
  7. ?>




$url = 'http://www.svnlabs.com';
$override = new override();



if ($over_func_name = $override->override_check('file_get_contents')) {
    $result=call_user_func($over_func_name, $url);

function fileGetContents($url)
  /// statements



PHP Function OverRide Class


class override 

var $functions = array(); 
var $includes = array(); 

function override_function($override, $function, $include) { 
 if ($include) { 
 $this->includes[$override] = $include; 
 else if (isset($this->includes[$override])) { 
 $this->functions[$override] = $function; 

function override_check($override) { 
 if (isset($this->includes[$override])) { 
 if (file_exists($this->includes[$override])) { 

if (function_exists($this->functions[$override])) {
 return $this->functions[$override]; 
 return false; 
return false; 


Make a habit of creating things modular, that means “pluggable” and “unpluggable”.

PHP ORM – Create select box with mysql set or enum

Hits: 6014  

PHP have rich set of functions to solve real time problems in programming and web development.. thanks to Rasmus Lerdorf

eval — Evaluate a string as PHP code

A SET datatype can hold any number of strings from a predefined list of strings. The ENUM datatype restricts to a single member of the set of predefined strings, the SET datatype allows to store any of the values together, from none to all of them.

CREATE TABLE svnlabs_set (
name SET(‘lamp’,’web’,’linux’,’joomla’)

CREATE TABLE svnlabs_enum (
name ENUM(‘lamp’,’web’,’linux’,’joomla’)

If we want to fill the html select box with these two tables…

SHOW COLUMNS FROM svnlabs_set;
> set(‘lamp’,’web’,’linux’,’joomla’)

SHOW COLUMNS FROM svnlabs_enum;
> enum(‘lamp’,’web’,’linux’,’joomla’)

now based on column type set list of string values from mysql to php array…



// if column type is set
$arr = “\$set=”.str_replace(“set”, “array(“, $column[‘Type’]));

// if column type is enum
$arr = “\$set=”.str_replace(“enum”, “array(“, $column[‘Type’]));



Use $set PHP array to fill select box….

CakePHP vs YII

Hits: 5588  

Have you checked my previous article on CakePHP…


Yii (Yes, it is) — a high-performance component-based PHP framework best for developing large-scale Web applications. Yii have features, including MVC, DAO/ActiveRecord, I18N/L10N, caching, jQuery-based AJAX support, authentication and role-based access control, scaffolding, input validation, widgets, events, theming, Web services, and so on. Written in strict OOP, Yii is easy to use and is extremely flexible and extensible.

YII Features:

– Magic overloading functions
Lazy loading
– Authentication / Validation
– Widgets (sharing extensions)
– Yii console
– High-performance
– Templates
MVC Push-Pull
– Test Case (PHPUnit, Selenium)
– jQuery
– Zend support

I am currently reviewing YII in comparison with CakePHP … Keep in touch 🙂

Framework vs CMS

Hits: 2147  

Framework: A web application framework is a software framework that is designed to support the development of dynamic websites, Web applications and Web services.

1. CodeIgniter
2. CakePHP
3. Zend
4. Symfony

CMS: A content management system (CMS) is the collection of procedures used to manage work flow in a collaborative environment. These procedures can be manual or computer-based.

1. Joomla
2. Drupal
3. Magento
4. CRE Loaded Oscomerce
5. WordPress

Create ZIP archives with PHP script and PEAR class

Hits: 3098  

We can use PEAR to process zip files in PHP using Archive_Zip….

First set PEAR path in php include path using set_include_path

Make Zipped file

include (‘Archive/Zip.php’);        // include PEAR ZIP package

$obj = new Archive_Zip(‘test.zip’);  // zipped file name

$files = array(‘svnlabs/1.gif’,
svnlabs/invoice.xls’);   // files add to zip

if ($obj->create($files)) {
echo ‘Files zipped successfully!’;
} else {
echo ‘Error in file zipping’;
List Zip file elements

include (‘Archive/Zip.php’);        // include PEAR ZIP package

$obj = new Archive_Zip(‘test.zip’); // Input zip file

$files = $obj->listContent();       // zip information

foreach ($files as $f) {
foreach ($f as $s => $v) {
echo “$s: $v\r\n”;
echo “\r\n”;
I really enjoyed programming with PEAR…

PHP – File Upload Stream

Hits: 5621  
File Upload Stream
File Upload Stream

PHP supports upload file stream… we can stream data to server using PHP stream_open() & stream_write() functions.

There is alternate method in PEAR to transfer files to server1 to server2. PEAR have HTTP package for uploading files.

HTTP_Request supports GET/POST/HEAD/TRACE/PUT/DELETE, Basic authentication, Proxy, Proxy Authentication, SSL, file uploads etc.


require_once "HTTP/Request.php";

$req =& new HTTP_Request("http://domain.com/upload");



$result $req->addFile("data""/home/svnlabs.mp4");

if (
PEAR::isError($result)) {

"Error occurred during file upload!";

} else {

$response $req->sendRequest();

if (
PEAR::isError($response)) {echo "Error occurred during file upload!";

} else {

"File successfully uploaded!";




Magic of PEAR – Date TimeZone

Hits: 4455  

PEAR is a framework and distribution system for reusable PHP components.

How we get PEAR packages with php files?

Add block of code to the php file….

// include PEAR class
include (“Date.php”);

// initialize Date object
$d = new Date(“1981-08-07 01:30:11”);

// retrieve date to display
echo $d->getDate();

// retrieve date as formatted string
echo $d->format(“%A, %d %B %Y %T”);


1981-08-07 01:30:11
Friday, 07 August 1981 01:30:11

Converting between time zones

// include class
include (“Date.php”);

// initialize object
$d = new Date(“1981-08-07 10:36:27”);

// set local time zone

// convert to foreign time zone

// retrieve converted date/time
echo $d->format(“%A, %d %B %Y %T”);

Thursday, 07 August 1981 16:06:27

Calculating GMT offsets

// include class
include (“Date.php”);

// initialize object
$d = new Date(“2006-08-08 10:26:27”);

// set local time zone

// get raw offset from GMT, in msec
echo $d->tz->getRawOffset();

Adding and subtracting timespans

// include class
include (“Date.php”);

// initialize object
$d = new Date(“1951-09-13 16:55:11”);

// add 01:20 to it
$d->addSpan(new Date_Span(“0,1,20,0”));

// subtract 00:05 from it
$d->subtractSpan(new Date_Span(“0,0,5,0”));

// retrieve date as formatted string
echo $d->format(“%A, %d %B %Y %T”);

PHP have rich library to manage “Daylight saving time”… we can use PEAR for DST

United States begins Daylight Saving Time at 2:00 a.m. on the second Sunday in March and reverts to standard time on the first Sunday in November.

Daylight Saving Time
Daylight Saving Time

Enjoy programming with PEAR…. 😉