Как проверить код php на ошибки

How to use the free code checker

Code

Copy and paste your PHP code into the editor.

Language

Select your language from the dropdown.

Check

Click the Check code button.

Improve

Use the results to improve your PHP code.

Get your PHP code bug-free and secure right from the IDE

This free code checker can find critical vulnerabilities and security issues in PHP code bases with a click. To take your application security to the next level, we recommend using Snyk Code for free right from your IDE.

Improved PHP code security powered by Snyk Code

This free web based PHP code checker is powered by Snyk Code. Sign up now to get access to all the features including vulnerability alerts, real time scan results, and actionable fix advice within your IDE.

Human-in-the-Loop PHP Code Checker

Snyk Code is an expert-curated, AI-powered PHP code checker that analyzes your code for security issues, providing actionable advice directly from your IDE to help you fix vulnerabilities quickly.

Real-time

Scan and fix source code in minutes.

Actionable

Fix vulns with dev friendly remediation.

Integrated in IDE

Find vulns early to save time & money.

Ecosystems

Integrates into existing workflow.

More than syntax errors

Comprehensive semantic analysis.

AI powered by people

Modern ML directed by security experts.

In-workflow testing

Automatically scan every PR and repo.

CI/CD security gate

Integrate scans into the build process.

Frequently asked questions

Что этот инструмент может

Этот инструмент проверяет синтаксис введенного кода PHP и выделяет любые синтаксические ошибки, если они есть.
Описание, которое вызывает синтаксическую ошибку, отличается в зависимости от версии PHP, поэтому выберите произвольную версию и используйте ее.

Полезно для

  • разработчики, чтобы найти причину ошибок в программах PHP

PHP — популярнейший скриптовый язык программирования общего назначения, который активно применяется при разработке web-приложений. Он поддерживается множеством хостинг-провайдеров и является одним из лидирующих языков, используемых в целях создания динамических web-сайтов. Иногда возникает необходимость выполнить проверку синтаксиса кода PHP. В статье будет рассмотрено, как это сделать.

Для проверки кода сегодня используют специальные онлайн-сервисы — валидаторы (validators). Они работают предельно просто: пользователю достаточно скопировать свой код в специальную форму и нажать кнопку «Проверить код» либо клавишу «Check». Также перед подтверждением проверки надо будет отметить галочкой нужную версию. Отдельные сервисы допускают возможность перетаскивания/загрузки файла с кодом.

Один из популярных сервисов для валидации — https://phpcodechecker.com/. Он даёт возможность легко и быстро найти синтаксическую ошибку в коде. Найденные проблемы будут выделены, плюс произойдёт автоматический переход на строку с ошибкой (вы сэкономите время поиска). Выделенная ошибка будет сопровождаться соответствующими комментариями.

Как узнать версию PHP?

Существуют ситуации, когда нужно выяснить, какая конкретно версия языка функционирует на вашем сервере. Если речь идёт о конкретном веб-сайте, используйте функцию phpinfo(). Необходимо поместить в корневой каталог файл phpinfo.php со следующим содержимым:


Далее достаточно будет открыть веб-браузер и перейти по адресу вашдомен/phpinfo.php. В результате версия PHP-сервера отобразится на экране.

1-1801-88acea.png

После того, как информация о версии будет получена, следует удалить файл из корневого каталога либо ограничить к нему доступ, т. к. предоставление конфигурации в общий доступ может нести угрозу информационной безопасности.

На этом всё. Как видите, проверить PHP код с точки зрения синтаксических ошибок можно легко и быстро, для чего существуют специальные инструменты — валидаторы. Не составит труда и узнать версию PHP в случае необходимости.

Узнайте, правилен ли ваш код! Проверяйте его на специальных онлайн-сервисах!

PHP_970x90-20219-10b307.jpg

Well, I have run into a bit of a pickle here. I am needing to check some PHP for syntax errors. I noticed this bit that needs to run from the commandline:

php -l somefile.php

However, is there a way to run this from within a PHP file itself? I’ve been looking and have think that I can use parse_str function somehow to accomplish this by entering it into a $_GET, but can’t quite understand how this works.

