Fatal error: Allowed memory size of 8388608 bytes exhausted


Hits: 4080  

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:

ini_set("memory_limit","64M");

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.


<?php
class Memory
{
public $var='3.1415962654';
}

$baseMemory = memory_get_usage();

for($i=0;$i<=100000;$i++)
{
$a=new Memory;
$a->self=$a;
if($i%500===0)
{
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

Source:

http://phplens.com/lens/php-book/optimizing-debugging-php.php
http://php.net/manual/en/features.gc.performance-considerations.php

Recursive Function for Nested Categories


Hits: 5300  

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` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pid` int(11) NOT NULL,
`name` varchar(255) NOT NULL
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


<?php

/*

Function lists all items in table tb_category

- id

- pid

- name

*/

$HOST="localhost";

$DB="categories";

$USER="root";

$PASS="";

mysql_connect($HOST,$USER,$PASS);

mysql_select_db($DB);

function RecursiveCat($pid)

{

static $level=0;

static $strid="";

static $strname="";

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

while($row=mysql_fetch_assoc($sql))

{

$id=$row['id'];

$level--;

$pad="";

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

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

$rid=RecursiveCat($id);

$strid[]=$row['id'];

$level++;

}

return $strname;

}

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

echo RecursiveCat(0);

echo '</select>';

?>

json_add for php


Hits: 2727  

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 😉

<?php
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: 3200  

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…
http://pecl.php.net/package/apd

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. ?>

 

 

<?php

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

 

$override->override_function('file_get_contents','fileGetContents',$url);

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

<?php 


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])) { 
  unset($this->includes[$override]); 
 } 
 $this->functions[$override] = $function; 
} 


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

if (function_exists($this->functions[$override])) {
 return $this->functions[$override]; 
} 
else 
{ 
 return false; 
} 
} 
else 
{ 
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: 5917  

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…

<?php

…….

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

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

…………..

?>

Use $set PHP array to fill select box….

CakePHP vs YII


Hits: 5482  

Have you checked my previous article on CakePHP…

http://blog.svnlabs.com/cakephp-in-svnlabs/

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
RBAC
– Test Case (PHPUnit, Selenium)
EAccelerator
– jQuery
– Zend support

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

Framework vs CMS


Hits: 2067  

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: 3018  

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

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

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

$files = array(‘svnlabs/1.gif’,
svnlabs/resume.doc’,
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

<?php
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: 5428  
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.


<?php

require_once "HTTP/Request.php";

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

$req->setBasicAuth("login""pass");

$req->setMethod(HTTP_REQUEST_METHOD_POST);

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

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

echo 
"Error occurred during file upload!";

} else {

$response $req->sendRequest();

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

} else {

echo 
"File successfully uploaded!";

}

}

?>

Magic of PEAR – Date TimeZone


Hits: 4373  

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….

<?php
// 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”);

?>

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

Converting between time zones

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

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

// set local time zone
$d->setTZByID(“GMT”);

// convert to foreign time zone
$d->convertTZByID(“IST”);

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

Output:
Thursday, 07 August 1981 16:06:27

Calculating GMT offsets

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

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

// set local time zone
$d->setTZByID(“PST”);

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

Adding and subtracting timespans

<?php
// 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…. 😉