How and by what means to find errors in PHP code?
When developing, sometimes the code does not work as intended or does not work at all. I sit and wonder: what is wrong and where?
After looking at the code for an hour , I go to prof. resources, such as Stack Overflow and post a question "Where is the error here? " or "Why it doesn't work?"
As a result, often the problem is small, a stupid typo, an error in the syntax, and so on. You will not become a professional if you run through resources for every nonsense. And I want them to to be.
Question: what are the ways to find errors in PHP code? What tools, methods, plugins, paths, etc.?
6 answers
Yesterday everything worked, but today it does not work / The code does not work as intended
Or
Debugging
What is the debugging process? What is it?
The debugging process is that we stop the script execution anywhere, look at what is in the variables, in the functions, analyze and go to other places; look for those places where the behavior deviates from the correct one.
An example with PhpStorm, but you can debug the code in any other IDE.
Preparation
First, you need to have a debugging library in PHP called xdebug. If it is not yet available, then you need to download it to xdebug.org.
Usually all libraries are located in the ext
folder inside the PHP folder. That's where you should put dll
.
Then in php.ini
we write settings:
[Xdebug]
zend_extension="C:/server/php/ext/php_xdebug.dll" // <!-- тут свой путь до dll!!!
xdebug.default_enable = 1
xdebug.remote_enable = 1
xdebug.remote_handler = "dbgp"
xdebug.remote_host = "localhost"
xdebug.remote_port = 9000
xdebug.auto_trace = 0
Restart the server, just in case.
Now, if you write phpinfo();
in the file .php
, you can see the following picture at the very bottom:
Opening PhpStorm
- click
create project from existing files
- select
Web server is installed locally, source files are located under its document root
- select the folder with the files, and click the "Project Root" button at the top to mark the folder as the root of the project
- click "Next"
-
Click Add new local server
- enter any server name and
Web Server root URL
. In the example under consideration, this ishttp://localhost/testy2
- click "Next" and then "Finish"
Launch
To start, in the left part of the panel with the code on any line, you can click LMB, thereby setting a breakpoint (breakpoint). This is where the debugger will automatically stop execution PHP, as soon as it gets to it. The number of breakpoints is unlimited. You can put it everywhere and a lot.
If you click PCM and select Debug
in the pop-up menu (or in the top menu - Run
→ Debug
), then when you first run PhpStorm will ask you to configure the interpreter. I.e. you need to select the PHP version from the folder where it is located, so that storm knows which version it will debug.
Now you can click Debug
!!!
In this case, since the function is called immediately on the same page, when you click the Debug
button, the debugger will immediately call the function, the execution will "freeze" on the first breakpoint. Otherwise, to activate it, you need to perform an action that will execute the desired code section (click on the button, send a POST request from the data form, and others actions).
Numbers indicate:
- Call stack, all nested calls that led to the current code location.
- Variables. At the moment, the lines below number 3 have not yet been executed, so only
$data
- Shows the current values of any variables and expressions. At any time, you can click on
+
, enter the name of any variable, and view its value in real time. For example:$data
or$nums[0]
, or you can also$nums[i]
anditem['test']['data'][$name[5]][$info[$key[1]]]
, etc. At the moment, the lines below number 3 have not yet been executed, so$sum
and$output
are marked in red with the inscription "cannot evaluate expression".
Process
The process itself uses controls (see image above, highlighted in green rectangle) and a bit of additionally (see image above, highlighted in orange rectangle).
Show Execution Point (Alt+F10) - transfers the current line of the debugged script to the file. For example, if there are a lot of files, you decided to look at what is in other tabs, and then forgot where you have debugging :)
Step Over (F8) - takes one step without going inside the function. That is, if there is a function on the current line, and not just a variable with a value, then when this button is clicked, the debugger will not go inside her.
Step Into (F7) - takes a step. But unlike the previous one, if there is a nested call (for example, a function), it goes inside it.
Step Out (Shift+F8) - executes commands until the current function completes. This is useful if you accidentally entered a nested call and need to quickly exit it without completing debugging.
Rerun (Ctrl+F5) - restarts debugging.
Resume Program(F9) - continues execution of the script from the current moment. If there are no other breakpoints, debugging ends and the script continues. Otherwise, the operation is interrupted at the next breakpoint.
Stop (Ctrl+F2) - completes debugging.
View Breakpoints (Ctrl+Shift+F8) - view all installed breakpoints.
Mute Breakpoints-disables breakpoints.
...
So, in the current code, you can see the value of the input parameters:
-
$data = "23 24 11 18"
- a string with data separated by a space -
$nums = (4) ["23", "24", "11", "18"]
- the array that was obtained from the input variable.
If we press F8 2 times, we will be on line 7; in the tabs Watches
and Variables
and in the code page itself, we will see that the variable $sum
was initialized and its value is 0.
If we now press F8, we get inside the loop foreach
and, pressing now F8, until the loop ends, it will be possible to observe at each iteration how the values of $num
and $sum
are constantly changing. Thus, we can trace step by step the entire process of changing any variables and values at any stage that interests us.
Further pressing F8 will move the code line to lines 11, 12, and finally 15.
Additional
If you click on View Breakpoints
in the left panel, you can not only view all breakpoints, but in the window that appears, you can even more fine-tune the condition under which you need to stop at this mark.
In the function above, for example, you only need to stop when $sum
exceeds the value of 20.
This is useful if the stop is needed only at a certain value, and not always (especially in the case of loops).
PHP error messages
Both on the local and on the combat server it is necessary to read and process all errors. The difference is that you need to configure the display of errors on the local server. On combat-errors DO NOT display on the screen, BUT need to be written to the log, where you can read and analyze them.
To display all errors on the screen, you need to write at the very beginning of the script:
ini_set('display_errors',1);
error_reporting(E_ALL ^E_NOTICE);
In this case, these lines will be report all critical errors to the screen. If no errors are displayed, you should write:
error_reporting(E_ALL);
To display syntax errors, correct them in php.ini
(or add the line php_flag display_errors 1
to .htaccess
).
Result:
You can immediately see:
- level (warning, notification, error)
- full text of the error
- script name with error
- line number in the same script
You can go to the script on the specified line and analyze it.
Don't know English?
Open any online translator and copy the error text there, replacing the uppercase letters with lowercase ones:
Fatal error: uncaught error: call to undefined function getSum() in W:\test\index.php on line 6
Фатальная ошибка: неперехваченная ошибка: вызов неопределенной функции getSum() в W:\test\index.php в строке 6
Straight in Russian says: undefined function getSum
. This means that there is a call, but there is no ad, and you need to search in the specified direction.
Grandfather's way
Despite the method described below, you should immediately note that there are wonderful tools that will help you quickly detect and fix errors. One of them is Integrated Development Environment (IDE). You can read more about it in the question:
What are the ways to prevent errors, find them, and fix them?
About the method.
This method was used in the old days the times when they just wrote the code, in fact, in notebooks. Now it also works, although with smart development environments and debuggers, it is not the fastest and most efficient way.
Used banally echo
/print_r
/var_dump
. Sometimes with the addition of die()
, so that the code does not go further.
Algorithm of actions:
- Write
echo(ИМЯ_ПЕРЕМЕННОЙ)
orprint_r(ИМЯ_ПЕРЕМЕННОЙ)
to one of the script points. Let's see what the values are equal to. - If the values are the same as expected, the error is lower. Delete it output of variables and write it below.
- If the values are not what you expected, then the problem is higher. We remove the output of variables and write it above.
- Repeat steps 2 and (or) 3 until we reach the lines where the output of variables on the line above gives the correct result, and below - no.
Example:
$test1 = 3;
$test2 == 2;
$result = $test1 + $test2;
echo $result;
We expect to see 5, but we see 3. We write
echo '$test1: '.$test1.', $test2: '.$test2.', $result: '.$result;
And see
$test1: 3, $test2: , $result: 3
$test1
- the correct value is
$test2
and $result
- invalid values. Especially in $test2
So, at least, the problem is in $test2
. If you look closely, you can see that you accidentally put the equal sign instead of the assignment sign.
$test2 == 2;
^------- лишний знак
Fix it.
(Note) If the code is not executed in principle, it does not output anything, for example, then it is enough to write echo 'тестовая_фраза';
in the code and move it higher and higher until it appears. As soon as the label appeared, it means that it was in the line below.
Total: all, what you need is to look at the required variable at each step of the algorithm and understand at what point the error occurs.
All the answers from above are good and correct, but I want to add a couple more points. Implementation of the static analyzer PHPStan, Phan or Psalm in the project, you can also use all 3 at once :) For more information, there is an article on habr poke
You need to start with the largest variable and go down var_dump();
, and find the wrong value of some variable.
The php.ini file may block error output. Decision. Check the parameters error_reporting = E_ALL, display_errors = On, display_startup_errors = On in php. ini. If you don't know where the php.ini file is? Use the php function phpinfo (). The table opens. There is a path to php.ini. Find the "Loaded Configuration File" and "Configuration File (php.ini) Path" options. Here I found about it. profi.spage.me/php/show-php-file-errors-enable-php-error-display