Someone else told me to use token_get_all() php function to determine this.

But I can’t figure out how to do this with any approach? Can anyone here give me some sample code to get started perhaps?? I don’t think using eval() is the way to go, although I had an eval($code) working, but don’t think I should run the script if there are PHP syntax errors.

Any help on this is greatly appreciated, as always!

asked Aug 14, 2012 at 21:01

Solomon Closson's user avatar

Solomon ClossonSolomon Closson

6,09114 gold badges72 silver badges114 bronze badges

3

You could simply do shell_exec() like this:

$output = shell_exec('php -l /path/to/filename.php');

This gives you the output of the command line operation in the string $output.

answered Aug 14, 2012 at 21:10

Mike Brant's user avatar

Mike BrantMike Brant

70.4k10 gold badges98 silver badges103 bronze badges

2

It is safer to check the return status of php -l

$fileName = '/path/to/file.php';
exec("php -l {$fileName}", $output, $return);

if ($return === 0) {
    // Correct syntax
} else {
    // Syntax errors
}

See this fiddle to see it in action

answered May 29, 2017 at 7:25

Mandy Schoep's user avatar

I use token_get_all for this. I have some PHP code in the db. Before saving, I do

function is_valid_php_code_or_throw( $code ) {
        $old = ini_set('display_errors', 1);
        try {
                token_get_all("<?phpn$code", TOKEN_PARSE);
        }
        catch ( Throwable $ex ) {
                $error = $ex->getMessage();
                $line = $ex->getLine() - 1;
                throw new InvalidInputException("PARSE ERROR on line $line:nn$error");
        }
        finally {
                ini_set('display_errors', $old);
        }
}

Works like a charm. Syntax only. No missing variables, type incompayibility etc.

InvalidInputException is my own. You can make it anything, or return a bool, or handle the exception yourself.

I’m not sure if display_errors is necessary. It was at some point.

answered Aug 7, 2018 at 19:16

Rudie's user avatar

RudieRudie

51.9k42 gold badges131 silver badges172 bronze badges

2

I would do it like this:

$php_file = 'The path to your file';
if(substr(`php -l $php_file`, 0, 16) == 'No syntax errors') {
    // Correct syntax
} else {
    // Error
}

answered Dec 14, 2015 at 10:12

Samuil Banti's user avatar

Samuil BantiSamuil Banti

1,6751 gold badge15 silver badges26 bronze badges

php_check_syntax should do the trick. If you’re running PHP >= 5.05, see the first comment in the comments section for the implementation.

answered Aug 14, 2012 at 21:03

wanovak's user avatar

wanovakwanovak

6,11724 silver badges32 bronze badges

3

You can use exec to check for syntax errors.

$tempFile = path/of/file
$syntaxParseError = strpos(exec('php -l '.$tempFile), 'No syntax errors detected') === false;`

Unfortunately, this will not give you the line number or tell you anything about the error. For that you will either need to install static analyzer on your server Is there a static code analyzer [like Lint] for PHP files? or write your own parser.

NB. token_get_all() will not determine anything on its own, but it useful function for making a parser.

Community's user avatar

answered Feb 10, 2017 at 2:47

Dan Bray's user avatar

Dan BrayDan Bray

7,1923 gold badges52 silver badges70 bronze badges

Why use the shell at all?

function syntax_is_valid($code)
{
    try
    {
        @eval($code);
    }
    catch (ParseError $e)
    {
        return false;
    }

    return true;    
}

Alternatively use $e->getMessage() for more info.

answered Jul 17, 2017 at 5:14

kjdion84's user avatar

kjdion84kjdion84

9,3748 gold badges60 silver badges86 bronze badges

1

Проверьте свой синтаксис PHP в Интернете. Мы предоставляем чекер для PHP5, PHP7 и PHP8.

Версия:

php-5.6.40

php-7.4.30

php-8.1.9

  • Как проверить карту памяти на телефоне на ошибки
  • Как проверить карту памяти на ошибки на андроид
  • Как проверить карту памяти на наличие ошибок
  • Как проверить камри 40 на ошибки
  • Как проверить итоговое сочинение на ошибки