PHP Fatal error: Allowed memory size

I am receiving the following error whilst trying to download huge size file from live php serve

php Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 1705654 bytes)

Here are some options to increase PHP memory allocation


  1. If you can edit or override the system php.ini file, increase the memory limit. For example, memory_limit = 256M
  2. If you cannot edit or override the system php.ini file, add php_value memory_limit 256M to your .htaccess file
  3. If you cannot edit or override the system php.ini file, add php_value memory_limit 256M to your .htaccess file
You can increase the memory allowed to php script by executing the following line above all the codes in the script


 ini_set('memory_limit','-1');  

But is never good. If you want to read a very large file, it is a best practise to copy it bit by bit. Try the following code for best practise.


 $path = 'path_to_file_.txt';  
 $file = fopen($path, 'r');  
 $len = 1024; // 1MB is reasonable for me. You can choose anything though, but do not make it too big  
 $output = fread( $file, $len );  
 while (!feof($file)) {  
   $output .= fread( $file, $len );  
 }  
 fclose($file);  
 echo 'Output is: ' . $output;  

Nikunj K

Phasellus facilisis convallis metus, ut imperdiet augue auctor nec. Duis at velit id augue lobortis porta. Sed varius, enim accumsan aliquam tincidunt, tortor urna vulputate quam, eget finibus urna est in augue.