这是什么?
这是关于您在 PHP 编程时可能遇到的警告、错误和通知的一些答案,但不知道如何修复它们。这也是一个社区 Wiki,因此邀请每个人参与添加和维护此列表。
这是为什么呢?
诸如“标头已发送”或“调用”之类的问题非对象的成员” 经常出现在 Stack Overflow 上。这些问题的根本原因总是相同的。因此,这些问题的答案通常会重复它们,然后向操作员展示在特定情况下要更改哪一行。这些答案不会给网站增加任何价值,因为它们仅适用于 OP 的特定代码。其他有相同错误的用户无法轻松地从中读出解决方案,因为它们太本地化了。这是可悲的,因为一旦你了解了根本原因,修复错误就变得微不足道了。因此,此列表试图以通用的方式解释该解决方案。
我应该在这里做什么?
如果您的问题已被标记为与此问题重复,请在下面找到您的错误消息并将修复应用于您的代码。答案通常包含进一步调查的链接,以防仅从一般答案中不清楚。
如果您想做出贡献,请添加您“最喜欢的”错误消息、警告或通知,每个答案一个,简短描述其含义(即使只是在其手册页中突出显示术语),可能的解决方案或调试方法以及有价值的现有问答列表。另外,请随意改进任何现有的答案。
列表
另外,请参阅:
What is this?
This is a number of answers about warnings, errors, and notices you might encounter while programming PHP and have no clue how to fix them. This is also a Community Wiki, so everyone is invited to participate adding to and maintaining this list.
Why is this?
Questions like "Headers already sent" or "Calling a member of a non-object" pop up frequently on Stack Overflow. The root cause of those questions is always the same. So the answers to those questions typically repeat them and then show the OP which line to change in their particular case. These answers do not add any value to the site because they only apply to the OP's particular code. Other users having the same error cannot easily read the solution out of it because they are too localized. That is sad because once you understood the root cause, fixing the error is trivial. Hence, this list tries to explain the solution in a general way to apply.
What should I do here?
If your question has been marked as a duplicate of this one, please find your error message below and apply the fix to your code. The answers usually contain further links to investigate in case it shouldn't be clear from the general answer alone.
If you want to contribute, please add your "favorite" error message, warning or notice, one per answer, a short description what it means (even if it is only highlighting terms to their manual page), a possible solution or debugging approach and a listing of existing Q&A that are of value. Also, feel free to improve any existing answers.
The List
- Nothing is seen. The page is empty and white. (also known as White Page/Screen Of Death)
- Code doesn't run/what looks like parts of my PHP code are output
- Warning: Cannot modify header information - headers already sent
- Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given a.k.a.
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
- Warning: [function] expects parameter 1 to be resource, boolean given
- Warning: [function]: failed to open stream: [reason]
- Warning: open_basedir restriction in effect
- Warning: Division by zero
- Warning: Illegal string offset 'XXX'
- Warning: count(): Parameter must be an array or an object that implements Countable
- Parse error: syntax error, unexpected '['
- Parse error: syntax error, unexpected T_XXX
- Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
- Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
- Parse error: syntax error, unexpected 'require_once' (T_REQUIRE_ONCE), expecting function (T_FUNCTION)
- Parse error: syntax error, unexpected T_VARIABLE
- Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
- Fatal error: Maximum execution time of XX seconds exceeded
- Fatal error: Call to a member function ... on a non-object or null
- Fatal Error: Call to Undefined function XXX
- Fatal Error: Cannot redeclare XXX
- Fatal error: Can't use function return value in write context
- Fatal error: Declaration of AAA::BBB() must be compatible with that of CCC::BBB()'
- Return type of AAA::BBB() should either be compatible with CCC::BBB(), or the #[\ReturnTypeWillChange] attribute should be used
- Fatal error: Using $this when not in object context
- Fatal error: Object of class Closure could not be converted to string
- Fatal error: Undefined class constant
- Fatal error: Uncaught TypeError: Argument #n must be of type x, y given
- Notice: Array to string conversion (< PHP 8.0) or Warning: Array to string conversion (>= PHP 8.0)
- Notice: Trying to get property of non-object error
- Notice: Undefined variable or property
- "Notice: Undefined Index", or "Warning: Undefined array key"
- Notice: Undefined offset XXX [Reference]
- Notice: Uninitialized string offset: XXX
- Notice: Use of undefined constant XXX - assumed 'XXX' / Error: Undefined constant XXX
- MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
- Strict Standards: Non-static method [<class>::<method>] should not be called statically
- Warning: function expects parameter X to be boolean/string/integer
- HTTP Error 500 - Internal server error
- Deprecated: Arrays and strings offset access syntax with curly braces is deprecated
- Warning: foreach() argument must be of type array|object, <type> given
Also, see:
发布评论
评论(30)
警告:无法修改标头信息 - 标头已发送
当您的脚本尝试将 HTTP 标头发送到客户端但之前已经有输出时会发生这种情况,这导致标头已发送到客户端。
这是一个
E_WARNING
并且它不会停止脚本。一个典型的例子是这样的模板文件:
session_start()
函数将尝试将带有会话 cookie 的标头发送到客户端。但是 PHP 在将元素写入输出流时已经发送了标头。您必须将
session_start()
移至顶部。您可以通过浏览触发警告的代码之前的行并检查其输出位置来解决此问题。将任何标头发送代码移到该代码之前。
一个经常被忽视的输出是 PHP 结束
?>
之后的新行。当?>
是文件中的最后一个内容时,省略它被认为是标准做法。同样,此警告的另一个常见原因是当开头前面有空格、行或不可见字符时,导致 Web 服务器发送标头和空格/换行符当 PHP 开始解析时将无法提交任何标头。
如果您的文件中有多个
代码块,则它们之间不应有任何空格。 (注意:如果您有自动构造的代码,则可能有多个块)
还要确保代码中没有任何字节顺序标记,例如,当脚本的编码为带有 BOM 的 UTF-8 时。
相关问题:
Warning: Cannot modify header information - headers already sent
Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.
This is an
E_WARNING
and it will not stop the script.A typical example would be a template file like this:
The
session_start()
function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the<html>
element to the output stream. You'd have to move thesession_start()
to the top.You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.
An often overlooked output is new lines after PHP's closing
?>
. It is considered a standard practice to omit?>
when it is the last thing in the file. Likewise, another common cause for this warning is when the opening<?php
has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.If your file has more than one
<?php ... ?>
code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.
Related Questions:
致命错误:在非对象上调用成员函数...
发生类似于
xyz->method()
的代码,其中xyz
不是对象,因此无法调用该方法
。这是一个致命错误,它将停止脚本(向前兼容性注意:从 PHP 7 开始它将成为一个可捕获的错误)。
大多数情况下,这表明代码缺少对错误条件的检查。在调用对象的方法之前验证该对象实际上是一个对象。
A 典型的示例是
在上面的示例中,无法准备查询,并且
prepare()
会将false
分配给$statement
。尝试调用execute()
方法将导致致命错误,因为false
是“非对象”,因为该值是布尔值。找出为什么你的函数返回一个布尔值而不是一个对象。例如,检查
$pdo
对象中最近发生的错误。有关如何调试的详细信息将取决于如何处理相关特定函数/对象/类的错误。如果
->prepare
失败,那么您的$pdo
数据库句柄对象 未传递到当前作用域。找到它的定义位置。然后将其作为参数传递,将其存储为属性,或通过全局范围共享。另一个问题可能是有条件地创建一个对象,然后尝试调用该条件块之外的方法。例如,
通过尝试在条件块之外执行方法,您的对象可能无法定义。
相关问题:
Fatal error: Call to a member function ... on a non-object
Happens with code similar to
xyz->method()
wherexyz
is not an object and therefore thatmethod
can not be called.This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).
Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.
A typical example would be
In the example above, the query cannot be prepared and
prepare()
will assignfalse
to$statement
. Trying to call theexecute()
method will then result in the Fatal Error becausefalse
is a "non-object" because the value is a boolean.Figure out why your function returned a boolean instead of an object. For example, check the
$pdo
object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.If even the
->prepare
is failing then your$pdo
database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example
By attempting to execute the method outside the conditional block, your object may not be defined.
Related Questions:
什么也看不见。页面是空的、白色的。
也称为死亡白页或死亡白屏。当错误报告关闭并且发生致命错误(通常是语法错误)时,就会发生这种情况。
如果您启用了错误日志记录,您将在错误日志中找到具体的错误消息。这通常位于一个名为“php_errors.log”的文件中,或者位于中央位置(例如,许多 Linux 环境中的
/var/log/apache2
),或者位于脚本本身的目录中(有时使用在共享托管环境中)。有时,暂时启用错误显示可能更简单。然后白页将显示错误消息。请小心,因为访问该网站的每个人都可以看到这些错误。
通过在脚本顶部添加以下 PHP 代码可以轻松完成此操作:
该代码将打开错误显示并将报告设置为最高级别。
由于
ini_set()
是在运行时执行的,因此对解析/语法错误没有影响。这些错误将出现在日志中。如果您还想在输出中显示它们(例如在浏览器中),则必须设置display_startup_errors
指令设置为true
。在php.ini
或.htaccess
中或通过 运行时之前影响配置的任何其他方法。您可以使用相同的方法设置 log_errors 和error_log 指令来选择您自己的日志文件位置。
查看日志或使用显示屏,您将获得更好的错误消息以及脚本停止的代码行。
相关问题:
相关错误:
Nothing is seen. The page is empty and white.
Also known as the White Page Of Death or White Screen Of Death. This happens when error reporting is turned off and a fatal error (often syntax error) occurred.
If you have error logging enabled, you will find the concrete error message in your error log. This will usually be in a file called "php_errors.log", either in a central location (e.g.
/var/log/apache2
on many Linux environments) or in the directory of the script itself (sometimes used in a shared hosting environment).Sometimes it might be more straightforward to temporarily enable the display of errors. The white page will then display the error message. Take care because these errors are visible to everybody visiting the website.
This can be easily done by adding at the top of the script the following PHP code:
The code will turn on the display of errors and set reporting to the highest level.
Since the
ini_set()
is executed at runtime it has no effects on parsing/syntax errors. Those errors will appear in the log. If you want to display them in the output as well (e.g. in a browser) you have to set thedisplay_startup_errors
directive totrue
. Do this either in thephp.ini
or in a.htaccess
or by any other method that affects the configuration before runtime.You can use the same methods to set the log_errors and error_log directives to choose your own log file location.
Looking in the log or using the display, you will get a much better error message and the line of code where your script comes to halt.
Related questions:
Related errors:
“注意:未定义的索引”或“警告:未定义的数组键”
当您尝试通过数组中不存在的键访问数组时,会发生这种情况。
未定义索引
通知的典型示例是 (demo)两者都是
spinach数组中不存在
和1
,导致E_NOTICE
被触发。在 PHP 8.0 中,这是一个 E_WARNING。解决方案是在访问该索引之前确保索引或偏移量存在。这可能意味着您需要修复程序中的错误,以确保这些索引在您期望的时候确实存在。或者这可能意味着您需要使用
array_key_exists
或isset
:如果您有如下代码:
则
$_POST['message']< /code> 时不会被设置此页面首次加载,您将收到上述错误。只有当提交表单并第二次运行此代码时,数组索引才会存在。您通常会通过以下方式检查这一点:
相关问题:
"Notice: Undefined Index", or "Warning: Undefined array key"
Happens when you try to access an array by a key that does not exist in the array.
A typical example of an
Undefined Index
notice would be (demo)Both
spinach
and1
do not exist in the array, causing anE_NOTICE
to be triggered. In PHP 8.0, this is an E_WARNING instead.The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using
array_key_exists
orisset
:If you have code like:
then
$_POST['message']
will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:Related Questions:
警告:mysql_fetch_array() 期望参数 1 为资源,布尔值
首先:
当您尝试从 mysql_query 的结果中获取数据但查询失败时,就会发生这种情况。
这是一个警告,不会停止脚本,但会使您的程序出错。
您需要通过相关问题检查
mysql_query
返回的结果:
相关错误:
其他也期望 MySQL 结果资源作为参数的 mysql* 函数将出于相同的原因产生相同的错误。
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
First and foremost:
This happens when you try to fetch data from the result of
mysql_query
but the query failed.This is a warning and won't stop the script, but will make your program wrong.
You need to check the result returned by
mysql_query
byRelated Questions:
Related Errors:
Other
mysql*
functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.致命错误:不在对象上下文中使用 $this
$this
是一个特殊变量PHP 不能被赋值。如果在不存在的上下文中访问它,则会给出此致命错误。此错误可能发生:
如果静态调用非静态方法。示例:
如何修复:再次检查您的代码,
$this
只能在对象上下文中使用,并且永远不应该在静态方法。此外,静态方法不应访问非静态属性。使用self::$static_property
访问静态属性。如果类方法中的代码已复制到普通函数或只是全局范围并且保留
$this
特殊变量。如何修复:检查代码并用不同的替换变量替换
$this
。相关问题:
Fatal error: Using $this when not in object context
$this
is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.This error can occur:
If a non-static method is called statically. Example:
How to fix: review your code again,
$this
can only be used in an object context, and should never be used in a static method. Also, a static method should not access the non-static property. Useself::$static_property
to access the static property.If code from a class method has been copied over into a normal function or just the global scope and keeping the
$this
special variable.How to fix: Review the code and replace
$this
with a different substitution variable.Related Questions:
致命错误:调用未定义的函数 XXX
当您尝试调用尚未定义的函数时会发生这种情况。常见原因包括缺少扩展和包含、条件函数声明、函数声明中的函数或简单的拼写错误。
示例 1 - 条件函数声明
在这种情况下,
fn()
将永远不会被声明,因为$someCondition
不为 true。示例 2 - 函数声明中的函数
在这种情况下,只有在调用
createFn()
时才会声明fn
。请注意,后续调用createFn()
将触发有关现有函数重新声明的错误。您可能还会在 PHP 内置函数中看到这一点。尝试在官方手册中搜索该函数,看看“扩展名”是什么(PHP模块) ) 它属于什么版本,以及哪些版本的 PHP 支持它。
如果缺少扩展,请安装该扩展并在 php.ini 中启用它。请参阅 PHP 手册中的安装说明,了解您的函数所在的扩展。您还可以使用包管理器启用或安装该扩展(例如 Debian 或 Ubuntu 中的
apt
,yum(Red Hat 或 CentOS 中的 yum
),或共享托管环境中的控制面板。如果该函数是在您正在使用的 PHP 的较新版本中引入的,您可能会在手册或其注释部分找到替代实现的链接。如果它已从 PHP 中删除,请查找有关原因的信息,因为它可能不再需要。
如果缺少包含,请确保在调用函数之前包含声明该函数的文件。
如果出现拼写错误,请更正拼写错误。
相关问题:
Fatal error: Call to undefined function XXX
Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.
Example 1 - Conditional Function Declaration
In this case,
fn()
will never be declared because$someCondition
is not true.Example 2 - Function in Function Declaration
In this case,
fn
will only be declared oncecreateFn()
gets called. Note that subsequent calls tocreateFn()
will trigger an error about Redeclaration of an Existing function.You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.
In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g.
apt
in Debian or Ubuntu,yum
in Red Hat or CentOS), or a control panel in a shared hosting environment.If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.
In case of missing includes, make sure to include the file declaring the function before calling the function.
In case of typos, fix the typo.
Related Questions:
解析错误:语法错误,意外的 T_XXX
当您在意外的位置有
T_XXX
令牌 时会发生这种情况,不平衡(多余)的括号、使用短标签而不在 php.ini 中激活它等等。相关问题:
如需进一步帮助,请参阅:
Parse error: syntax error, unexpected T_XXX
Happens when you have
T_XXX
token in unexpected place, unbalanced (superfluous) parentheses, use of short tag without activating it in php.ini, and many more.Related Questions:
For further help see:
致命错误:无法在写入上下文中使用函数返回值
这通常发生在直接使用
empty
的函数时。示例:
这是因为
empty
是一种语言构造由于它不是函数,因此在 5.5 之前的 PHP 版本中不能使用表达式作为参数来调用它。在 PHP 5.5 之前,empty()
的参数必须是变量,但在 PHP 5.5+ 中允许任意表达式(例如函数的返回值) 。empty
尽管它的名字如此,但实际上并不检查变量是否为“空”。相反,它检查变量是否不存在,或者== false
。表达式(例如示例中的is_null(null)
)将始终被视为存在,因此这里empty
仅检查它是否等于 false。您可以将此处的empty()
替换为!
,例如if (!is_null(null))
,或者显式与 false 进行比较,例如if (is_null(null) == false)
。相关问题:
Fatal error: Can't use function return value in write context
This usually happens when using a function directly with
empty
.Example:
This is because
empty
is a language construct and not a function, it cannot be called with an expression as its argument in PHP versions before 5.5. Prior to PHP 5.5, the argument toempty()
must be a variable, but an arbitrary expression (such as a return value of a function) is permissible in PHP 5.5+.empty
, despite its name, does not actually check if a variable is "empty". Instead, it checks if a variable doesn't exist, or== false
. Expressions (likeis_null(null)
in the example) will always be deemed to exist, so hereempty
is only checking if it is equal to false. You could replaceempty()
here with!
, e.g.if (!is_null(null))
, or explicitly compare to false, e.g.if (is_null(null) == false)
.Related Questions:
MySQL:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以了解使用 close ... at line ... 的正确语法。
此错误通常是由于您忘记正确转义传递给 MySQL 查询的数据而引起的。
不做什么(“坏主意”)的示例:
此代码可以包含在带有要提交的表单的页面中,其 URL 类似于 http://example.com/edit.php?id=10 (编辑帖子 n°10)
如果提交的文本包含单引号?
$query
最终结果是:当这个查询发送到 MySQL 时,它会抱怨语法错误,因为中间多了一个单引号。
为了避免此类错误,您必须始终在将数据用于查询之前对其进行转义。
在 SQL 查询中使用数据之前转义数据也非常重要,因为如果不这样做,您的脚本将容易受到 SQL 注入。 SQL 注入可能会导致记录、表或整个数据库的更改、丢失或修改。这是一个非常严重的安全问题!
文档:
mysql_real_escape_string()
mysqli_real_escape_string()
MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
This error is often caused because you forgot to properly escape the data passed to a MySQL query.
An example of what not to do (the "Bad Idea"):
This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)
What will happen if the submitted text contains single quotes?
$query
will end up with:And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.
To avoid such errors, you MUST always escape the data before use in a query.
Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!
Documentation:
mysql_real_escape_string()
mysqli_real_escape_string()
解析错误:语法错误,意外 T_ENCAPSED_AND_WHITESPACE
在 PHP 8.0 及更高版本中,消息改为:
当尝试使用带引号的键引用数组值以在双引号内进行插值时,最常遇到此错误当整个复杂变量构造未包含在
{}
中时为字符串。错误情况:
这将导致
意外的T_ENCAPSED_AND_WHITESPACE
:可能的修复:
在双引号字符串中,PHP 将允许使用数组键字符串不加引号,并且不会发出
E_NOTICE
。因此,上面的内容可以写为:整个复杂数组变量和键可以包含在
{}
中,在这种情况下,它们应该被引用以避免 <代码>E_NOTICE。 PHP 文档推荐此语法适用于复杂变量。当然,上述任何的替代方法是连接数组变量而不是对其进行插值:
有关参考,请参阅变量解析部分"http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double" rel="nofollow noreferrer">PHP 字符串手册页
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
In PHP 8.0 and above, the message is instead:
This error is most often encountered when attempting to reference an array value with a quoted key for interpolation inside a double-quoted string when the entire complex variable construct is not enclosed in
{}
.The error case:
This will result in
Unexpected T_ENCAPSED_AND_WHITESPACE
:Possible fixes:
In a double-quoted string, PHP will permit array key strings to be used unquoted, and will not issue an
E_NOTICE
. So the above could be written as:The entire complex array variable and key(s) can be enclosed in
{}
, in which case they should be quoted to avoid anE_NOTICE
. The PHP documentation recommends this syntax for complex variables.Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolating it:
For reference, see the section on Variable Parsing in the PHP Strings manual page
致命错误:允许的 XXX 字节内存大小已耗尽(尝试分配 XXX 字节)
没有足够的内存来运行脚本。 PHP 已达到内存限制并停止执行。这个错误是致命的,脚本停止。 内存限制的值可以在
php.ini
文件中配置,也可以通过在脚本中使用ini_set('memory_limit', '128 M');
(这将覆盖php.ini
中定义的值)。内存限制的目的是防止单个 PHP 脚本耗尽所有可用内存并导致整个 Web 服务器瘫痪。首先要做的就是尽量减少脚本所需的内存量。例如,如果您正在将大文件读入变量或从数据库中获取许多记录并将它们全部存储在数组中,则可能会使用大量内存。更改您的代码,改为逐行读取文件或一次获取一个数据库记录,而不将它们全部存储在内存中。这确实需要对幕后发生的事情以及数据何时存储在内存中与其他地方有一定的概念认识。
如果当您的脚本没有执行内存密集型工作时发生此错误,您需要检查您的代码以查看是否存在内存泄漏。
memory_get_usage
函数是您的朋友。相关问题:
Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in the
php.ini
file or by usingini_set('memory_limit', '128 M');
in the script (which will overwrite the value defined inphp.ini
). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.The first thing to do is to minimise the amount of memory your script needs. For instance, if you're reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what's going on behind the scenes and when data is stored in memory vs. elsewhere.
If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The
memory_get_usage
function is your friend.Related Questions:
警告:[function]:无法打开流:[reason]
当您通常通过
include
、require 调用文件时会发生这种情况
或fopen
并且 PHP 找不到该文件或没有足够的权限来加载该文件。发生这种情况的原因有多种:
一个常见的错误是不使用绝对路径。通过使用完整路径或 魔法常量(例如
)可以轻松解决此问题__DIR__
或dirname(__FILE__)
:或者:
确保使用正确的路径是解决这些问题的一个步骤,这也可能与不存在的文件、文件系统的权限阻止有关访问或打开PHP 本身的 basedir 限制。
快速解决此问题的最佳方法是遵循下面的故障排除清单。
相关问题:
相关错误:
Warning: [function]: failed to open stream: [reason]
It happens when you call a file usually by
include
,require
orfopen
and PHP couldn't find the file or have not enough permission to load the file.This can happen for a variety of reasons :
One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like
__DIR__
ordirname(__FILE__)
:or:
Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.
The best way to solve this problem quickly is to follow the troubleshooting checklist below.
Related Questions:
Related Errors:
注意:未定义的变量
当您尝试使用先前未定义的变量时会发生这种情况。
一个典型的例子是
如果您之前没有定义
$counter
,上面的代码将触发通知。正确的方法是在使用变量之前对其进行设置。
类似地,变量在其作用域之外不可访问,例如在使用匿名函数时。
应该使用
use
来传递此错误。注意:未定义的属性
此错误的含义大致相同,但涉及对象的属性。重复使用上面的示例,此代码将触发错误,因为尚未设置
counter
属性。相关问题:
Notice: Undefined variable
Happens when you try to use a variable that wasn't previously defined.
A typical example would be
If you didn't define
$counter
before, the code above will trigger the notice.The correct way is to set the variable before using it
Similarly, a variable is not accessible outside its scope, for example when using anonymous functions.
This should instead be passed using
use
Notice: Undefined property
This error means much the same thing, but refers to a property of an object. Reusing the example above, this code would trigger the error because the
counter
property hasn't been set.Related Questions:
注意:使用未定义的常量 XXX - 假设为“XXX”
,或者在 PHP 7.2 或更高版本中:
警告:使用未定义的常量 XXX - 假设为“XXX”(这将在 PHP 的未来版本中引发错误)
或者在 PHP 8.0 中或更高版本:
错误:未定义常量 XXX
当代码中使用标记并且看起来是常量,但未定义该名称的常量时,会发生这种情况。
导致此通知的最常见原因之一是未能引用用作关联数组键的字符串。
例如:
另一个常见原因是变量名称前面缺少
$
(美元)符号:或者您可能拼错了其他一些常量或关键字:
它也可能是需要 PHP 扩展的标志或者当您尝试访问该库定义的常量时缺少该库。
相关问题:
Notice: Use of undefined constant XXX - assumed 'XXX'
or, in PHP 7.2 or later:
Warning: Use of undefined constant XXX - assumed 'XXX' (this will throw an Error in a future version of PHP)
or, in PHP 8.0 or later:
Error: Undefined constant XXX
This occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.
One of the most common causes of this notice is a failure to quote a string used as an associative array key.
For example:
Another common cause is a missing
$
(dollar) sign in front of a variable name:Or perhaps you have misspelled some other constant or keyword:
It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.
Related Questions:
解析错误:语法错误,意外 T_PAAMAYIM_NEKUDOTAYIM
作用域解析运算符也称为“Paamayim Nekudotayim”,源自希伯来语 פעמйם נקודתйй。这意味着“双冒号”。
如果您无意中将
::
放入代码中,通常会发生此错误。相关问题:
文档:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew פעמיים נקודתיים. which means "double colon".
This error typically happens if you inadvertently put
::
in your code.Related Questions:
Documentation:
Fatal error: Cannot redeclare class [class name]
Fatal error: Cannot redeclare [function name]
这意味着您要么使用相同的函数/类名称两次,并且需要重命名其中一个,或者是因为您在应该使用
require_once
或include_once
的地方使用了require
或include
>。当在 PHP 中声明一个类或函数时,它是不可变的,以后不能用新值声明。
考虑以下代码:
class.php
index.php
第二次调用
do_stuff()
将产生上述错误。通过将require
更改为require_once
,我们可以确定包含MyClass
定义的文件只会被加载一次,并且错误将应避免。Fatal error: Cannot redeclare class [class name]
Fatal error: Cannot redeclare [function name]
This means you're either using the same function/class name twice and need to rename one of them, or it is because you have used
require
orinclude
where you should be usingrequire_once
orinclude_once
.When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.
Consider the following code:
class.php
index.php
The second call to
do_stuff()
will produce the error above. By changingrequire
torequire_once
, we can be certain that the file that contains the definition ofMyClass
will only be loaded once, and the error will be avoided.解析错误:语法错误,意外的 T_VARIABLE
可能的情况
我似乎找不到我的代码出错的地方。这是我的完整错误:
我正在尝试的
答案
解析错误: 程序的语法问题,例如在语句末尾留下分号,或者类似上面的情况,缺少
.
运算符。当解释器遇到解析错误时,它会停止运行您的程序。简而言之,这是一个语法错误,意味着您的代码中存在某些内容阻止其正确解析并因此无法运行。
您应该做的是仔细检查错误所在的行是否有任何简单的错误。
该错误消息意味着在文件的第 x 行中,PHP 解释器本应看到一个左括号,但它却遇到了名为
T_VARIABLE
的内容。这个T_VARIABLE
东西称为token
。这是 PHP 解释器表达程序不同基本部分的方式。当解释器读入程序时,它会将您写入的内容翻译成标记列表。无论您将变量放在程序中的何处,解释器列表中都会有一个T_VARIABLE
标记。好读:解析器令牌列表
因此,请确保至少启用
E_PARSE
在您的php.ini
中。生产脚本中不应存在解析错误。我总是建议在编码时添加以下语句:
PHP 错误报告
另外,使用 IDE 是个好主意,它可以让您在键入时知道解析错误。您可以使用:
相关问题:
Parse error: syntax error, unexpected T_VARIABLE
Possible scenario
I can't seem to find where my code has gone wrong. Here is my full error:
What I am trying
Answer
Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the
.
operator. The interpreter stops running your program when it encounters a parse error.In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.
What you should do is check carefully at the lines around where the error is for any simple mistakes.
That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something called
T_VARIABLE
. ThatT_VARIABLE
thing is called atoken
. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE
token in the interpreter's list.Good read: List of Parser Tokens
So make sure you enable at least
E_PARSE
in yourphp.ini
. Parse errors should not exist in production scripts.I always recommended to add the following statement, while coding:
PHP error reporting
Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:
Related Questions:
注意:未初始化的字符串偏移量:
*
顾名思义,当您很可能尝试使用不存在的键迭代数组或从数组中查找值时,就会发生此类错误。
考虑一下您,正在尝试显示
$string
中的每个字母上面的示例将生成(在线演示):
并且,一旦脚本完成回显
D
,您就会收到错误,因为在for()
循环内,您已经告诉 PHP 向您显示从第一个到第五个字符串字符'ABCD'
存在,但由于循环从0
开始计数,并在到达4 时回显
,它会抛出偏移错误。D
类似错误:
Notice: Uninitialized string offset:
*
As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.
Consider you, are trying to show every letter from
$string
The above example will generate (online demo):
And, as soon as the script finishes echoing
D
you'll get the error, because inside thefor()
loop, you have told PHP to show you the from first to fifth string character from'ABCD'
Which, exists, but since the loop starts to count from0
and echoesD
by the time it reaches to4
, it will throw an offset error.Similar Errors:
注意:尝试获取非对象的属性错误
当您尝试在不存在对象的情况下访问对象的属性时,会发生此错误。
非对象通知的典型示例是
在这种情况下,
$users
是一个数组(因此不是对象)并且它没有任何属性。这类似于访问数组中不存在的索引或键(请参阅注意:未定义的索引)。
这个例子被简化了很多。大多数情况下,这样的通知表示未经检查的返回值,例如,如果对象不存在或只是意外的非对象值(例如,在 Xpath 结果中,具有意外格式的 JSON 结构,则库返回 NULL ) 、具有意外格式的 XML 等),但代码不会检查此类情况。
由于这些非对象通常会被进一步处理,因此在非对象上调用对象方法时通常会发生致命错误(请参阅:致命错误:在非对象上调用成员函数...)停止脚本。
通过检查错误条件和/或变量是否与期望相匹配可以轻松防止这种情况。这里有一个带有 DOMXPath 示例的通知:
问题是访问第一个项目的
nodeValue
属性(字段),而尚未检查它是否存在于$result
集合。相反,通过将变量分配给代码所操作的对象来使代码更加明确是值得的:相关错误:
Notice: Trying to get property of non-object error
Happens when you try to access a property of an object while there is no object.
A typical example for a non-object notice would be
In this case,
$users
is an array (so not an object) and it does not have any properties.This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).
This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returns
NULL
if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.
It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:
The problem is accessing the
nodeValue
property (field) of the first item while it has not been checked if it exists or not in the$result
collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:Related errors:
警告:open_basedir 限制生效
此警告可能会出现在与文件和目录访问相关的各种函数中。它警告配置问题。
当它出现时,意味着某些文件的访问已被禁止。
警告本身不会破坏任何内容,但大多数情况下,如果文件访问被阻止,脚本将无法正常工作。
修复方法通常是更改 PHP 配置,相关设置称为 < a href="http://www.php.net/manual/en/ini.core.php#ini.open-basedir" rel="nofollow noreferrer">
open_basedir
。有时会使用错误的文件或目录名称,解决方法是使用正确的文件或目录名称。
相关问题:
Warning: open_basedir restriction in effect
This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.
When it appears, it means that access has been forbidden to some files.
The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.
The fix is normally to change the PHP configuration, the related setting is called
open_basedir
.Sometimes the wrong file or directory names are used, the fix is then to use the right ones.
Related Questions:
解析错误:语法错误,意外的 '['
此错误有两种变体:
变体 1
此数组初始值设定项语法仅在 PHP 5.4 中引入;它将在之前的版本上引发解析器错误。如果可能,请升级您的安装或使用旧语法:
另请参阅此示例 来自手册。
变体 2
PHP 5.4 中还引入了数组解引用函数结果。如果无法升级,您需要使用(临时)变量:
另请参阅 这个例子来自手册。
Parse error: syntax error, unexpected '['
This error comes in two variatians:
Variation 1
This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:
See also this example from the manual.
Variation 2
Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:
See also this example from the manual.
警告:[function] 期望参数 1 为资源,给定布尔值
(警告:mysql_fetch_array() 期望参数 1 为资源,给定布尔值)
资源是 PHP 中的类型(如字符串、整数或对象)。资源是一个不透明的斑点,其本身没有任何固有的有意义的价值。资源特定于一组特定的 PHP 函数或扩展并由它们定义。例如,Mysql扩展定义了两种资源类型:
cURL 扩展定义了另外两种资源类型:
当
var_dump
编辑时,值看起来像这样:大多数资源都是这样的,某种类型的数字标识符(
(1)
) ((curl)< /代码>)。
您随身携带这些资源并将它们传递给不同的功能,这些资源对这些功能有意义。通常,这些函数在后台分配某些数据,而资源只是它们用来在内部跟踪该数据的引用。
“...期望参数 1 为资源,给定布尔值”错误通常是由于未经检查的操作导致的,该操作本应创建资源,但却返回了
false
。例如,fopen
函数具有以下描述:因此,在此代码中,
$fp
将是类型为 (stream) 的resource(x)
或false
:如果您不检查是否
fopen
操作成功或失败,从而确定$fp
是有效资源还是false
并将$fp
传递给另一个需要资源的函数,你可能会得到上面的错误:你总是需要错误检查尝试分配资源的函数的返回值并且可能失败:
相关错误:
Warning: [function] expects parameter 1 to be resource, boolean given
(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)
Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:
The cURL extension defines another two resource types:
When
var_dump
ed, the values look like this:That's all most resources are, a numeric identifier (
(1)
) of a certain type ((curl)
).You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.
The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returned
false
instead. For instance, thefopen
function has this description:So in this code,
$fp
will either be aresource(x) of type (stream)
orfalse
:If you do not check whether the
fopen
operation succeed or failed and hence whether$fp
is a valid resource orfalse
and pass$fp
to another function which expects a resource, you may get the above error:You always need to error check the return value of functions which are trying to allocate a resource and may fail:
Related Errors:
警告:非法字符串偏移“XXX”
当您尝试使用方括号语法访问数组元素时,会发生这种情况,但您是在字符串上执行此操作,而不是在数组上执行此操作,因此该操作显然不会有道理。。
示例:
如果您认为该变量应该是一个数组,请查看它来自哪里并解决那里的问题。
Warning: Illegal string offset 'XXX'
This happens when you try to access an array element with the square bracket syntax, but you're doing this on a string, and not on an array, so the operation clearly doesn't make sense.
Example:
If you think the variable should be an array, see where it comes from and fix the problem there.
警告:数组到字符串的转换
注意:数组到字符串的转换
(PHP 7.4 之前的注意事项,自 PHP 8.0 起为警告)
如果您尝试将数组视为字符串,就会发生这种情况:
数组不能简单地被
echo
'd或与字符串连接,因为结果没有明确定义。 PHP 将使用字符串“Array”代替数组,并触发通知指出这可能不是预期的结果,您应该在此处检查您的代码。您可能想要这样的东西:或者循环数组:
如果此通知出现在您不希望的地方,则意味着您认为是字符串的变量实际上是数组。这意味着您的代码中有一个错误,该错误使该变量成为数组而不是您期望的字符串。
Warning: Array to string conversion
Notice: Array to string conversion
(A notice until PHP 7.4, since PHP 8.0 a warning)
This simply happens if you try to treat an array as a string:
An array cannot simply be
echo
'd or concatenated with a string, because the result is not well defined. PHP will use the string "Array" in place of the array, and trigger the notice to point out that that's probably not what was intended and that you should be checking your code here. You probably want something like this instead:Or loop the array:
If this notice appears somewhere you don't expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.
代码无法运行/输出了看起来像我的 PHP 代码的部分内容
如果您没有看到 PHP 代码的任何结果和/或您在网页中看到部分 PHP 源代码输出,您可以非常确定你的 PHP 实际上并没有被执行。如果您在浏览器中使用“查看源代码”,您可能会看到整个 PHP 源代码文件。由于 PHP 代码嵌入在
标记中,浏览器会尝试将它们解释为 HTML 标记,结果可能看起来有些混乱。
要实际运行 PHP 脚本,您需要:
* 除非您重新配置它,否则一切都可以配置。
最后一项尤其重要。只需双击该文件,就可能会使用以下地址在浏览器中打开它:
这完全绕过了您可能正在运行的任何 Web 服务器,并且该文件不会被解释。您需要访问 Web 服务器上文件的 URL,可能类似于:
您可能还想检查是否使用短开放标记
而不是
并且您的 PHP 配置已关闭短开放标记。
另请参阅 PHP代码没有被执行,而是代码显示在页面上
Code doesn't run/what looks like parts of my PHP code are output
If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in
<?php ?>
tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.To actually run your PHP scripts, you need:
* Unless you reconfigure it, everything can be configured.
This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:
This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:
You may also want to check whether you're using short open tags
<?
instead of<?php
and your PHP configuration has turned short open tags off.Also see PHP code is not being executed, instead code shows on the page
已弃用:已弃用带有大括号的数组和字符串偏移访问语法
在 PHP 7.4.0 之前,可以通过大括号
{}
访问字符串偏移量和数组元素:自 PHP 7.4.0 起已弃用此语法生成警告:
您必须使用方括号
[]
来访问字符串偏移量和数组元素:此更改的 RFC 链接到 PHP 脚本尝试机械地修复此问题。
Deprecated: Array and string offset access syntax with curly braces is deprecated
String offsets and array elements could be accessed by curly braces
{}
prior to PHP 7.4.0:This has been deprecated since PHP 7.4.0 and generates a warning:
You must use square brackets
[]
to access string offsets and array elements:The RFC for this change links to a PHP script which attempts to fix this mechanically.
警告:mysql_connect():用户“名称”@“主机”的访问被拒绝
当您使用无效或丢失的凭据(用户名/密码)连接到 MySQL/MariaDB 服务器时,会出现此警告。因此,这通常不是代码问题,而是服务器配置问题。
请参阅
mysql_connect("localhost", "user", "pw")
上的手册页 示例。检查您是否确实使用了
$username
和$password
。(使用密码:NO)
时就会发生这种情况。通常只有本地测试服务器允许使用用户名
root
、无密码和test
数据库名称进行连接。您可以使用命令行客户端测试它们是否真正正确:
mysql --user="用户名" --password="密码"testdb
用户名和密码区分大小写,且空格不被忽略。如果您的密码包含
$
等元字符,请转义它们,或将密码放入 单引号。大多数共享主机提供商都会预先声明与 unix 用户帐户相关的 mysql 帐户(有时只是前缀或额外的数字后缀)。请参阅文档以了解模式或文档,以及用于设置密码的 CPanel 或任何界面。
请参阅 MySQL 手册,了解添加用户帐户< /a> 使用命令行。当作为管理员用户连接时,您可以发出如下查询:
创建用户“用户名”@“localhost”,由“newpassword”标识;
或者使用管理员或WorkBench 或任何其他图形工具来创建、检查或更正帐户详细信息。
如果您无法修复您的凭据,那么向互联网请求“请帮忙”将不会有任何效果。只有您和您的托管提供商拥有权限和足够的访问权限来诊断和修复问题。
使用提供商提供的主机名验证您是否可以访问数据库服务器:
ping dbserver.hoster.example.net
直接从网络服务器上的 SSH 控制台检查这一点。从本地开发客户端到共享托管服务器的测试几乎没有意义。
通常您只希望服务器名称为“localhost”,它通常使用可用的本地命名套接字。有时您可以尝试
“127.0.0.1”
作为后备。如果您的 MySQL/MariaDB 服务器侦听不同的端口,请使用
“servername:3306”
。如果失败,则可能存在防火墙问题。 (偏离主题,不是编程问题。不可能进行远程猜测帮助。)
当使用常量时,例如
DB_USER
或DB_PASSWORD
,检查它们是否确实已定义。如果您收到
“警告:为 'DB_USER'@'host' 定义的访问”
和“注意:使用未定义的常量 'DB_PASS'”
,那就是你的问题了。验证您的例如
xy/db-config.php
确实包含在内,还有什么。检查设置是否正确
GRANT
权限。仅有
用户名
+密码
对是不够的。每个 MySQL/MariaDB 帐户都可以有一组附加的权限。
这些可以限制您可以连接到哪些数据库、连接可能来自哪个客户端/服务器以及允许哪些查询。
因此,
mysql_query
也可能会显示“访问被拒绝”警告 调用,如果您无权从特定表中SELECT
或INSERT
/UPDATE
以及更常见的删除
任何内容。通过命令行连接时,您可以调整帐户权限使用管理员帐户的客户端,查询如下:
将 yourdb.* 上的所有内容授予“用户名”@“localhost”;
如果警告首先出现
Warning: mysql_query(): Access Denied for user ''@'localhost '
那么你可能有一个 php.ini 预配置的帐户/密码对.检查
mysql.default_user=
和mysql.default_password=
是否具有有意义的值。通常这是一个提供者配置。因此,请联系他们的支持人员以解决不匹配问题。
查找共享托管提供商的文档:
例如HostGator,GoDaddy,1and1,DigitalOcean、BlueHost、DreamHost,MediaTemple, ixWebhosting, lunarhosting,或者只是谷歌你的。
或者通过您的网络托管提供商的支持渠道咨询他们。
请注意,您可能还耗尽了可用连接池。由于并发连接过多,您将收到拒绝访问的警告。 (您必须调查设置。这是一个偏离主题的服务器配置问题,而不是编程问题。)
您的 libmysql 客户端版本可能与数据库服务器不兼容。通常,可以使用驱动程序中编译的 PHP 来访问 MySQL 和 MariaDB 服务器。如果您有自定义设置,或者过时的 PHP 版本,以及较新的数据库服务器,或者明显过时的数据库服务器 - 那么版本不匹配可能会阻止连接。 (不,你必须自己调查。没有人能猜出你的设置)。
更多参考:
Warning: mysql_connect(): Access denied for user 'name'@'host'
This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials (username/password). So this is typically not a code problem, but a server configuration issue.
See the manual page on
mysql_connect("localhost", "user", "pw")
for examples.Check that you actually used a
$username
and$password
.(using password: NO)
.Only the local test server usually allows to connect with username
root
, no password, and thetest
database name.You can test if they're really correct using the command line client:
mysql --user="username" --password="password" testdb
Username and password are case-sensitive and whitespace is not ignored. If your password contains meta characters like
$
, escape them, or put the password in single quotes.Most shared hosting providers predeclare mysql accounts in relation to the unix user account (sometimes just prefixes or extra numeric suffixes). See the docs for a pattern or documentation, and CPanel or whatever interface for setting a password.
See the MySQL manual on Adding user accounts using the command line. When connected as admin user you can issue a query like:
CREATE USER 'username'@'localhost' IDENTIFIED BY 'newpassword';
Or use Adminer or WorkBench or any other graphical tool to create, check or correct account details.
If you can't fix your credentials, then asking the internet to "please help" will have no effect. Only you and your hosting provider have permissions and sufficient access to diagnose and fix things.
Verify that you could reach the database server, using the host name given by your provider:
ping dbserver.hoster.example.net
Check this from a SSH console directly on your webserver. Testing from your local development client to your shared hosting server is rarely meaningful.
Often you just want the server name to be
"localhost"
, which normally utilizes a local named socket when available. Othertimes you can try"127.0.0.1"
as fallback.Should your MySQL/MariaDB server listen on a different port, then use
"servername:3306"
.If that fails, then there's a perhaps a firewall issue. (Off-topic, not a programming question. No remote guess-helping possible.)
When using constants like e.g.
DB_USER
orDB_PASSWORD
, check that they're actually defined.If you get a
"Warning: Access defined for 'DB_USER'@'host'"
and a"Notice: use of undefined constant 'DB_PASS'"
, then that's your problem.Verify that your e.g.
xy/db-config.php
was actually included and whatelse.Check for correctly set
GRANT
permissions.It's not sufficient to have a
username
+password
pair.Each MySQL/MariaDB account can have an attached set of permissions.
Those can restrict which databases you are allowed to connect to, from which client/server the connection may originate from, and which queries are permitted.
The "Access denied" warning thus may as well show up for
mysql_query
calls, if you don't have permissions toSELECT
from a specific table, orINSERT
/UPDATE
, and more commonlyDELETE
anything.You can adapt account permissions when connected per command line client using the admin account with a query like:
GRANT ALL ON yourdb.* TO 'username'@'localhost';
If the warning shows up first with
Warning: mysql_query(): Access denied for user ''@'localhost'
then you may have a php.ini-preconfigured account/password pair.Check that
mysql.default_user=
andmysql.default_password=
have meaningful values.Oftentimes this is a provider-configuration. So contact their support for mismatches.
Find the documentation of your shared hosting provider:
e.g. HostGator, GoDaddy, 1and1, DigitalOcean, BlueHost, DreamHost, MediaTemple, ixWebhosting, lunarhosting, or just google yours´.
Else consult your webhosting provider through their support channels.
Note that you may also have depleted the available connection pool. You'll get access denied warnings for too many concurrent connections. (You have to investigate the setup. That's an off-topic server configuration issue, not a programming question.)
Your libmysql client version may not be compatible with the database server. Normally MySQL and MariaDB servers can be reached with PHPs compiled in driver. If you have a custom setup, or an outdated PHP version, and a much newer database server, or significantly outdated one - then the version mismatch may prevent connections. (No, you have to investigate yourself. Nobody can guess your setup).
More references:
警告:被零除
警告消息“被零除”是新 PHP 开发人员最常问的问题之一。这个错误不会引起异常,因此,一些开发人员偶尔会通过在表达式前添加错误抑制运算符@来抑制警告。例如:
但是,与任何警告一样,最好的方法是追踪警告的原因并解决它。警告的原因可能来自您尝试除以 0、等于 0 的变量或尚未分配的变量(因为 NULL == 0)的任何实例,因为结果将是“未定义”。
要纠正此警告,您应该重写表达式以检查该值是否不为 0,如果是,请执行其他操作。如果该值为零,则不应除以该值,或者应将该值更改为 1,然后除以,这样除法的结果相当于仅除以附加变量。
相关问题:
Warning: Division by zero
The warning message 'Division by zero' is one of the most commonly asked questions among new PHP developers. This error will not cause an exception, therefore, some developers will occasionally suppress the warning by adding the error suppression operator @ before the expression. For example:
But, like with any warning, the best approach would be to track down the cause of the warning and resolve it. The cause of the warning is going to come from any instance where you attempt to divide by 0, a variable equal to 0, or a variable which has not been assigned (because NULL == 0) because the result will be 'undefined'.
To correct this warning, you should rewrite your expression to check that the value is not 0, if it is, do something else. If the value is zero you either should not divide, or you should change the value to 1 and then divide so the division results in the equivalent of having divided only by the additional variable.
Related Questions:
严格标准:非静态方法 [::] 不应静态调用
当您尝试调用类上的非静态方法(因为它是静态的)时会发生这种情况,并且您的
error_reporting()
设置中还有E_STRICT
标志。示例:
HTML::br()
或$html::br()
实际上,您可以通过不将
E_STRICT
添加到error_reporting()
,例如,对于 PHP 5.4.0 及更高版本,
E_STRICT
包含在E_ALL
[参考]。但这并不可取。解决方案是将您想要的静态函数定义为实际的静态函数:或按常规调用该函数:
相关问题:
Strict Standards: Non-static method [<class>::<method>] should not be called statically
Occurs when you try to call a non-static method on a class as it was static, and you also have the
E_STRICT
flag in yourerror_reporting()
settings.Example :
HTML::br()
or$html::br()
You can actually avoid this error by not adding
E_STRICT
toerror_reporting()
, egsince as for PHP 5.4.0 and above,
E_STRICT
is included inE_ALL
[ref]. But that is not adviceable. The solution is to define your intended static function as actualstatic
:or call the function conventionally :
Related questions :