Reputation: 198203
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.
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.
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.
Also, see:
Upvotes: 1290
Views: 284223
Reputation: 27342
This warning is shown when the type of the first variable in the foreach expression isn't an array
or object
.
Example 1
# Warning: foreach() argument must be of type array|object, null given
$x = null;
foreach($x as $v) {
}
Example 2
# Warning: foreach() argument must be of type array|object, string given
$x = 'abc';
foreach($x as $v) {
}
These are the two most common examples.
array
or object
.Upvotes: 1
Reputation: 160923
First and foremost:
Please, don't use
mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
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
by
$res = mysql_query($sql);
if (!$res) {
trigger_error(mysql_error(),E_USER_ERROR);
}
// after checking, do the fetch
Related 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.
Upvotes: 95
Reputation: 522529
(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:
$arr = array('foo', 'bar');
echo $arr; // Notice: Array to string conversion
$str = 'Something, ' . $arr; // Notice: Array to string conversion
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:
echo $arr[0]; // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar
Or loop the array:
foreach($arr as $key => $value) {
echo "array $key = $value";
// displays first: array 0 = foo
// displays next: array 1 = bar
}
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.
Upvotes: 22
Reputation: 97948
Every PHP page request or script invocation measures how long PHP code has been executing. If a configured limit is reached, the script is aborted with this message.
Note that the time generally doesn't include things that happen "outside of" PHP, such as time waiting for results from the database, or external programs executed with shell_exec
, etc. The exception is when PHP is running on Windows, where the time measured is "clock time" and does include these external wait times.
Common causes
while
, do...while
or for
loop may never complete, meaning PHP is running continuously forever. Even a foreach
loop can be infinite, for instance if looping over an Iterator object or generator function.Changing the limit
If you know that you have a slow process, you can configure the time limit:
set_time_limit(10);
means "allow 10 more seconds, regardless of how long the script has already taken".Both mechanisms should be given a number of seconds, or the special value 0
which means "no limit". Setting "no limit" is most useful for command-line scripts which you genuinely intend to run forever in the background; for web pages, it is better to set some finite value, even if it is very large, to prevent bugs in your code causing the entire system to become unresponsive.
Upvotes: 4
Reputation: 88707
or, in PHP 7.2 or later:
or, in PHP 8.0 or later:
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:
// Wrong
echo $array[key];
// Right
echo $array['key'];
Another common cause is a missing $
(dollar) sign in front of a variable name:
// Wrong
echo varName;
// Right
echo $varName;
Or perhaps you have misspelled some other constant or keyword:
// Wrong
$foo = fasle;
// Right
$foo = false;
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:
Upvotes: 48
Reputation: 317147
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)
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];
Both spinach
and 1
do not exist in the array, causing an E_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
or isset
:
$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
echo $data['spinach'];
}
else {
echo 'No key spinach in the array';
}
If you have code like:
<?php echo $_POST['message']; ?>
<form method="post" action="">
<input type="text" name="message">
...
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:
if ($_POST) .. // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') .. // page was requested with POST
Related Questions:
Upvotes: 113
Reputation: 4834
Happens when you try to use a variable that wasn't previously defined.
A typical example would be
foreach ($items as $item) {
// do something with item
$counter++;
}
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
$counter = 0;
foreach ($items as $item) {
// do something with item
$counter++;
}
Similarly, a variable is not accessible outside its scope, for example when using anonymous functions.
$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) {
// Prefix is undefined
return "${prefix} ${food}";
}, $food);
This should instead be passed using use
$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) use ($prefix) {
return "${prefix} ${food}";
}, $food);
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.
$obj = new stdclass;
$obj->property = 2342;
foreach ($items as $item) {
// do something with item
$obj->counter++;
}
Related Questions:
Upvotes: 48
Reputation: 270727
In PHP 8.0 and above, the message is instead:
syntax error, unexpected string content "", expecting "-" or identifier or variable or number
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 {}
.
This will result in Unexpected T_ENCAPSED_AND_WHITESPACE
:
echo "This is a double-quoted string with a quoted array key in $array['key']";
//---------------------------------------------------------------------^^^^^
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:
echo "This is a double-quoted string with an un-quoted array key in $array[key]";
//------------------------------------------------------------------------^^^^^
The entire complex array variable and key(s) can be enclosed in {}
, in which case they should be quoted to avoid an E_NOTICE
. The PHP documentation recommends this syntax for complex variables.
echo "This is a double-quoted string with a quoted array key in {$array['key']}";
//--------------------------------------------------------------^^^^^^^^^^^^^^^
// Or a complex array property of an object:
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";
Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolating it:
echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside.";
//----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
For reference, see the section on Variable Parsing in the PHP Strings manual page
Upvotes: 59
Reputation: 42743
This error explains itself. Your code attempted to call some_function()
and passed the wrong type of data as one of the arguments. For example:
<?php declare(strict_types=1);
function multiply(int $x, int $y) { return $x * $y; }
echo multiply("3", 4);
Because the called functions first argument is with the int
scalar type, and the call is in a file which has strict types enabled (stict_types=1
), it type-errors when passing a string
to it:
Fatal error: Uncaught TypeError: multiply(): Argument #1 ($x) must be of type integer, string given in...
This example on 3v4l.org.
Upvotes: 2
Reputation: 145512
The HTTP status code 500 and the typical Apache or browser warning is a very broad message. It's not the actual error. To figure out if it's a webserver misconfiguration (.htaccess
) or a PHP fatal error, you have to look at the error.log
.
You can typically find the webservers log under:
/var/log/apache2
on Linux servers, often used for local and virtual hosts./var/www/_user12345_/logs
or similar on shared hosting plans.logs/
directory alongside each htdocs/
folder.C:\xampp\apache\logs\error.log
for WAMP/XAMPP distributions of Apache+PHP.httpd.conf
and its ErrorLog
directive./var/log/nginx/nginx_error.log
for NGINX.C:\inetpub\logs\LogFiles
for IIS.journalctl -r -u apache2.service
could also hold parts of the log on Linux setups.It's a text file. Search for the entry most closely matching the error time, and use the significant part of the error message (from "PHP Error: …" until "in line…") for further googling.
[Mon 22:10] [:error] [pid 12345] [client 127.0.0.1] FastCGI: server "/fcgi/p73" stderr: PHP message:
PHP Error: Unfiltered input
variable $_JSON['pokestop_lng'] in filyfile.php on line 845
For FPM setups you will often just see fatal PHP errors here. Whereas older mod_php (shared hosting) configurations often mix in warnings and notices (which usually are also worth inspecting).
If not configured to use the system or Apache logging mechanism, you may also want to look at PHP's error.log. Generally it's simpler to leave the defaults and just enable error_display
+ error_reporting
to reveal the concrete error. The HTTP 500 catch-all page after all is just a variation of PHP's white screen of death.
See also:
Upvotes: 8
Reputation: 36003
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:
$value = @(2 / 0);
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.
if ( $var1 == 0 ) { // check if var1 equals zero
$var1 = 1; // var1 equaled zero so change var1 to equal one instead
$var3 = ($var2 / $var1); // divide var1/var2 ie. 1/1
} else {
$var3 = ($var2 / $var1); // if var1 does not equal zero, divide
}
Related Questions:
Upvotes: 14
Reputation: 42743
This error means that you have attempted to use a class constant that does not exist. Unlike other "undefined" notices and warnings, this is a fatal error and will stop the script immediately.
The first thing to be checked should be typographic errors. Confirm the constant is defined in the class, and that it is called using the appropriate namespace. Confirm also that all appropriate files have been included to resolve the constant.
Upvotes: 2
Reputation: 79014
String offsets and array elements could be accessed by curly braces {}
prior to PHP 7.4.0:
$string = 'abc';
echo $string{0}; // a
$array = [1, 2, 3];
echo $array{0}; // 1
This has been deprecated since PHP 7.4.0 and generates a warning:
Deprecated: Array and string offset access syntax with curly braces is deprecated
You must use square brackets []
to access string offsets and array elements:
$string = 'abc';
echo $string[0]; // a
$array = [1, 2, 3];
echo $array[0]; // 1
The RFC for this change links to a PHP script which attempts to fix this mechanically.
Upvotes: 21
Reputation: 42743
Self-explanatory; the parameter passed to the count()
function has to be something that is countable, usually an array.
The likely problem is that a scalar value such as a string or integer was passed, or an object that doesn't implement the Countable
interface. Using var_dump()
on the variable in question can show whether or not this is the case.
Upvotes: 5
Reputation: 73035
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:
Upvotes: 47
Reputation: 33400
It means that you are not executing your anonymous function (or a closure).
An error will be thrown for this example using arrow functions:
echo $fn = fn($x = 42) => $x;
Or for any anonymous function
echo function($x = 42) { return $x; };
To resolve this error you need to execute the closure.
echo $fn = (fn($x = 42) => $x)(30); // take notice of the 2 sets of brackets
echo (function($x = 42) { return $x; })(30);
This kind of syntax is called IIFE and it was added in PHP 7.
Upvotes: 9
Reputation: 198203
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
$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object
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:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object
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:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$div = $result->item(0);
$divText = "-/-";
if (is_object($div)) {
$divText = $div->nodeValue;
}
echo $divText;
Related errors:
Upvotes: 36
Reputation: 57322
Possible scenario
I can't seem to find where my code has gone wrong. Here is my full error:
Parse error: syntax error, unexpected T_VARIABLE on line x
What I am trying
$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';
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
. That T_VARIABLE
thing is called a token
. 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 your php.ini
. Parse errors should not exist in production scripts.
I always recommended to add the following statement, while coding:
error_reporting(E_ALL);
Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:
Related Questions:
Upvotes: 37
Reputation: 16495
*
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
$string = 'ABCD';
for ($i=0, $len = strlen($string); $i <= $len; $i++){
echo "$string[$i] \n";
}
The above example will generate (online demo):
A
B
C
D
Notice: Uninitialized string offset: 4 in XXX on line X
And, as soon as the script finishes echoing D
you'll get the error, because inside the for()
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 from 0
and echoes D
by the time it reaches to 4
, it will throw an offset error.
Similar Errors:
Upvotes: 36
Reputation: 9427
It happens when you call a file usually by include
, require
or fopen
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__
or dirname(__FILE__)
:
include __DIR__ . '/inc/globals.inc.php';
or:
require dirname(__FILE__) . '/inc/globals.inc.php';
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:
Upvotes: 48
Reputation: 160923
This usually happens when using a function directly with empty
.
Example:
if (empty(is_null(null))) {
echo 'empty';
}
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 to empty()
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 (like is_null(null)
in the example) will always be deemed to exist, so here empty
is only checking if it is equal to false. You could replace empty()
here with !
, e.g. if (!is_null(null))
, or explicitly compare to false, e.g. if (is_null(null) == false)
.
Related Questions:
Upvotes: 75
Reputation: 317147
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
$someCondition = false;
if ($someCondition === true) {
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn()
will never be declared because $someCondition
is not true.
Example 2 - Function in Function Declaration
function createFn()
{
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn
will only be declared once createFn()
gets called. Note that subsequent calls to createFn()
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:
Upvotes: 83
Reputation: 160923
$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:
class Foo {
protected $var;
public function __construct($var) {
$this->var = $var;
}
public static function bar () {
// ^^^^^^
echo $this->var;
// ^^^^^
}
}
Foo::bar();
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. Use self::$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:
Upvotes: 87
Reputation: 317147
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:
<html>
<?php session_start(); ?>
<head><title>My Page</title>
</html>
...
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 the session_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:
Upvotes: 308
Reputation: 42743
If the wrong type of parameter is passed to a function – and PHP cannot convert it automatically – a warning is thrown. This warning identifies which parameter is the problem, and what data type is expected. The solution: change the indicated parameter to the correct data type.
For example this code:
echo substr(["foo"], 23);
Results in this output:
PHP Warning: substr() expects parameter 1 to be string, array given
Upvotes: 6
Reputation: 198203
Happens with code similar to xyz->method()
where xyz
is not an object and therefore that method
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
// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);
In the example above, the query cannot be prepared and prepare()
will assign false
to $statement
. Trying to call the execute()
method will then result in the Fatal Error because false
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
if ($someCondition) {
$myObj = new MyObj();
}
// ...
$myObj->someMethod();
By attempting to execute the method outside the conditional block, your object may not be defined.
Related Questions:
Upvotes: 209
Reputation: 1285
Occurs when a class attempts to use
multiple Traits, where two or more of those Traits have defined a property by the same name, and with the property having differing initial values.
Example:
<?php
trait TraitA
{
public $x = 'a';
}
trait TraitB
{
public $x = 'b';
}
class ClassC
{
use TraitA, TraitB;
}
Problematic: While it's possible to resolve conflicts between competing methods, there is currently no syntax that would resolve a conflict between two competing properties. The only solution at this time is to refactor; i.e., avoid a conflict between property names that produces a fatal error.
Related Questions:
Upvotes: 7
Reputation: 11413
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"):
$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);
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:
$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';
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()
Upvotes: 68
Reputation: 145512
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 the test
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
or DB_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 to SELECT
from a specific table, or INSERT
/UPDATE
, and more commonly DELETE
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=
and mysql.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:
Btw, you probably don't want to use
mysql_*
functions anymore. Newcomers often migrate to mysqli, which however is just as tedious. Instead read up on PDO and prepared statements.
$db = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
Upvotes: 20
Reputation: 28777
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:
ini_set('display_errors', 1); error_reporting(~0);
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 the display_startup_errors
directive to true
. Do this either in the php.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:
Upvotes: 131