出现这个错误消息,有什么建议吗?

允许内存大小为33554432字节已耗尽(已尝试分配 43148176字节)的PHP


当前回答

我在php7.2和laravel 5.6中遇到了同样的问题。我只是增加变量memory_limit = 128M在php.ini的数量作为我的应用程序的需求。可能是256M/512M/1048M.....现在它工作得很好。

其他回答

如果您的脚本需要分配这么大的内存,那么您可以通过在php文件中添加这一行来增加内存限制

ini_set('memory_limit', '44M');

其中,4400万是你预计消费的数量。

但是,大多数情况下,此错误消息意味着脚本正在做错误的事情,增加内存限制只会导致相同的错误消息,但数字不同。

因此,您必须重写代码,而不是增加内存限制,这样它就不会分配那么多内存。例如,在较小的块中处理大量数据,取消保存大值但不再需要的变量,等等。

在Wordpress中切换到一个新主题后,我收到了同样的错误信息。PHP运行的是5.3版本,所以我切换到了7.2。这解决了问题。

我注意到许多答案只是试图增加脚本的内存数量,但通常情况下,这意味着由于不可预见的容量或大小,某些东西对内存过于自由。显然,如果你不是脚本的作者,除非你有野心,否则你要受作者的摆布:)PHP文档甚至说内存问题是由于“写得不好的脚本”。

值得一提的是,ini_set('memory_limit', '-1');(无限制)会导致服务器不稳定,因为0字节空闲=坏事。相反,要根据脚本要做的事情和机器上可用的内存数量找到一个合理的平衡。

一个更好的方法是:如果您是脚本的作者(或雄心勃勃),您可以使用xdebug调试此类内存问题。最新版本(2.6.0 -发布2018-01-29)带回了内存分析,显示哪些函数调用消耗了大量内存。它暴露了脚本中难以找到的问题。通常情况下,低效率是在一个循环中,它不期望它接收到的容量,但每种情况都将留给读者作为练习:)

xdebug文档很有帮助,但它可以归结为3个步骤:

安装它-可通过apt-get和yum等 配置它- xdebug.ini: xdebug。Profiler_enable = 1, xdebug。Profiler_output_dir = /where/ever/ 在QCacheGrind、KCacheGrind等工具中查看配置文件

I was also having the same problem, looked for phpinfo.ini, php.ini or .htaccess files to no avail. Finally I have looked at some php files, opened them and checked the codes inside for memory. Finally this solution was what I come out with and it worked for me. I was using wordpress, so this solution might only work for wordpress memory size limit problem. My solution, open default-constants.php file in /public_html/wp-includes folder. Open that file with code editor, and find memory settings under wp_initial_constants scope, or just Ctrl+F it to find the word "memory". There you will come over WP_MEMORY_LIMIT and WP_MAX_MEMORY_LIMIT. Just increase it, it was 64 MB in my case, I increased it to 128 MB and then to 200 MB.

// Define memory limits.
if ( ! defined( 'WP_MEMORY_LIMIT' ) ) {
    if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) {
        define( 'WP_MEMORY_LIMIT', $current_limit );
    } elseif ( is_multisite() ) {
        define( 'WP_MEMORY_LIMIT', '200M' );
    } else {
        define( 'WP_MEMORY_LIMIT', '128M' );
    }
}

if ( ! defined( 'WP_MAX_MEMORY_LIMIT' ) ) {
    if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) {
        define( 'WP_MAX_MEMORY_LIMIT', $current_limit );
    } elseif ( -1 === $current_limit_int || $current_limit_int > 268435456 /* = 256M */ ) {
        define( 'WP_MAX_MEMORY_LIMIT', $current_limit );
    } else {
        define( 'WP_MAX_MEMORY_LIMIT', '256M' );
    }
}

顺便说一句,请不要做下面的代码,因为这是不好的做法:

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

如果您试图读取一个文件,这将占用PHP中的内存。例如,如果您试图打开并读取一个MP3文件(例如,$data = file("http://mydomain.com/path/sample.mp3")),它将把它全部拉到内存中。

正如Nelson所建议的,如果您确实需要使用这么多内存,您可以提高您的最大内存限制。