Parse error syntax error unexpected что делать

Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it's just part of the learning process. However, it's often easy to interpret error messages such as: PHP ...

What are the syntax errors?

PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or identifiers. It can’t guess your coding intentions.

Function definition syntax abstract

Most important tips

There are a few basic precautions you can always take:

  • Use proper code indentation, or adopt any lofty coding style.
    Readability prevents irregularities.

  • Use an IDE or editor for PHP with syntax highlighting.
    Which also help with parentheses/bracket balancing.

    Expected: semicolon

  • Read the language reference and examples in the manual.
    Twice, to become somewhat proficient.

How to interpret parser errors

A typical syntax error message reads:

Parse error: syntax error, unexpected T_STRING, expecting ; in file.php on line 217

Which lists the possible location of a syntax mistake. See the mentioned file name and line number.

A moniker such as T_STRING explains which symbol the parser/tokenizer couldn’t process finally. This isn’t necessarily the cause of the syntax mistake, however.

It’s important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.

Solving syntax errors

There are many approaches to narrow down and fix syntax hiccups.

  • Open the mentioned source file. Look at the mentioned code line.

    • For runaway strings and misplaced operators, this is usually where you find the culprit.

    • Read the line left to right and imagine what each symbol does.

  • More regularly you need to look at preceding lines as well.

    • In particular, missing ; semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )

    • If { code blocks } are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simplify that.

  • Look at the syntax colorization!

    • Strings and variables and constants should all have different colors.

    • Operators +-*/. should be tinted distinct as well. Else they might be in the wrong context.

    • If you see string colorization extend too far or too short, then you have found an unescaped or missing closing " or ' string marker.

    • Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone if it’s not ++, --, or parentheses following an operator. Two strings/identifiers directly following each other are incorrect in most contexts.

  • Whitespace is your friend.
    Follow any coding style.

  • Break up long lines temporarily.

    • You can freely add newlines between operators or constants and strings. The parser will then concretize the line number for parsing errors. Instead of looking at the very lengthy code, you can isolate the missing or misplaced syntax symbol.

    • Split up complex if statements into distinct or nested if conditions.

    • Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.)

    • Add newlines between:

      1. The code you can easily identify as correct,
      2. The parts you’re unsure about,
      3. And the lines which the parser complains about.

      Partitioning up long code blocks really helps to locate the origin of syntax errors.

  • Comment out offending code.

    • If you can’t isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.

    • As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.

    • Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)

    • When you can’t resolve the syntax issue, try to rewrite the commented out sections from scratch.

  • As a newcomer, avoid some of the confusing syntax constructs.

    • The ternary ? : condition operator can compact code and is useful indeed. But it doesn’t aid readability in all cases. Prefer plain if statements while unversed.

    • PHP’s alternative syntax (if:/elseif:/endif;) is common for templates, but arguably less easy to follow than normal { code } blocks.

  • The most prevalent newcomer mistakes are:

    • Missing semicolons ; for terminating statements/lines.

    • Mismatched string quotes for " or ' and unescaped quotes within.

    • Forgotten operators, in particular for the string . concatenation.

    • Unbalanced ( parentheses ). Count them in the reported line. Are there an equal number of them?

  • Don’t forget that solving one syntax problem can uncover the next.

    • If you make one issue go away, but other crops up in some code below, you’re mostly on the right path.

    • If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)

  • Restore a backup of previously working code, if you can’t fix it.

    • Adopt a source code versioning system. You can always view a diff of the broken and last working version. Which might be enlightening as to what the syntax problem is.
  • Invisible stray Unicode characters: In some cases, you need to use a hexeditor or different editor/viewer on your source. Some problems cannot be found just from looking at your code.

    • Try grep --color -P -n "[x80-xFF]" file.php as the first measure to find non-ASCII symbols.

    • In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.

  • Take care of which type of linebreaks are saved in files.

    • PHP just honors n newlines, not r carriage returns.

    • Which is occasionally an issue for MacOS users (even on OS  X for misconfigured editors).

    • It often only surfaces as an issue when single-line // or # comments are used. Multiline /*...*/ comments do seldom disturb the parser when linebreaks get ignored.

  • If your syntax error does not transmit over the web:
    It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things:

    • You are looking at the wrong file!

    • Or your code contained invisible stray Unicode (see above).
      You can easily find out: Just copy your code back from the web form into your text editor.

  • Check your PHP version. Not all syntax constructs are available on every server.

    • php -v for the command line interpreter

    • <?php phpinfo(); for the one invoked through the webserver.

    Those aren’t necessarily the same. In particular when working with frameworks, you will them to match up.

  • Don’t use PHP’s reserved keywords as identifiers for functions/methods, classes or constants.

  • Trial-and-error is your last resort.

If all else fails, you can always google your error message. Syntax symbols aren’t as easy to search for (Stack Overflow itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.

Further guides:

  • PHP Debugging Basics by David Sklar
  • Fixing PHP Errors by Jason McCreary
  • PHP Errors – 10 Common Mistakes by Mario Lurig
  • Common PHP Errors and Solutions
  • How to Troubleshoot and Fix your WordPress Website
  • A Guide To PHP Error Messages For Designers — Smashing Magazine

White screen of death

If your website is just blank, then typically a syntax error is the cause.
Enable their display with:

  • error_reporting = E_ALL
  • display_errors = 1

In your php.ini generally, or via .htaccess for mod_php,
or even .user.ini with FastCGI setups.

Enabling it within the broken script is too late because PHP can’t even interpret/run the first line. A quick workaround is crafting a wrapper script, say test.php:

<?php
   error_reporting(E_ALL);
   ini_set("display_errors", 1);
   include("./broken-script.php");

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHP’s error_log and look into your webserver’s error.log when a script crashes with HTTP 500 responses.

Антон Шевчук // Web-разработчик

Не совершает ошибок только тот, кто ничего не делает, и мы тому пример – трудимся не покладая рук над созданием рабочих мест для тестировщиков :)

О да, в этой статье я поведу свой рассказа об ошибках в PHP, и том как их обуздать.

Ошибки

Разновидности в семействе ошибок

Перед тем как приручать ошибки, я бы рекомендовал изучить каждый вид и отдельно обратить внимание на самых ярких представителей.

Чтобы ни одна ошибка не ушла незамеченной потребуется включить отслеживание всех ошибок с помощью функции error_reporting(), а с помощью директивы display_errors включить их отображение:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

Фатальные ошибки

Самый грозный вид ошибок – фатальные, они могут возникнуть как при компиляции, так и при работе парсера или PHP-скрипта, выполнение скрипта при этом прерывается.

E_PARSE
Это ошибка появляется, когда вы допускаете грубую ошибку синтаксиса и интерпретатор PHP не понимает, что вы от него хотите, например если не закрыли фигурную или круглую скобочку:

<?php
/**
 Parse error: syntax error, unexpected end of file
 */
{

Или написали на непонятном языке:

<?php
/**
 Parse error: syntax error, unexpected '...' (T_STRING)
 */
Тут будет ошибка парсера

Лишние скобочки тоже встречаются, и не важно круглые либо фигурные:

<?php
/**
 Parse error: syntax error, unexpected '}'
 */
}

Отмечу один важный момент – код файла, в котором вы допустили parse error не будет выполнен, следовательно, если вы попытаетесь включить отображение ошибок в том же файле, где возникла ошибка парсера то это не сработает:

<?php
// этот код не сработает
error_reporting(E_ALL);
ini_set('display_errors', 1);

// т.к. вот тут
ошибка парсера

E_ERROR
Это ошибка появляется, когда PHP понял что вы хотите, но сделать сие не получилось ввиду ряда причин, так же прерывает выполнение скрипта, при этом код до появления ошибки сработает:

Не был найден подключаемый файл:

/**
 Fatal error: require_once(): Failed opening required 'not-exists.php' (include_path='.:/usr/share/php:/usr/share/pear')
 */
require_once 'not-exists.php';

Было брошено исключение (что это за зверь, расскажу немного погодя), но не было обработано:

/**
 Fatal error: Uncaught exception 'Exception'
 */
throw new Exception();

При попытке вызвать несуществующий метод класса:

/**
 Fatal error: Call to undefined method stdClass::notExists()
 */
$stdClass = new stdClass();
$stdClass->notExists();

Отсутствия свободной памяти (больше, чем прописано в директиве memory_limit) или ещё чего-нить подобного:

/**
 Fatal Error: Allowed Memory Size
 */
$arr = array();

while (true) {
    $arr[] = str_pad(' ', 1024);
}

Очень часто происходит при чтении либо загрузки больших файлов, так что будьте внимательны с вопросом потребляемой памяти

Рекурсивный вызов функции. В данном примере он закончился на 256-ой итерации, ибо так прописано в настройках xdebug:

/**
 Fatal error: Maximum function nesting level of '256' reached, aborting!
 */
function deep() {
    deep();
}
deep();

Не фатальные

Данный вид не прерывает выполнение скрипта, но именно их обычно находит тестировщик, и именно они доставляют больше всего хлопот у начинающих разработчиков.

E_WARNING
Частенько встречается, когда подключаешь файл с использованием include, а его не оказывается на сервере или ошиблись указывая путь к файлу:

/**
 Warning: include_once(): Failed opening 'not-exists.php' for inclusion
 */
include_once 'not-exists.php';

Бывает, если используешь неправильный тип аргументов при вызове функций:

/**
 Warning: join(): Invalid arguments passed
 */
join('string', 'string');

Их очень много, и перечислять все не имеет смысла…

E_NOTICE
Это самые распространенные ошибки, мало того, есть любители отключать вывод ошибок и клепают их целыми днями. Возникают при целом ряде тривиальных ошибок.

Когда обращаются к неопределенной переменной:

/**
 Notice: Undefined variable: a
 */
echo $a;

Когда обращаются к несуществующему элементу массива:

<?php
/**
 Notice: Undefined index: a
 */
$b = array();
$b['a'];

Когда обращаются к несуществующей константе:

/**
 Notice: Use of undefined constant UNKNOWN_CONSTANT - assumed 'UNKNOWN_CONSTANT'
 */
echo UNKNOWN_CONSTANT;

Когда не конвертируют типы данных:

/**
 Notice: Array to string conversion
 */
echo array();

Для избежания подобных ошибок – будьте внимательней, и если вам IDE подсказывает о чём-то – не игнорируйте её:

PHP E_NOTICE in PHPStorm

E_STRICT
Это ошибки, которые научат вас писать код правильно, чтобы не было стыдно, тем более IDE вам эти ошибки сразу показывают. Вот например, если вызвали не статический метод как статику, то код будет работать, но это как-то неправильно, и возможно появление серьёзных ошибок, если в дальнейшем метод класса будет изменён, и появится обращение к $this:

/**
 Strict standards: Non-static method Strict::test() should not be called statically
 */
class Strict { 
    public function test() { 
        echo 'Test'; 
    } 
}

Strict::test();

E_DEPRECATED
Так PHP будет ругаться, если вы используете устаревшие функции (т.е. те, что помечены как deprecated, и в следующем мажорном релизе их не будет):

/**
 Deprecated: Function split() is deprecated
 */

// популярная функция, всё никак не удалят из PHP
// deprecated since 5.3
split(',', 'a,b');

В моём редакторе подобные функции будут зачёркнуты:

PHP E_DEPRECATED in PHPStorm

Обрабатываемые

Этот вид, которые разводит сам разработчик кода, я их уже давно не встречал, не рекомендую их вам заводить:

  • E_USER_ERROR – критическая ошибка
  • E_USER_WARNING – не критическая ошибка
  • E_USER_NOTICE – сообщения которые не являются ошибками

Отдельно стоит отметить E_USER_DEPRECATED – этот вид всё ещё используется очень часто для того, чтобы напомнить программисту, что метод или функция устарели и пора переписать код без использования оной. Для создания этой и подобных ошибок используется функция trigger_error():

/**
 * @deprecated Deprecated since version 1.2, to be removed in 2.0
 */
function generateToken() {
    trigger_error('Function `generateToken` is deprecated, use class `Token` instead', E_USER_DEPRECATED);
    // ...
    // code ...
    // ...
}

Теперь, когда вы познакомились с большинством видов и типов ошибок, пора озвучить небольшое пояснение по работе директивы display_errors:

  • если display_errors = on, то в случае ошибки браузер получит html c текстом ошибки и кодом 200
  • если же display_errors = off, то для фатальных ошибок код ответа будет 500 и результат не будет возвращён пользователю, для остальных ошибок – код будет работать неправильно, но никому об этом не расскажет

Приручение

Для работы с ошибками в PHP существует 3 функции:

  • set_error_handler() — устанавливает обработчик для ошибок, которые не обрывают работу скрипта (т.е. для не фатальных ошибок)
  • error_get_last() — получает информацию о последней ошибке
  • register_shutdown_function() — регистрирует обработчик который будет запущен при завершении работы скрипта. Данная функция не относится непосредственно к обработчикам ошибок, но зачастую используется именно для этого

Теперь немного подробностей об обработке ошибок с использованием set_error_handler(), в качестве аргументов данная функция принимает имя функции, на которую будет возложена миссия по обработке ошибок и типы ошибок которые будут отслеживаться. Обработчиком ошибок может так же быть методом класса, или анонимной функцией, главное, чтобы он принимал следующий список аргументов:

  • $errno – первый аргумент содержит тип ошибки в виде целого числа
  • $errstr – второй аргумент содержит сообщение об ошибке
  • $errfile – необязательный третий аргумент содержит имя файла, в котором произошла ошибка
  • $errline – необязательный четвертый аргумент содержит номер строки, в которой произошла ошибка
  • $errcontext – необязательный пятый аргумент содержит массив всех переменных, существующих в области видимости, где произошла ошибка

В случае если обработчик вернул true, то ошибка будет считаться обработанной и выполнение скрипта продолжится, иначе — будет вызван стандартный обработчик, который логирует ошибку и в зависимости от её типа продолжит выполнение скрипта или завершит его. Вот пример обработчика:

<?php
    // включаем отображение всех ошибок, кроме E_NOTICE
    error_reporting(E_ALL & ~E_NOTICE);
    ini_set('display_errors', 1);
    
    // наш обработчик ошибок
    function myHandler($level, $message, $file, $line, $context) {
        // в зависимости от типа ошибки формируем заголовок сообщения
        switch ($level) {
            case E_WARNING:
                $type = 'Warning';
                break;
            case E_NOTICE:
                $type = 'Notice';
                break;
            default;
                // это не E_WARNING и не E_NOTICE
                // значит мы прекращаем обработку ошибки
                // далее обработка ложится на сам PHP
                return false;
        }
        // выводим текст ошибки
        echo "<h2>$type: $message</h2>";
        echo "<p><strong>File</strong>: $file:$line</p>";
        echo "<p><strong>Context</strong>: $". join(', $', array_keys($context))."</p>";
        // сообщаем, что мы обработали ошибку, и дальнейшая обработка не требуется
        return true;
    }
    
    // регистрируем наш обработчик, он будет срабатывать на для всех типов ошибок
    set_error_handler('myHandler', E_ALL);

У вас не получится назначить более одной функции для обработки ошибок, хотя очень бы хотелось регистрировать для каждого типа ошибок свой обработчик, но нет – пишите один обработчик, и всю логику отображения для каждого типа описывайте уже непосредственно в нём

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

function shutdown() {
    echo 'Этот текст будет всегда отображаться';
}
register_shutdown_function('shutdown');

Данная функция будет срабатывать всегда!

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

function shutdown() {
    $error = error_get_last();
    if (
        // если в коде была допущена ошибка
        is_array($error) &&
        // и это одна из фатальных ошибок
        in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])
    ) {
        // очищаем буфер вывода (о нём мы ещё поговорим в последующих статьях)
        while (ob_get_level()) {
            ob_end_clean();
        }
        // выводим описание проблемы
        echo 'Сервер находится на техническом обслуживании, зайдите позже';
    }
}
register_shutdown_function('shutdown');

Задание
Дополнить обработчик фатальных ошибок выводом исходного кода файла где была допущена ошибка, а так же добавьте подсветку синтаксиса выводимого кода.

О прожорливости

Проведём простой тест, и выясним – сколько драгоценных ресурсов кушает самая тривиальная ошибка:

/**
 * Этот код не вызывает ошибок
 */

// сохраняем параметры памяти и времени выполнения скрипта
$memory = memory_get_usage();
$time= microtime(true);

$a = '';
$arr = [];
for ($i = 0; $i < 10000; $i++) {
    $arr[$a] = $i;
}

printf('%f seconds <br/>', microtime(true) - $time);
echo number_format(memory_get_usage() - $memory, 0, '.', ' '), ' bytes<br/>';

В результате запуска данного скрипта у меня получился вот такой результат:

0.002867 seconds 
984 bytes

Теперь добавим ошибку в цикле:

/**
 * Этот код содержит ошибку
 */

// сохраняем параметры памяти и времени выполнения скрипта
$memory = memory_get_usage();
$time= microtime(true);

$a = '';
$arr = [];
for ($i = 0; $i < 10000; $i++) {
    $arr[$b] = $i; // тут ошиблись с именем переменной
}

printf('%f seconds <br/>', microtime(true) - $time);
echo number_format(memory_get_usage() - $memory, 0, '.', ' '), ' bytes<br/>';

Результат ожидаемо хуже, и на порядок (даже на два порядка!):

0.263645 seconds 
992 bytes

Вывод однозначен – ошибки в коде приводят к лишней прожорливости скриптов – так что во время разработки и тестирования приложения включайте отображение всех ошибок!

Тестирование проводил на PHP версии 5.6, в седьмой версии результат лучше – 0.0004 секунды против 0.0050 – разница только на один порядок, но в любом случае результат стоит прикладываемых усилий по исправлению ошибок

Где собака зарыта

В PHP есть спец символ «@» – оператор подавления ошибок, его используют дабы не писать обработку ошибок, а положится на корректное поведение PHP в случае чего:

<?php
    echo @UNKNOWN_CONSTANT;

При этом обработчик ошибок указанный в set_error_handler() всё равно будет вызван, а факт того, что к ошибке было применено подавление можно отследить вызвав функцию error_reporting() внутри обработчика, в этом случае она вернёт 0.

Если вы в такой способ подавляете ошибки, то это уменьшает нагрузку на процессор в сравнении с тем, если вы их просто скрываете (см. сравнительный тест выше), но в любом случае, подавление ошибок это зло

Исключения

В эру PHP4 не было исключений (exceptions), всё было намного сложнее, и разработчики боролись с ошибками как могли, это было сражение не на жизнь, а на смерть… Окунуться в эту увлекательную историю противостояния можете в статье Исключительный код. Часть 1. Стоит ли её читать сейчас? Думаю да, ведь это поможет вам понять эволюцию языка, и раскроет всю прелесть исключений

Исключения — исключительные событие в PHP, в отличии от ошибок не просто констатируют наличие проблемы, а требуют от программиста дополнительных действий по обработке каждого конкретного случая.

К примеру, скрипт должен сохранить какие-то данные в кеш файл, если что-то пошло не так (нет доступа на запись, нет места на диске), генерируется исключение соответствующего типа, а в обработчике исключений принимается решение – сохранить в другое место или сообщить пользователю о проблеме.

Исключение – это объект который наследуется от класса Exception, содержит текст ошибки, статус, а также может содержать ссылку на другое исключение которое стало первопричиной данного. Модель исключений в PHP схожа с используемыми в других языках программирования. Исключение можно инициировать (как говорят, “бросить”) при помощи оператора throw, и можно перехватить (“поймать”) оператором catch. Код генерирующий исключение, должен быть окружен блоком try, для того чтобы можно было перехватить исключение. Каждый блок try должен иметь как минимум один соответствующий ему блок catch или finally:

try {
    // код который может выбросить исключение
    if (rand(0, 1)) {
        throw new Exception('One')
    } else {
        echo 'Zero';
    }
} catch (Exception $e) {
    // код который может обработать исключение
    echo $e->getMessage();
}

В каких случаях стоит применять исключения:

  • если в рамках одного метода/функции происходит несколько операций которые могут завершиться неудачей
  • если используемый вами фреймверк или библиотека декларируют их использование

Для иллюстрации первого сценария возьмём уже озвученный пример функции для записи данных в файл – помешать нам может очень много факторов, а для того, чтобы сообщить выше стоящему коду в чем именно была проблема необходимо создать и выбросить исключение:

$directory = __DIR__ . DIRECTORY_SEPARATOR . 'logs';

// директории может не быть
if (!is_dir($directory)) {
    throw new Exception('Directory `logs` is not exists');
}

// может не быть прав на запись в директорию
if (!is_writable($directory)) {
    throw new Exception('Directory `logs` is not writable');
}

// возможно кто-то уже создал файл, и закрыл к нему доступ
if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
    throw new Exception('System can't create log file');
}

fputs($file, date('[H:i:s]') . " donen");
fclose($file);

Соответственно ловить данные исключения будем примерно так:

try {
    // код который пишет в файл
    // ...
} catch (Exception $e) {
    // выводим текст ошибки
    echo 'Не получилось: '. $e->getMessage();
}

В данном примере приведен очень простой сценарий обработки исключений, когда у нас любая исключительная ситуация обрабатывается на один манер. Но зачастую – различные исключения требуют различного подхода к обработке, и тогда следует использовать коды исключений и задать иерархию исключений в приложении:

// исключения файловой системы
class FileSystemException extends Exception {}

// исключения связанные с директориями
class DirectoryException extends FileSystemException {
    // коды исключений
    const DIRECTORY_NOT_EXISTS =  1;
    const DIRECTORY_NOT_WRITABLE = 2;
}

// исключения связанные с файлами
class FileException extends FileSystemException {}

Теперь, если использовать эти исключения то можно получить следующий код:

try {
    // код который пишет в файл
    if (!is_dir($directory)) {
        throw new DirectoryException('Directory `logs` is not exists', DirectoryException::DIRECTORY_NOT_EXISTS);
    }

    if (!is_writable($directory)) {
        throw new DirectoryException('Directory `logs` is not writable', DirectoryException::DIRECTORY_NOT_WRITABLE);
    }

    if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
        throw new FileException('System can't open log file');
    }

    fputs($file, date('[H:i:s]'') . " donen");
    fclose($file);
} catch (DirectoryException $e) {
    echo 'С директорией возникла проблема: '. $e->getMessage();
} catch (FileException $e) {
    echo 'С файлом возникла проблема: '. $e->getMessage();
} catch (FileSystemException $e) {
    echo 'Ошибка файловой системы: '. $e->getMessage();
} catch (Exception $e) {
    echo 'Ошибка сервера: '. $e->getMessage();
}

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

Так, а что будет если не поймать исключение? Вы получите “Fatal Error: Uncaught exception …”. Неприятно.
Чтобы избежать подобной ситуации следует использовать функцию set_exception_handler() и установить обработчик для исключений, которые брошены вне блока try-catch и не были обработаны. После вызова такого обработчика выполнение скрипта будет остановлено:

// в качестве обработчика событий 
// будем использовать анонимную функцию
set_exception_handler(function($exception) {
    /** @var Exception $exception */
    echo $exception->getMessage(), "<br/>n";
    echo $exception->getFile(), ':', $exception->getLine(), "<br/>n";
    echo $exception->getTraceAsString(), "<br/>n";
});

Ещё расскажу про конструкцию с использованием блока finally – этот блок будет выполнен вне зависимости от того, было выброшено исключение или нет:

try {
    // код который может выбросить исключение
} catch (Exception $e) {
    // код который может обработать исключение
    // если конечно оно появится
} finally {
    // код, который будет выполнен при любом раскладе
}

Для понимания того, что это нам даёт приведу следующий пример использования блока finally:

try {
    // где-то глубоко внутри кода
    // соединение с базой данных
    $handler = mysqli_connect('localhost', 'root', '', 'test');

    try {
        // при работе с БД возникла исключительная ситуация
        // ...
        throw new Exception('DB error');
    } catch (Exception $e) {
        // исключение поймали, обработали на своём уровне
        // и должны его пробросить вверх, для дальнейшей обработки
        throw new Exception('Catch exception', 0, $e);
    } finally {
        // но, соединение с БД необходимо закрыть
        // будем делать это в блоке finally
        mysqli_close($handler);
    }

    // этот код не будет выполнен, если произойдёт исключение в коде выше
    echo "Ok";
} catch (Exception $e) {
    // ловим исключение, и выводим текст
    echo $e->getMessage();
    echo "<br/>";
    // выводим информацию о первоначальном исключении
    echo $e->getPrevious()->getMessage();
}

Т.е. запомните – блок finally будет выполнен даже в том случае, если вы в блоке catch пробрасываете исключение выше (собственно именно так он и задумывался).

Для вводной статьи информации в самый раз, кто жаждет ещё подробностей, то вы их найдёте в статье Исключительный код ;)

Задание
Написать свой обработчик исключений, с выводом текста файла где произошла ошибка, и всё это с подсветкой синтаксиса, так же не забудьте вывести trace в читаемом виде. Для ориентира – посмотрите как это круто выглядит у whoops.

PHP7 – всё не так, как было раньше

Так, вот вы сейчас всю информацию выше усвоили и теперь я буду грузить вас нововведениями в PHP7, т.е. я буду рассказывать о том, с чем вы столкнётесь через год работы PHP разработчиком. Ранее я вам рассказывал и показывал на примерах какой костыль нужно соорудить, чтобы отлавливать критические ошибки, так вот – в PHP7 это решили исправить, но как обычно завязались на обратную совместимость кода, и получили хоть и универсальное решение, но оно далеко от идеала. А теперь по пунктам об изменениях:

  1. при возникновении фатальных ошибок типа E_ERROR или фатальных ошибок с возможностью обработки E_RECOVERABLE_ERROR PHP выбрасывает исключение
  2. эти исключения не наследуют класс Exception (помните я говорил об обратной совместимости, это всё ради неё)
  3. эти исключения наследуют класс Error
  4. оба класса Exception и Error реализуют интерфейс Throwable
  5. вы не можете реализовать интерфейс Throwable в своём коде

Интерфейс Throwable практически полностью повторяет нам Exception:

interface Throwable
{
    public function getMessage(): string;
    public function getCode(): int;
    public function getFile(): string;
    public function getLine(): int;
    public function getTrace(): array;
    public function getTraceAsString(): string;
    public function getPrevious(): Throwable;
    public function __toString(): string;
}

Сложно? Теперь на примерах, возьмём те, что были выше и слегка модернизируем:

try {
    // файл, который вызывает ошибку парсера
    include 'e_parse_include.php';
} catch (Error $e) {
    var_dump($e);
}

В результате ошибку поймаем и выведем:

object(ParseError)#1 (7) {
  ["message":protected] => string(48) "syntax error, unexpected 'будет' (T_STRING)"
  ["string":"Error":private] => string(0) ""
  ["code":protected] => int(0)
  ["file":protected] => string(49) "/www/education/error/e_parse_include.php"
  ["line":protected] => int(4)
  ["trace":"Error":private] => array(0) { }
  ["previous":"Error":private] => NULL
}

Как видите – поймали исключение ParseError, которое является наследником исключения Error, который реализует интерфейс Throwable, в доме который построил Джек. Ещё есть другие, но не буду мучать – для наглядности приведу иерархию исключений:

interface Throwable
  |- Exception implements Throwable
  |    |- ErrorException extends Exception
  |    |- ... extends Exception
  |    `- ... extends Exception
  `- Error implements Throwable
      |- TypeError extends Error
      |- ParseError extends Error
      |- ArithmeticError extends Error
      |  `- DivisionByZeroError extends ArithmeticError
      `- AssertionError extends Error 

TypeError – для ошибок, когда тип аргументов функции не совпадает с передаваемым типом:

try {
    (function(int $one, int $two) {
        return;
    })('one', 'two');
} catch (TypeError $e) {
    echo $e->getMessage();
}

ArithmeticError – могут возникнуть при математических операциях, к примеру когда результат вычисления превышает лимит выделенный для целого числа:

try {
    1 << -1;
} catch (ArithmeticError $e) {
    echo $e->getMessage();
}

DivisionByZeroError – ошибка деления на ноль:

try {
    1 / 0;
} catch (ArithmeticError $e) {
    echo $e->getMessage();
}

AssertionError – редкий зверь, появляется когда условие заданное в assert() не выполняется:

ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);

try {
    assert(1 === 0);
} catch (AssertionError $e) {
    echo $e->getMessage();
}

При настройках production-серверов, директивы zend.assertions и assert.exception отключают, и это правильно

Задание
Написать универсальный обработчик ошибок для PHP7, который будет отлавливать все возможные исключения.

При написании данного раздела были использованы материалы из статьи Throwable Exceptions and Errors in PHP 7

Отладка

Иногда для отладки кода нужно отследить что происходило с переменной или объектом на определённом этапе, для этих целей есть функция debug_backtrace() и debug_print_backtrace() которые вернут историю вызовов функций/методов в обратном порядке:

<?php
function example() {
    echo '<pre>';
    debug_print_backtrace();
    echo '</pre>';
}

class ExampleClass {
    public static function method () {
        example();
    }
}

ExampleClass::method();

В результате выполнения функции debug_print_backtrace() будет выведен список вызовов приведших нас к данной точке:

#0  example() called at [/www/education/error/backtrace.php:10]
#1  ExampleClass::method() called at [/www/education/error/backtrace.php:14]

Проверить код на наличие синтаксических ошибок можно с помощью функции php_check_syntax() или же команды php -l [путь к файлу], но я не встречал использования оных.

Assert

Отдельно хочу рассказать о таком экзотическом звере как assert() в PHP, собственно это кусочек контрактной методологии программирования, и дальше я расскажу вам как я никогда его не использовал :)

Первый случай – это когда вам надо написать TODO прямо в коде, да так, чтобы точно не забыть реализовать заданный функционал:

// включаем вывод ошибок
error_reporting(E_ALL);
ini_set('display_errors', 1);

// включаем asserts
ini_set('zend.assertions', 1);
ini_set('assert.active', 1);

assert(false, "Remove it!");

В результате выполнения данного кода получим E_WARNING:

Warning: assert(): Remove it! failed

PHP7 можно переключить в режим exception, и вместо ошибки будет всегда появляться исключение AssertionError:

// включаем asserts
ini_set('zend.assertions', 1);
ini_set('assert.active', 1);
// переключаем на исключения
ini_set('assert.exception', 1);

assert(false, "Remove it!");

В результате ожидаемо получаем не пойманный AssertionError. При необходимости, можно выбрасывать произвольное исключение:

assert(false, new Exception("Remove it!"));

Но я бы рекомендовал использовать метки @TODO, современные IDE отлично с ними работают, и вам не нужно будет прикладывать дополнительные усилия и ресурсы для работы с ними

Второй вариант использования – это создание некоего подобия TDD, но помните – это лишь подобие. Хотя, если сильно постараться, то можно получить забавный результат, который поможет в тестировании вашего кода:

// callback-функция для вывода информации в браузер
function backlog($script, $line, $code, $message) {
    echo "<h3>$message</h3>";
    highlight_string ($code);
}

// устанавливаем callback-функцию
assert_options(ASSERT_CALLBACK, 'backlog');
// отключаем вывод предупреждений
assert_options(ASSERT_WARNING,  false);

// пишем проверку и её описание
assert("sqr(4) == 16", "When I send integer, function should return square of it");

// функция, которую проверяем
function sqr($a) {
    return; // она не работает
}

Третий теоретический вариант – это непосредственно контрактное программирование – когда вы описали правила использования своей библиотеки, но хотите точно убедится, что вас поняли правильно, и в случае чего сразу указать разработчику на ошибку (я вот даже не уверен, что правильно его понимаю, но пример кода вполне рабочий):

/**
 * Настройки соединения должны передаваться в следующем виде
 *
 *     [
 *         'host' => 'localhost',
 *         'port' => 3306,
 *         'name' => 'dbname',
 *         'user' => 'root',
 *         'pass' => ''
 *     ]
 *
 * @param $settings
 */
function setupDb ($settings) {
    // проверяем настройки
    assert(isset($settings['host']), 'Db `host` is required');
    assert(isset($settings['port']) && is_int($settings['port']), 'Db `port` is required, should be integer');
    assert(isset($settings['name']), 'Db `name` is required, should be integer');

    // соединяем с БД
    // ...
}

setupDb(['host' => 'localhost']);

Никогда не используйте assert() для проверки входных параметров, ведь фактически assert() интерпретирует строковую переменную (ведёт себя как eval()), а это чревато PHP-инъекцией. И да, это правильное поведение, т.к. просто отключив assert’ы всё что передаётся внутрь будет проигнорировано, а если делать как в примере выше, то код будет выполняться, а внутрь отключенного assert’a будет передан булевый результат выполнения

Если у вас есть живой опыт использования assert() – поделитесь со мной, буду благодарен. И да, вот вам ещё занимательно чтива по этой теме – PHP Assertions, с таким же вопросом в конце :)

В заключение

Я за вас напишу выводы из данной статьи:

  • Ошибкам бой – их не должно быть в вашем коде
  • Используйте исключения – работу с ними нужно правильно организовать и будет счастье
  • Assert – узнали о них, и хорошо

P.S. Спасибо Максиму Слесаренко за помощь в написании статьи

Содержание

  1. PHP parse/syntax errors; Ошибки Unexpected XXX и как решить их
  2. 8 ответов 8
  3. Unexpected T_STRING
  4. Unexpected identifier «xxx»
  5. Строки с неверными кавычками
  6. Незакрытые строки
  7. Кавычки, не связанные с программированием
  8. Отсутствует точка с запятой
  9. Невидимые символы Unicode
  10. Заэкранированная кавычка
  11. Unexpected T_VARIABLE
  12. Unexpected ‘$varname’ (T_VARIABLE)
  13. Отсутствует точка с запятой
  14. Неверная конкатенация строк
  15. Пропущен оператор выражения
  16. В перечислениях в массивах или функциях
  17. В объявлении свойств классов
  18. Переменные сразу после идентификаторов
  19. Отсутствие скобок до/после языковых конструкций if, for, foreach
  20. Else не ожидает условий
  21. Необходимы скобки для замыканий (closure)
  22. Невидимые пробелы
  23. Общее о синтаксических ошибках
  24. ### Заметка:
  25. ### Как интерпретировать ошибки парсера
  26. Unexpected (
  27. Выражения в параметрах объявленной функции
  28. Выражения в свойствах класса
  29. isset(()), empty, key, next, current
  30. Unexpected )
  31. Висячая запятая при вызове функции/метода
  32. Незавершённые выражения
  33. Foreach as constant
  34. Unexpected <
  35. Unmatched subexpressions in an if (Несовпадающие подвыражения) в if
  36. < and >в выражениях
  37. Unexpected >
  38. Последнее выражение в блоке и потеря точки с запятой
  39. Недопустимая вложенность блоков/Forgotten < (забытая < )
  40. Unexpected < , expecting (
  41. Список параметров функции/метода
  42. Условные конструкции
  43. Unexpected T_CONSTANT_ENCAPSED_STRING
  44. Unexpected T_ENCAPSED_AND_WHITESPACE
  45. Неправильная интерполяция переменных
  46. Отсутствует конкатенация
  47. Отсутствует начальная кавычка
  48. Пропущена запятая в массиве
  49. Пропущена запятая в аргументах функции/метода
  50. Строка закрыта слишком поздно
  51. Отступ в HEREDOC
  52. Unexpected $end
  53. Unexpected end of file
  54. Отступ в HEREDOC
  55. Заэкранированная кавычка
  56. Альтернативный синтаксис
  57. Unexpected T_FUNCTION

PHP parse/syntax errors; Ошибки Unexpected XXX и как решить их

Часто программисты допускают ошибки. Могут возникать ошибки синтаксиса. Например:

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

Всегда смотрите на контекст кода. Синтаксическая ошибка часто кроется в упомянутых или в предыдущих строках кода. Сравните свой код с примерами синтаксиса из руководства.

Дополнительные ссылки для поиска ошибок:

В ответах ниже обобщены распространенные ошибки, найдите ошибку в списке ниже и перейдите к ответу с её описанием.

Unexpected $end / Unexpected end of file

Unexpected continue (T_CONTINUE)
Unexpected continue (T_BREAK)
Unexpected continue (T_RETURN)

В работе.

Unexpected character in input: ‘ ‘ (ASCII=92) state=1

Unexpected ‘public’ (T_PUBLIC)
Unexpected ‘private’ (T_PRIVATE)
Unexpected ‘protected’ (T_PROTECTED)
Unexpected ‘final’ (T_FINAL)

Unexpected ‘use’ (T_USE)

Unexpected ,
Unpexected .
Unexpected ;
Unexpected *
Unexpected :
Unexpected ‘:’, expecting ‘,’ or ‘)’
Unexpected &
Unexpected .

8 ответов 8

Unexpected T_STRING

Unexpected identifier «xxx»

Означает, что был обнаружен необработанный идентификатор. Это может быть разное: от «голых слов» до оставшихся констант или имен функций, забытых строк без кавычек или любого простого текста. Примерные проблемы:

Строки с неверными кавычками

Любая неэкранированная и случайная кавычка » или ‘ образует недопустимое выражение.

В данном примере используются двойные кавычки в двойных. Это неверно. Интерпретатор «увидит» строку » и строку «>click here» (т.к. строки заключаются в кавычки), а что такое http://example.com он не поймёт. Важно не забывать использовать обратный слэш для экранирования » двойных кавычек или ’ одинарных кавычек — в зависимости от того, что использовалось снаружи для всей строки (для ознакомления со строками). Например если снаружи двойные кавычки, то внутри проще использовать одинарные, чтобы не запутаться, либо экранировать двойную. С одинарными аналогично. Ещё проще большой текст помещать в HEREDOC или NOWDOC

Незакрытые строки

Если вы пропустите закрывающую кавычку, то синтаксическая ошибка обычно возникает позже.

Кавычки, не связанные с программированием

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

Отсутствует точка с запятой

Невидимые символы Unicode

Если вы получили жалобу парсера T_STRING на совершенно не вызывающий подозрений код, например:

Нужно взять другой текстовый редактор. Или даже hexeditor. То, что здесь выглядит как простые пробелы и символы новой строки, может содержать невидимые константы. Такое бывает в документах с кодировкой UTF-8 BOM и нужно сделать кодировку UTF-8 без BOM

Заэкранированная кавычка

Символ имеет особое значение. Часто символ применяют для экранирования в строках. Чтобы кавычка внутри строки, которая обёрнута в такие же кавычки, печаталась как есть, то её экранируют. Т.е. строка echo «Jim said »Hello»»; выведет Jim said «hello» . Если применить последовательность » , то она будет расценена как попытка экранирования кавычки. Поэтому строка ниже, выдаст ошибку

правильно будет экранировать обратные слэши тоже:

Unexpected T_VARIABLE

Unexpected ‘$varname’ (T_VARIABLE)

Означает, что есть конкретная переменная с указаннымв ошибке именем, которая не вписывается в текущую структуру выражения/инструкции.

Отсутствует точка с запятой

Как правило пропущена точка с запятой, а на следующей строке идёт переменная:

Неверная конкатенация строк

Пропущен оператор выражения

В перечислениях в массивах или функциях

В объявлении свойств классов

В свойства можно назначать только статические значения (которые однозначно определены), но не выражения.

Если необходимо присвоивать переменной выражение, то это нужно делать либо в конструкторе, либо в другом каком-либо инициализирующем методе

Переменные сразу после идентификаторов

Отсутствие скобок до/после языковых конструкций if, for, foreach

Else не ожидает условий

тут надо либо фигурные скобки, либо применять elseif (если не нарушает логики)

Необходимы скобки для замыканий (closure)

Переменные, которые передаются в замыкания всегда надо оборачивать в круглые скобки

Невидимые пробелы

Как отмечалось ранее. Могут быть невидимые символы. Проверьте на их наличие (читайте выше ошибки Unexpected T_STRING)

Общее о синтаксических ошибках

### Заметка:

Если ваш браузер отображает сообщения об ошибках, такие как «SyntaxError: illegal character», то это на самом деле связано не с PHP, а с Javascript и синтаксическими ошибками в нём

Синтаксические ошибки, возникающие в коде vendor: если синтаксическая ошибка возникла после установки или обновления пакета vendor’а — это может быть связано с несовместимостью версии PHP, поэтому проверьте версию vendor’а. и требования к настройке вашей платформы.

Используйте IDE, например PHPStorm, который всегда подскажет, что с кодом что-то не так. Обращайте внимание на подсказки:

Иногда возникают ошибки из-за лишних символов в начале файла, в частности BOM. Убедитесь, что файл сохранён в UTF-8 без BOM. (если нужен именно utf8)

Если ваш веб-сайт просто пустой с белым экраном, то, как правило, причиной является синтаксическая ошибка. Включите их отображение с помощью этой инструкции

### Как интерпретировать ошибки парсера

Типичное сообщение об ошибке синтаксиса:

Parse error: syntax error, unexpected T_STRING, expecting ‘ ; ‘ in file.php on line 217

(Ошибка синтаксического анализа: синтаксическая ошибка, неожиданный T_STRING, ожидалось ‘ ; ‘ в файле file.php в строке 217)

Тут указано возможное место синтаксической ошибки. См. упомянутые имя файла и номер строки.

Токен, такой как T_STRING , объясняет, какой символ синтаксический анализатор/токенизатор не смог окончательно обработать. Однако это не обязательно является причиной синтаксической ошибки. Поэтому важно изучить предыдущие строки кода. Часто синтаксические ошибки — это ошибки, произошедшие ранее. Номер строки ошибки — это именно то место, где синтаксический анализатор окончательно отказался от обработки всего этого, а не точная линия ошибки

Unexpected (

Открывающие круглые скобки обычно следуют за языковыми конструкциями, такими как if / foreach / for / array / list , или начинают арифметическое выражение. Они синтаксически неверны после «strings» , предыдущих скобок () , одинокого $ и в некоторых типичных контекстах объявлений. Типичные ошибки:

Выражения в параметрах объявленной функции

Параметры в объявлении функции могут быть только литеральными значениями или константными выражениями. То есть выражение time() + 90000 нельзя использовать в качестве дефолтного значения параметра функциию. Тем не менее при вызове функции можно свободно использовать выражение:

Выражения в свойствах класса

Как и ошибка выше, нельзя применять выражения для свойств класса, т.е.

Если необходимо что-то вычислить, то данные вычисления/выражения стОит помеестить в конструктор класса.

Единственное, PHP 7 позволяет написать public $property = 1 + 2 + 3; . Но это посзволительно, т.к., по сути, это выражение с константными значениями, не вычисляемое «на лету».

isset(()), empty, key, next, current

И isset() и empty() являются встроенными языковыми конструкциями языка, а не функциями, им необходим прямой доступ к переменной. Если вы непреднамеренно добавите слишком много скобок, то вы создадите доп. выражение:

Для PHP Parse error: syntax error, unexpected ‘(‘

Для PHP Fatal error: Cannot use isset() on the result of an expression

Начиная с версии 7.0 — ошибки не будет

Unexpected )

Висячая запятая при вызове функции/метода

В новых версиях языка позволены висячие запятые при нициализации массивов или списков (а также в объявлении функций/методов), но не при вызове функций/методов

Незавершённые выражения

Например если забыли в арифметическом выражении, то синтаксический анализатор сдается. Потому что он не знает как интерпретировать это:

Но если забыли закрывающую скобку вдобавок, то получите жалобу о неожиданной точке с запятой.

Foreach as constant

Если забыть добавить доллар к переменной:

PHP здесь иногда говорит, что вместо этого ожидался -> или ?-> . Поскольку class->variable мог бы удовлетворить ожидаемому выражению.

Unexpected <

Фигурные скобки < и >окружают блоки кода. И синтаксические ошибки о них обычно указывают на какую-то неправильную вложенность.

Unmatched subexpressions in an if (Несовпадающие подвыражения) в if

Чаще всего несбалансированные ( и ) являются причиной, если парсер жалуется на открывающуюся фигурную скобку < , которая появляется слишком рано. Простой пример:

Необходимо посчитать все открывающие и закрывающие скобки и сопоставить их количество. Также используйте IDE, которая помогает в этом и не пишите код без пробелов. Удобочитаемость имеет значение.

< and >в выражениях

Нельзя оборачивать выражения в скобки.

Придётся выражение вынести в переменную и подставлять уже её:

Unexpected >

Когда получаете ошибку «unexpected > «, чаще всего означает, что закрывали блок кода слишком рано.

Последнее выражение в блоке и потеря точки с запятой

Недопустимая вложенность блоков/Forgotten < (забытая < )

Блок кода был > закрыт слишком рано, или забыли открытую скобку < :

В приведенном выше фрагменте if не было открывающей фигурной скобки < . Таким образом, закрывающая >ниже стала излишней. И поэтому следующая закрывающая > , предназначенная для функции, не была связана с исходной открывающей фигурной скобкой < .

Unexpected < , expecting (

Языковые конструкции, требующие условия/объявления и блока кода, вызовут эту ошибку.

Список параметров функции/метода

Условные конструкции

То же самое для частых используемых конструкций: for / foreach , while / do , etc.

Как минимум всегда смотрите документацию, чтобы сравнить, правильно ли вы пишите ne или иную конструкцию/функцию/метод/класс и т.д.

Unexpected T_CONSTANT_ENCAPSED_STRING

Unexpected T_ENCAPSED_AND_WHITESPACE

Предупреждения T_ENCAPSED… появляются в контексте строки с двойными кавычками, в то время как строки T_CONSTANT… часто возникают в простых выражениях или операторах PHP.

Неправильная интерполяция переменных

Ключи массива должны быть в кавычках. Но в строках с двойными кавычками (или HEREDOC) это не так. Парсер жалуется на содержащуюся в одинарных кавычках строку.

Можно использовать PHP2-style для написания ключей мамссивов внутри строки

Но лучше изучить фигурный синтаксис и использовать его. Он позволяет писать ключи массива как обычно:

Отсутствует конкатенация

Отсутствует начальная кавычка

Пропущена запятая в массиве

Пропущена запятая в аргументах функции/метода

Строка закрыта слишком поздно

Отступ в HEREDOC

До версии 7.3 закрывающий идентификатор должен был находиться в самом начале новой строки. Поэтому код ниже вызовет ошибку

Unexpected $end

Unexpected end of file

Ошибка означает, что код закончился, в то время как парсер ожидает больше кода. (Сообщение немного вводит в заблуждение, если понимать его буквально. Речь идет не о переменной с именем «$end», как иногда предполагают новички. Оно относится к «концу файла»). Причина: несовпадение количества открывающих и закрывающих фигурных скобок.

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

  • Используйте правильные отступы, чтобы избежать таких проблем. И вообще, в принципе, используйте отступы и форматирование!
  • Используйте IDE с сопоставлением скобок, чтобы выяснить, где > была утеряна. Большинство IDE выделяют совпадающие фигурные скобки, квадратные скобки и круглые скобки. Что позволяет довольно легко проверить соответствие:

Отступ в HEREDOC

До версии 7.3 закрывающий идентификатор должен был находиться в самом начале новой строки. Поэтому код ниже может вызывать ошибку

Заэкранированная кавычка

Символ имеет особое значение. Часто символ применяют для экранирования в строках. Чтобы кавычка внутри строки, которая обёрнута в такие же кавычки, печаталась как есть, то её экранируют. Т.е. строка echo «Jim said »Hello»»; выведет Jim said «hello» . Если применить последовательность » , то она будет расценена как попытка экранирования кавычки. Поэтому строка ниже, выдаст ошибку

правильно будет экранировать обратные слэши тоже:

С другой стороны, PHP обычно преобразует пути в стиле Unix (например, «C:/xampp/htdocs/» ) в правильный путь для Windows.

Альтернативный синтаксис

Несколько реже вы можете увидеть эту синтаксическую ошибку при использовании альтернативного синтаксиса для блоков операторов/кодов в шаблонах. Используя if: и else: отсутствует endif; , например (т.е. закрывающий тег)

Unexpected T_FUNCTION

Может возникнуть например в версии PHP ниже 5.3.0, когда не было ещё анонимных функций. В некоторые функции, такие как array_map нужно было передать имя функции обработчика, например $range = array_map( «name_of_function_to_call», $myArray ); . Так что минимум надо проверить версию PHP и проверить что именно на вход ожадает текущая функция. И принять решение: повысить версию PHP или переписать под старый стиль: создать отдельно функцию и во вторую передать имя первой.

Источник

By definition, syntax is an arrangement of elements such as words or a set of rules that determine the form of a structure. Thus, if there’s an element in your code that is not part of the syntax like an extra comma or if it’s missing an element that is supposed to be in the code like a missing bracket, the compiler will not be able to parse or process the file, and most likely to generate an error.

A syntax error appears when the ‘syntax’ of the rules are not followed correctly. It happens when the written code is not correct. For instance, there’s a missing semicolon, a misspelled word, or an additional bracket. Mistakes as simple as these can make the system lost in translation, but on the brighter side, these errors indicate where the issue comes from and how to solve it. For those who run multiple WordPress websites, you can monitor user activities in the WordPress dashboard to locate which user activity caused the error.

Also, keep in mind that WordPress websites may experience such issues without sending any notification to the user. To make yourself aware of any errors generated in your WordPress site, make sure that your WordPress error debug is always enabled.

The structure of a syntax error usually looks like this, “Parse error: syntax error, unexpected character in path/to/php-file.php on line number“; whereas undefined constant errors are structured like this, “Notice: Use of undefined constant constant string – assumed ‘constant string‘ in path/to/php-file.php on line number“. An example of an unexpected error is this, “Parse error: unexpected character in path/to/php-file.php on line number“.

The word ‘number’ refers to the line number written in nominal form like 25 or 1345 for instance. The ‘file’ tells you where the issue persists, the ‘line number’ hints you where the error is located, while the ‘character’ or the ‘constant string’ provides a clue on what to find exactly around the stated line number. Unexpected parse errors may also list a string instead of a character.

What Causes the PHP Parse or Syntax Errors In WordPress?

  1. Home

  2. parsing — PHP parse/syntax errors; and how to solve them

107 votes

6 answers

Get the solution ↓↓↓

Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it’s just part of the learning process. However, it’s often easy to interpret error messages such as:

PHP Parse error: syntax error, unexpected ‘{-code-1}’ in index.php on line 20

The unexpected symbol isn’t always the real culprit. But the line number gives a rough idea of where to start looking.

Always look at the code context. The syntax mistake often hides in the mentioned or in previous code lines. Compare your code against syntax examples from the manual.

While not every case matches the other. Yet there are some general steps to .
This references summarized the common pitfalls:

  • Unexpected T_STRING

  • Unexpected T_VARIABLE

  • Unexpected T_CONSTANT_ENCAPSED_STRING

  • Unexpected $end

  • Unexpected T_FUNCTION…

  • Unexpected

  • Unexpected

  • Unexpected T_IF

  • Unexpected T_LNUMBER

  • Unexpected ?

  • Unexpected continue (T_CONTINUE)

  • Unexpected ‘=’

  • Unexpected T_INLINE_HTML…

  • Unexpected T_PAAMAYIM_NEKUDOTAYIM…

  • Unexpected T_OBJECT_OPERATOR…

  • Unexpected T_DOUBLE_ARROW…

  • Unexpected T_SL…

  • Unexpected T_BOOLEAN_OR…

    Unexpected T_BOOLEAN_AND…

  • Unexpected T_IS_EQUAL

  • Unexpected T_NS_SEPARATOR…

  • Unexpected character in input: ‘

  • Unexpected ‘public’ (T_PUBLIC) …

  • Unexpected T_STATIC…

  • Unexpected T_CLASS…

  • Unexpected ‘use’ (T_USE)

  • Unexpected T_DNUMBER

  • Unexpected (comma)

  • Unpexected (period)

  • Unexpected (semicolon)

  • Unexpected (asterisk)

  • Unexpected (colon)

  • Unexpected ‘:’, expecting ‘,’ or ‘)’

  • Unexpected (call-time pass-by-reference)

  • Unexpected

Closely related references:

  • What does this error mean in PHP? (runtime errors)
    • Parse error: syntax error, unexpected T_XXX
    • Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
    • Parse error: syntax error, unexpected T_VARIABLE
  • What does this symbol mean in PHP? (language tokens)
  • Those

And:

  • The PHP manual on php.net and its various language tokens
  • Or Wikipedia’s syntax introduction on PHP.
  • And lastly our of course.

While Stack Overflow is also welcoming rookie coders, it’s mostly targetted at professional programming questions.

  • Answering everyone’s coding mistakes and narrow typos is considered mostly off-topic.
  • So please take the time to follow the basic steps, before posting syntax fixing requests.
  • If you still have to, please show your own solving initiative, attempted fixes, and your thought process on what looks or might be wrong.

If your browser displays error messages such as «SyntaxError: illegal character», then it’s not actually php-related, but a javascript-syntax error.


Syntax errors raised on vendor code: Finally, consider that if the syntax error was not raised by editing your codebase, but after an external vendor package install or upgrade, it could be due to PHP version incompatibility, so check the vendor’s requirements against your platform setup.

2021-12-15

Write your answer


408

votes

Answer

Solution:

What are the syntax errors?

PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or ident{-code-18}-code-11}iers. It can{-code-18}-code-8}t guess your coding intentions.

{-code-18}-code-7}Function

Most important tips

There are a few basic precautions you can always take:

  • Use proper code indentation, or adopt any lofty coding style.
    Readability prevents irregularities.

  • Use an with syntax highlighting.
    Which also help with parentheses/bracket balancing.

    {-code-18}-code-7}Expected:

  • Read the language reference and examples in the manual.
    Twice, to become somewhat proficient.

How to interpret parser errors

A typical syntax error message reads:

Parse error: syntax error, unexpected {-code-18}-code-4{-code-18}-code-5}-code-2{-code-18}-code-5}, expecting {-code-18}-code-8}{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}{-code-18}-code-8} in file.php on line 217

Which lists the possible location of a syntax mistake. See the mentioned file name and line number.

A moniker such as{-code-18}-code-4{-code-18}-code-5}-code-2{-code-18}-code-5} explains which symbol the parser/tokenizer couldn{-code-18}-code-8}t process finally. This isn{-code-18}-code-8}t necessarily the cause of the syntax mistake, however.

It{-code-18}-code-8}s important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.

Solving syntax errors

There are many approaches to narrow down and fix syntax hiccups.

  • Open the mentioned source file. Look at the mentioned code line.

    • For runaway strings and misplaced operators, this is usually where you find the culprit.

    • Read the line left to right and imagine what each symbol does.

  • More regularly you need to look at preceding lines as well.

    • In particular, missing{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5} semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )

    • If{-code-18}-code-4{-code-18}-code-5} code blocks{-code-18}-code-5} are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simpl{-code-18}-code-11}y that.

  • Look at the syntax colorization!

    • Strings and variables and constants should all have d{-code-18}-code-11}ferent colors.

    • Operators{-code-18}-code-6} should be tinted distinct as well. Else they might be in the wrong context.

    • If you see string colorization extend too far or too short, then you have found an unescaped or missing closing{-code-18}-code-7} or{-code-18}-code-8} string marker.

    • Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone {-code-18}-code-11} it{-code-18}-code-8}s not{-code-18}-code-9},{-code-18}-code-10}, or parentheses following an operator. Two strings/ident{-code-18}-code-11}iers directly following each other are incorrect in most contexts.

  • Whitespace is your friend.
    Follow any coding style.

  • Break up long lines temporarily.

    • You can freely add newlines between operators or constants and strings. The parser will then concretize the line number for parsing errors. Instead of looking at the very lengthy code, you can isolate the missing or misplaced syntax symbol.

    • Split up complex{-code-18}-code-11} statements into distinct or nested{-code-18}-code-11} conditions.

    • Instead of lengthy math formulas or logic chains, use temporary variables to simpl{-code-18}-code-11}y the code. (More readable = fewer errors.)

    • Add newlines between:

      1. The code you can easily ident{-code-18}-code-11}y as correct,
      2. The parts you{-code-18}-code-8}re unsure about,
      3. And the lines which the parser complains about.

      Partitioning up long code blocks really helps to locate the origin of syntax errors.

  • Comment out offending code.

    • If you can{-code-18}-code-8}t isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.

    • As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.

    • Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)

    • When you can{-code-18}-code-8}t resolve the syntax issue, try to rewrite the commented out sections from scratch.

  • As a newcomer, avoid some of the confusing syntax constructs.

    • The ternary{-code-18}-code-13} condition operator can compact code and is useful indeed. But it doesn{-code-18}-code-8}t aid readability in all cases. Prefer plain{-code-18}-code-11} statements while unversed.

    • PHP{-code-18}-code-8}s alternative syntax ({-code-18}-code-11}:/else{-code-18}-code-11}:/end{-code-18}-code-11}{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}) is common for templates, but arguably less easy to follow than normal{-code-18}-code-4{-code-18}-code-5} code{-code-18}-code-5} blocks.

  • The most prevalent newcomer mistakes are:

    • Missing semicolons{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5} for terminating statements/lines.

    • Mismatched string quotes for{-code-18}-code-7} or{-code-18}-code-8} and unescaped quotes within.

    • Forgotten operators, in particular for the string. concatenation.

    • Unbalanced( parentheses). Count them in the reported line. Are there an equal number of them?

  • Don{-code-18}-code-8}t forget that solving one syntax problem can uncover the next.

    • If you make one issue go away, but other crops up in some code below, you{-code-18}-code-8}re mostly on the right path.

    • If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)

  • Restore a backup of previously working code, {-code-18}-code-11} you can{-code-18}-code-8}t fix it.

    • Adopt a source code versioning system. You can always view ad{-code-18}-code-11}f of the broken and last working version. Which might be enlightening as to what the syntax problem is.
  • Invisible stray Unicode characters: In some cases, you need to use a hexeditor or d{-code-18}-code-11}ferent editor/viewer on your source. Some problems cannot be found just from looking at your code.

    • Try as the first measure to find non-ASCII symbols.

    • In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.

  • Take care of which type of linebreaks are saved in files.

    • PHP just honors n newlines, not r carriage returns.

    • Which is occasionally an issue for MacOS users (even on OS {-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5} X for misconfigured editors).

    • It often only surfaces as an issue when single-line// or# comments are used. Multiline/*...*/ comments do seldom disturb the parser when linebreaks get ignored.

  • If your syntax error does not transmit over the web:
    It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things:

    • You are looking at the wrong file!

    • Or your code contained invisible stray Unicode (see above).
      You can easily find out: Just copy your code back from the web form into your text editor.

  • Check your PHP version. Not all syntax constructs are available on every server.

    • php -v for the command line interpreter

    • <{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}?php phpinfo(){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5} for the one invoked through the webserver.

    Those aren{-code-18}-code-8}t necessarily the same. In particular when working with frameworks, you will them to match up.

  • Don{-code-18}-code-8}t use PHP{-code-18}-code-8}s reserved keywords as ident{-code-18}-code-11}iers for functions/methods, classes or constants.

  • Trial-and-error is your last resort.

If all else fails, you can always google your error message. Syntax symbols aren{-code-18}-code-8}t as easy to search for (Stack Overflow itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.

Further guides:

  • PHP Debugging Basics by David Sklar
  • Fixing PHP Errors by Jason McCreary
  • PHP Errors – 10 Common Mistakes by Mario Lurig
  • Common PHP Errors and Solutions
  • How to Troubleshoot and Fix your WordPress Website
  • A Guide To PHP Error Messages For Designers — Smashing Magazine

White screen of death

If your website is just blank, then typically a syntax error is the cause.
Enable their display with:

  • error_reporting = E_ALL
  • display_errors = 1

In your generally, or via for mod_php,
or even with FastCGI setups.

Enabling it within the broken script is too late because PHP can{-code-18}-code-8}t even interpret/run the first line. A quick workaround is crafting a wrapper script, saytest.php:

<{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}?php
   error_reporting(E_ALL){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}
   ini_set({-code-18}-code-7}display_errors{-code-18}-code-7}, 1){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}
   include({-code-18}-code-7}./broken-script.php{-code-18}-code-7}){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHP{-code-18}-code-8}serror_log and look into your webserver{-code-18}-code-8}s when a script crashes with HTTP 500 responses.


182

votes

Answer

Solution:

I think this topic is totally overdiscussed/overcomplicated. Using an IDE is THE way to go to completely avoid any syntax errors. I would even say that working without an IDE is kind of unprofessional. Why? Because modern IDEs check your syntax after every character you type. When you code and your entire line turns red, and a big warning notice shows you the exact type and the exact position of the syntax error, then there’s absolutely no need to search for another solution.

Using a syntax-checking IDE means:

You’ll (effectively) never run into syntax errors again, simply because you see them right as you type. Seriously.

Excellent IDEs with syntax check (all of them are available for Linux, Windows and Mac):

  1. NetBeans [free]
  2. PHPStorm [$199 USD]
  3. Eclipse with PHP Plugin [free]
  4. Sublime [$80 USD] (mainly a text editor, but expandable with plugins, like PHP Syntax Parser)


627

votes

Answer

Solution:

Unexpected{-code-11}-code-1}

These days, the unexpected{-code-11}-code-1} array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only support{-code-11}-code-3}.

{-code-17}php53 = array{-code-12}1, 2, 3{-code-23};
{-code-17}php54 = {-code-11}-code-1}1, 2, 3{-code-21};
         ⇑

Array function result dereferencing is likewise not available for older PHP versions:

{-code-17}result = get_whatever{-code-12}{-code-23}{-code-11}-code-1}"key"{-code-21};
                      ⇑

Reference — What does this error mean in PHP? — «Syntax error, unexpected shows the most common and practical workarounds.

Though, you’re always better off just upgrading your PHP installation. For shared webhosting plans, first research if e.g.{-code-11}-code-7} can be used to enable a newer runtime.

See also:

  • PHP syntax for dereferencing function result в†’ possible as of PHP 5.4
  • PHP syntax error, unexpected ‘{-code-11}-code-1}’
  • Shorthand for arrays: is there a literal syntax like {-code-11}} or {-code-11}-code-1}{-code-21}?
  • PHP 5.3.10 vs PHP 5.5.3 syntax error unexpected ‘{-code-11}-code-1}’
  • PHP Difference between {-code-11}-code-3} and {-code-11}-code-1}{-code-21}
  • PHP Array Syntax Parse Error Left Square Bracket «{-code-11}-code-1}»

BTW, there are also preprocessors and PHP 5.4 syntax down-converters if you’re really clingy with older + slower PHP versions.

Other causes for Unexpected{-code-11}-code-1} syntax errors

If it’s not the PHP version mismatch, then it’s oftentimes a plain typo or newcomer syntax mistake:

  • You can’t use array property declarations/expressions in classes, not even in PHP 7.

    protected {-code-17}var{-code-11}-code-1}"x"{-code-21} = "Nope";
                  ⇑
    
  • Confusing{-code-11}-code-1} with opening curly braces{-code-11} or parentheses{-code-12} is a common oversight.

    foreach {-code-11}-code-1}{-code-17}a as {-code-17}b{-code-23}
            ⇑
    

    Or even:

    function foobar{-code-11}-code-1}{-code-17}a, {-code-17}b, {-code-17}c{-code-21} {-code-11}
                   ⇑
    
  • Or trying to dereference {-code-16}ants {-code-12}before PHP 5.6{-code-23} as arrays:

    {-code-17}var = {-code-16}{-code-11}-code-1}123{-code-21};
           ⇑
    

    At least PHP interprets that{-code-16} as a {-code-16}ant name.

    If you meant to access an array variable {-code-12}which is the typical cause here{-code-23}, then add the leading{-code-17} sigil — so it becomes a{-code-17}varname.

  • You are trying to use the{-code-19} keyword on a member of an associative array. This is not valid syntax:

    {-code-19} {-code-17}var{-code-11}-code-1}'key'{-code-21};
    

Unexpected{-code-21} closing square bracket

This is somewhat rarer, but there are also syntax accidents with the terminating array{-code-21} bracket.

  • Again mismatches with{-code-23} parentheses or} curly braces are common:

    function foobar{-code-12}{-code-17}a, {-code-17}b, {-code-17}c{-code-21} {-code-11}
                              ⇑
    
  • Or trying to end an array where there isn’t one:

    {-code-17}var = 2{-code-21};
    

    Which often occurs in multi-line and nested array declarations.

    {-code-17}array = {-code-11}-code-1}1,{-code-11}-code-1}2,3{-code-21},4,{-code-11}-code-1}5,6{-code-11}-code-1}7,{-code-11}-code-1}8{-code-21},{-code-11}-code-1}9,10{-code-21}{-code-21},11{-code-21},12{-code-21}{-code-21},15{-code-21};
                                                 ⇑
    

    If so, use your IDE for bracket matching to find any premature{-code-21} array closure. At the very least use more spacing and newlines to narrow it down.


42

votes

Answer

Solution:

Unexpected {-code-1{-code-16}

An «{-code-13{-code-16}unexpected{-code-1{-code-16}«{-code-13{-code-16} means that there’s a literal{-code-2{-code-16} name{-code-8{-code-16} which doesn’t fit into the current expression/statement structure{-code-4{-code-16}

purposefully abstract/inexact operator+{-code-2{-code-16} diagram

  1. Missing semicolon

    It most commonly indicates a missing semicolon in the previous line{-code-4{-code-16} Variable assignments following a statement are a good indicator where to look:

            {-code-3{-code-16}
    
  2. String concatenation

    A frequent mishap are string concatenations with {-code-14{-code-16}gotten{-code-4{-code-16} operator:

                                    {-code-5{-code-16}
    

    Btw{-code-8{-code-16} you should prefer string interpolation {-code-23}basic variables in double quotes) whenever that helps readability{-code-4{-code-16} Which avoids these syntax issues{-code-4{-code-16}

    String interpolation is a scripting language core feature{-code-4{-code-16} No shame in utilizing it{-code-4{-code-16} Ignore any micro-optimization advise about variable{-code-4{-code-16} concatenation being faster{-code-4{-code-16} It’s not{-code-4{-code-16}

  3. Missing expression operators

    Of course the same issue can arise in other expressions{-code-8{-code-16} {-code-14{-code-16} instance arithmetic operations:

                {-code-7{-code-16}
    

    PHP can’t guess here {-code-19} the variable should have been added{-code-8{-code-16} subtracted or compared etc{-code-4{-code-16}

  4. Lists

    Same {-code-14{-code-16} syntax {-code-11{-code-16}s{-code-8{-code-16} like in array populations{-code-8{-code-16} where the parser also indicates an expected comma{-code-8{-code-16} {-code-14{-code-16} example:

                                           ⇓
     $var = array{-code-23}"{-code-13{-code-16}1"{-code-13{-code-16} =>{-code-13{-code-16} $val{-code-8{-code-16} $val2{-code-8{-code-16} $val3 $val4){-code-13{-code-16}
    

    Or functions parameter {-code-11{-code-16}s:

                                     ⇓
     function myfunc{-code-23}$param1{-code-8{-code-16} $param2 $param3{-code-8{-code-16} $param4)
    

    Equivalently do you see this with{-code-11{-code-16} or{-code-12{-code-16} statements{-code-8{-code-16} or when lacking a{-code-13{-code-16} semicolon in a{-code-14{-code-16} loop{-code-4{-code-16}

  5. Class declarations

    This parser error also occurs in class declarations{-code-4{-code-16} You can only assign static constants{-code-8{-code-16} not expressions{-code-4{-code-16} Thus the parser complains about variables as assigned data:

     class xyz {      ⇓
         var $value = $_GET["{-code-13{-code-16}input"{-code-13{-code-16}]{-code-13{-code-16}
    

    Unmatched{-code-16} closing curly braces can in particular lead here{-code-4{-code-16} If a method is terminated too early {-code-23}use proper indentation!){-code-8{-code-16} then a stray variable is commonly misplaced into the class declaration body{-code-4{-code-16}

  6. Variables after ident{-code-19}iers

    You can also never have a variable follow an ident{-code-19}ier directly:

                  ⇓
     $this->{-code-13{-code-16}myFunc$VAR{-code-23}){-code-13{-code-16}
    

    Btw{-code-8{-code-16} this is a common example where the intention was to use variable variables perhaps{-code-4{-code-16} In this case a variable property lookup with$this->{-code-13{-code-16}{"{-code-13{-code-16}myFunc$VAR"{-code-13{-code-16}{-code-16}{-code-23}){-code-13{-code-16} {-code-14{-code-16} example{-code-4{-code-16}

    Take in mind that using variable variables should be the exception{-code-4{-code-16} Newcomers often try to use them too casually{-code-8{-code-16} even when arrays would be simpler and more appropriate{-code-4{-code-16}

  7. Missing parentheses after language constructs

    Hasty typing may lead to {-code-14{-code-16}gotten opening or closing parenthesis
    {-code-14{-code-16}{-code-19} and{-code-14{-code-16} and{-code-14{-code-16}each statements:

            ⇓
     {-code-14{-code-16}each $array as $key) {
    

    Solution: add the missing opening{-code-23} between statement and variable{-code-4{-code-16}

                           ⇓
     {-code-19} {-code-23}$var = pdo_query{-code-23}$sql) {
          $result = …
    

    The curly{ brace does not open the code block{-code-8{-code-16} without closing the{-code-19} expression with the) closing parenthesis first{-code-4{-code-16}

  8. Else does not expect conditions

         ⇓
    else {-code-23}$var >{-code-13{-code-16}= 0)
    

    Solution: Remove the conditions fromelse or use {-code-4{-code-16}

  9. Need brackets {-code-14{-code-16} closure

         ⇓
    function{-code-23}) use $var {{-code-16}
    

    Solution: Add brackets around$var{-code-4{-code-16}

  10. Invisible whitespace

    As mentioned in the reference answer on «{-code-13{-code-16}Invisible stray Unicode»{-code-13{-code-16} {-code-23}such as a non-breaking space){-code-8{-code-16} you might also see this error {-code-14{-code-16} unsuspecting code like:

    <{-code-13{-code-16}?php
                              в‡ђ
    $var = new PDO{-code-23}{-code-4{-code-16}{-code-4{-code-16}{-code-4{-code-16}){-code-13{-code-16}
    

    It’s rather prevalent in the start of files and {-code-14{-code-16} copy-and-pasted code{-code-4{-code-16} Check with a hexeditor{-code-8{-code-16} {-code-19} your code does not visually appear to contain a syntax issue{-code-4{-code-16}

See also

  • Search: unexpected {-code-1{-code-16}


770

votes

Answer

Solution:

Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE

The unwieldy namesT_CONSTANT_ENCAPSED_STRING andT_ENCAPSED_AND_WHITESPACE refer to quoted "string" literals.

They’re used in different contexts, but the syntax issue are quite similar. T_ENCAPSED… warnings occur in double quoted string context, while T_CONSTANT… strings are often astray in plain PHP expressions or statements.

  1. Incorrect variable interpolation

    And it comes up most frequently for incorrect PHP variable interpolation:

                              ⇓     ⇓
    echo "Here comes a $wrong['array'] access";
    

    Quoting arrays keys is a must in PHP context. But in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted'string', because it usually expects a literal identifier / key there.

    More precisely it’s valid to use PHP2-style simple syntax within double quotes for array references:

    echo "This is only $valid[here] ...";
    

    Nested arrays or deeper object references however require the complex curly string expression syntax:

    echo "Use {$array['as_usual']} with curly syntax.";
    

    If unsure, this is commonly safer to use. It’s often even considered more readable. And better IDEs actually use distinct syntax colorization for that.

  2. Missing concatenation

    If a string follows an expression, but lacks a concatenation or other operator, then you’ll see PHP complain about the string literal:

                           ⇓
    print "Hello " . WORLD  " !";
    

    While it’s obvious to you and me, PHP just can’t guess that the string was meant to be appended there.

  3. Confusing string quote enclosures

    The same syntax error occurs when confounding string delimiters. A string started by a single' or double" quote also ends with the same.

                    ⇓
    print "<a href="' . $link . '">click here</a>";
          вЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџвЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџвЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџ
    

    That example started with double quotes. But double quotes were also destined for the HTML attributes. The intended concatenation operator within however became interpreted as part of a second string in single quotes.

    Tip: Set your editor/IDE to use slightly distinct colorization for single and double quoted strings. (It also helps with application logic to prefer e.g. double quoted strings for textual output, and single quoted strings only for constant-like values.)

    This is a good example where you shouldn’t break out of double quotes in the first place. Instead just use proper for the HTML attributesВґ quotes:

    print "<a href="{$link}">click here</a>";
    

    While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently.

  4. Missing opening quote

    Equivalently are forgotten opening a recipe for parser errors:

                   ⇓
     make_url(login', 'open');
    

    Here the', ' would become a string literal after a bareword, when obviouslylogin was meant to be a string parameter.

  5. Array lists

    If you miss a, comma in an array creation block, the parser will see two consecutive strings:

    array(               ⇓
         "key" => "value"
         "next" => "....",
    );
    

    Note that the last line may always contain an extra comma, but overlooking one in between is unforgivable. Which is hard to discover without syntax highlighting.

  6. Function parameter lists

    The same thing for function calls:

                             ⇓
    myfunc(123, "text", "and"  "more")
    
  7. Runaway strings

    A common variation are quite simply forgotten string terminators:

                                    ⇓
    mysql_evil("SELECT * FROM stuffs);
    print "'ok'";
          ⇑
    

    Here PHP complains about two string literals directly following each other. But the real cause is the unclosed previous string of course.

  8. HEREDOC indentation

    Prior PHP 7.3, the heredoc string end delimiter can’t be prefixed with spaces:

    print <<< HTML
        <link..>
        HTML;
       ⇑
    

    Solution: upgrade PHP or find a better hoster.

See also

  • Interpolation (double quoted string) of Associative Arrays in PHP
  • PHP — syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
  • Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in PHP
  • Unexpected T_CONSTANT_ENCAPSED_STRING error in SQL Query


153

votes

Answer

Solution:

Unexpected

is a bit of a misnomer. It does not refer to a quoted{-code-2}. It means a raw identifier was encountered. This can range from{-code-3} words to leftover{-code-4} or function names, forgotten unquoted strings, or any plain text.

  1. Misquoted strings

    This syntax error is most common for misquoted string values however. Any unescaped and stray{-code-5} or{-code-6} quote will form an invalid expression:

                   ⇓                  ⇓
     {-code-11} {-code-5}<{-code-29}a href={-code-5}http://example.com{-code-5}>{-code-29}click here<{-code-29}/a>{-code-29}{-code-5}{-code-29}
    

    Syntax highlighting will make such mistakes super obvious. It{-code-6}s important to remember to use backslashes for escaping{-code-33}{-code-5} double quotes, or{-code-33}{-code-6} single quotes — depending on which was used as string enclosure.

    • For convenience you should prefer outer single quotes when outputting plain HTML with double quotes within.
    • Use double quoted strings if you want to interpolate variables, but then watch out for escaping literal{-code-5} double quotes.
    • For lengthier output, prefer multiple{-code-11}/{-code-12} lines instead of escaping in and out. Better yet consider a HEREDOC section.

    Another example is using PHP entry inside HTML code generated with PHP:

    {-code-14} = {-code-6}<{-code-29}div>{-code-29}some text with {-code-25}php {-code-11} {-code-6}some php entry{-code-6} ?>{-code-29}<{-code-29}/div>{-code-29}{-code-6}
    

    This happens if{-code-14} is large with many lines and developer does not see the whole PHP variable value and focus on the piece of code forgetting about its source. Example is here

    See also What is the difference between single-quoted and double-quoted strings in PHP?.

  2. Unclosed strings

    If you miss a closing then a syntax error typically materializes later. An unterminated string will often consume a bit of code until the next intended string value:

                                                           ⇓
    {-code-11} {-code-5}Some text{-code-5}, {-code-32}a_variable, {-code-5}and some runaway string {-code-29}
    success({-code-5}finished{-code-5}){-code-29}
             в‡Ї
    

    It{-code-6}s not just literals which the parser may protest then. Another frequent variation is an for unquoted literal HTML.

  3. Non-programming string quotes

    If you copy and paste code from a blog or website, you sometimes end up with invalid code. Typographic quotes aren{-code-6}t what PHP expects:

    {-code-14} = ’Something something..’ + {-code-20} ain{-code-6}t quotes”{-code-29}
    

    Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example{-code-20} is interpreted as a constant identifier. But any following text literal is then seen as a {-code-3}word/ by the parser.

  4. The missing semicolon{-code-29} again

    If you have an unterminated expression in previous lines, then any following statement or language construct gets seen as raw identifier:

           {-code-21}
    

    PHP just can{-code-6}t know if you meant to run two functions after another, or if you meant to multiply their results, add them, compare them, or only run one{-code-22} or the other.

  5. Short open tags and{-code-23} headers in PHP scripts

    This is rather uncommon. But if short_open_tags are enabled, then you can{-code-6}t begin your PHP scripts with an XML declaration:

          ⇓
    {-code-23} {-code-27}={-code-5}1.0{-code-5}?>{-code-29}
    


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-12-15

Link To Source

Link To Answer
People are also looking for solutions of the problem: target class [commandmakecommand] does not exist.

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.


About the technologies asked in this question

PHP

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

Laravel

Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework.
https://laravel.com/

JavaScript

JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/

MySQL

DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL.
It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/

HTML

HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/



Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Updated on April 5, 2022

Parse Error, Syntax Error Unexpected in WordPress [FIXED]

Parse Error: Syntax Error Unexpected ‘ ‘ in WordPress

Table of Contents [TOC]

  • Parse Error: Syntax Error Unexpected ‘ ‘ in WordPress
    • What are parse error: syntax errors ?
    • What Is A Syntax Error?
    • What Causes the PHP parse/syntax errors in WordPress?
    • How to detect syntax error in wordpress?
    • How To Find Parse Error in WordPress?
  • How To Fix parse error syntax error unexpected ‘ ‘ in wordpress Via FTP?
    •  Steps to Fix Syntax Error in WordPress Via FTP
    • Fix Parse Error by Uploading Fresh Files
    • Tools To Help You Fix The Syntax Error in WordPress
  • How To Avoid Syntax Errors?
    • Enable debugging
    • Disable plugins and themes
    • Like this:
    • Related

Trying something new on your WordPress site? Got any of the following errors like

⚠️ parse error: syntax error, unexpected t_string wordpress,

⚠️ parse error syntax error unexpected end of file in wordpress,

⚠️ parse error: syntax error, unexpected t_function wordpress,

⚠️ parse error syntax error unexpected text t_string wordpress,

⚠️ parse error syntax error unexpected if t_if wordpress,

⚠️ wordpress parse error syntax error unexpected expecting or ‘;’

then don’t freak out. You are not the first one to receive the parse error in WordPress. In this article we will show you how to fix the unexpected syntax error in WordPress. The parse error in WordPress isn’t a common error, and it typically occurs through a mistake made by the user.

Sometimes we install a new plugin in our WordPress and when we activate it we get a syntax error. Sometimes that error appears between the content, but sometimes all the content disappears and we only see the error. Or worse, sometimes not even that. We only have a blank screen.

We are here to tell you that this is completely normal if you have seen the “Syntax Error”⚠️ message because WordPress can sometimes be confusing with annoying syntax errors.

These errors occur if the correct PHP syntax rules are not followed. In this tutorial, we will show you how to fix syntax error in WordPress with simple instructions for beginners.

Let’s see how to understand, debug and fix  a syntax error, or alternatively, at least isolate it:

Some Commonly Asked Questions:

  • How to Fix the Syntax Error in WordPress?
  • How to Fix Parse error: syntax error, unexpected ‘ ‘ WordPress?⚠️
  • How to Fix the Parse Error in WordPress?
  • How to debug and fix WordPress Syntax Errors?

In this post you will also know more about:

  • How do you fix a syntax error?
  • What is parse error syntax error unexpected?
  • What is a parse error in WordPress?
  • How do I fix invalid syntax in Python?
  • What causes a syntax error?
  • What Is syntax error with example?

What are parse error: syntax errors ?

parse error syntax error in WordPress

PHP errors⚠️ can occur when your code is being converted from a series of characters to something that is visible to the visitors of your site.

This error may also happen when an update is made by the developer of a theme or an extension (this is rather rare, but it can happen).

For example, you may have made syntax errors in your code by forgetting parentheses, adding spaces or characters.

These errors occur when the PHP code can’t start or finish being parsed. Obviously, if this is the case, something terribly wrong has happened and it may take more than putting some } there to heal your code.

This could be a copy and paste problem. Maybe the developer did not copy and paste the lines of the code as mentioned in the tutorial.

⚠️ The most probable cause of the error is a missing or a mismatched parenthesis in the PHP code

In WordPress, there are typically 3 main kinds of parse error which may occur to your WordPress site:

⚠️ Syntax error – It occurs because of the semicolons, curly brackets or quotations that were used in the PHP code. Either one of them is missing or the wrong ones were added.

⚠️ Unexpected error – It happens when you include a character such as an opening or closing bracket or other similar characters. This is a parse error which occurs when php is still looking for something and reaches the end of the file without finding it. It could be a quote or bracket which is unclosed, and php is still treating the file contents as a part of the quote.

Php is just telling you it was unexpected

⚠️ Undefined constant error – This is the problem with the character missing in an array while referencing a variable or possible scenarios.

It is extremely important to keep in mind that these three kinds of parsing errors have many different variations depending on the specific mistake in the written PHP code.

Related Issue – Fix WordPress Stuck in Maintenance Mode

What Is A Syntax Error?

Fixing the Syntax Error unexpected in wordpress website

The WordPress syntax error is common among users who add code snippets to their WordPress sites. When this error occurs, you usually see something like in the homepage of the website:

⚠️ Parse error: syntax error, unexpected T_FUNCTION in /home/content/94/4245094/html/wp-content/plugins/my-calendar/my-calendar-styles.php on line 465

Often this error happens because a programming language is not used properly, that is, the rules are not followed and the code is written incorrectly. It can be something as simple as not placing a semicolon, or that a complete file is misspelled. When compiling, it will not be understood and that error will appear. The positive thing about this error is that you will know exactly what it is and we will see how to correct it. In case you run a multi wordpress site and want to find out which user activity lead to this error, it can be found by monitoring user activity in wordpress dashboard.

Parse-Error-in-WordPress_-How-to-Fix-Syntax-Errors-in-WordPress

Syntax errors structure:

“Parse error: syntax error, unexpected character in path/to/php-file.php on line number

Undefined constant errors structure:

“Notice: Use of undefined constant constant string – assumed ‘constant string‘ in path/to/php-file.php on line number

Unexpected errors Example

“Parse error: unexpected character in path/to/php-file.php on line number

Unexpected parse errors may list a string instead of a character.

In each of these examples, number refers to the line number and is going to be replaced with actual numbers such as 23 or 1256, for example, though, not necessarily those exact line numbers.

  • The file indicated in the error message is – where the issue persists
  • The line number gives you a hint as to where to look for the mistake.

The character or constant string names give you an idea of what to look for around the indicated line number. These are what needs fixing or else they’re related to what needs correcting.

Related Read Fix Sorry, This File Type Is Not Permitted For Security Reasons

What Causes the PHP parse/syntax errors in WordPress?

Even a small typo error in the wrong place can cause the operation of your entire WordPress page to stop working. However, the message “Syntax error” is not an insoluble problem.

A syntax error is, as a rule, caused by a small critical error in the syntax of your code. A missing comma or an incorrect parenthesis interrupts the entire script. Have you recently installed a snippet or updated a plugin? If this is the case, then you should check this first.

To resolve WordPress syntax errors, you must rework the part of the code that caused this error. Either you delete it completely or you correct the syntax.

As a beginner, it is not uncommon to be quickly frustrated when a single mistake makes the entire site inaccessible. If you have added the code in your WordPress dashboard via the editor area then it is no longer possible to directly access your WordPress code.

How to detect syntax error in wordpress?

If the error appeared just after you have pasted some block of code, check the latter mainly.

Anyway, in the syntax error message, you will see the damaged file and the line of code that you should review. This is also seen when you activate the debug by defining define (‘WP_DEBUG’, true); in wp-config.php.

  • Check that you do not miss any semicolons. There are codes that at first glance do not seem to have an error, and adding a semicolon at the end, the error message disappears.
  • Check that the quotes are in the proper format, in PHP the double and single quotes are used, make sure they are not italic.
  • Check that there is no missing parenthesis to open or close. You can PHP code syntax for any errors using this handy tool.

To identify the origin or cause of this error, follow the steps below:

  • wp-config.php: Activate debug by defining define (‘WP_DEBUG’, true); Normally it will throw the error on the screen where it will indicate the file, the line and the type of error that was found during the execution.
  • Close each order: Check that you do not lack a ; at the close of each line.
  • Check the quotes: In PHP, single quotes and double quotes are used. Sometimes, when copying and pasting, the format is moved and the quotes appear cursive (curly quotes). Example:  “” instead of “” or ‘’ instead of ”.
  • Check the parentheses: It is very common in instructions with leaving a parenthesis to close or to open. Balanced parentheses require every opening parenthesis to be closed in the reverse order opened.

How To Find Parse Error in WordPress?

The easiest way to open a PHP file is to open it using the default text editor on your computer. The default text editor is based on JavaScript which allows it to run on several platforms and CMS like WordPress and is compatible with most web browsers.

The text editors allow us to write while we see the final result of the text.

And ultimately, the editor generates the content as text, images and other elements in HTML code and shows it to us in a similar way to how it will be on our website.

Popular text editors include

  • Notepad++
  • Sublime Text
  • Atom
  • Brackets
  • TextWrangler

Related Read How To Fix “This Account Has Been Suspended” error in WordPress

How To Fix parse error syntax error unexpected ‘ ‘ in wordpress Via FTP?

How To Fix Parse Error Syntax Error Via FTP

In order to fix the Syntax Error in WordPress you need to edit the code that caused this error.  The only possible way to resolve the syntax error is to directly exchange the faulty code via FTP or access the file you last edited using FTP.

 Steps to Fix Syntax Error in WordPress Via FTP

  • >> After installing the FTP program
  • >> connect it to your website
  • >> go to the theme file that needs editing.

In case you forgot which file you need to edit, just look at the error code. The error will tell you exactly which file and which line you need to edit.

  • >> Remove the code you last added / write the code in correct syntax
  • >> Save the file and upload it back to your server
  • >> Come to your WordPress site and refresh the page, and it will open as before..

How to Fix Parse Error Syntax Errors in WordPress

Fix Parse Error by Uploading Fresh Files

  • If you cannot figure out how to fix your code >> try uploading a fresh version of the file.
  • If your theme is the problem >> download a copy of it (the version you’re using).
  • If you only have the original folder archived and have only updated the theme through the WordPress admin ever since >> download a fresh copy of it from your theme provider.
  • If you do choose the WordPress root and your problem is with wp-includes or wp-admin >> you can safely upload fresh copies of these files to your site.

Tools To Help You Fix The Syntax Error in WordPress

If you have already tried the above steps and still get the syntax error, we recommend that you should try the tools given below:

PHP Storm

It is an IDE considered quite complete with its paid version of monthly or annual membership (USD $199) you can receive all the updates. Php Storm is part of JetBrains, and they offer the whole package (including PHPStorm) for USD 649 per year.

However, they offer a version for university students, with the prohibition of use for commercial purposes.

Visual Studio Code

It is a code editor with many features for beginners and experts. Visual Studio Code also accepts multiple extensions and customizations.

Related Read How To Fix WordPress Not Sending Email Issue

How To Avoid Syntax Errors?

The ideal is that you learn PHP because knowledge of a language is what helps you to detect errors in your code at a glance.

Avoiding these errors is as easy as fixing them if you’re at least a little familiar with PHP. You can check your code for syntax mistakes automatically by running it through a PHP code validator.

Otherwise, you can always check your codes before applying them to a website or convert them into a plugin. Here are some tools that can help you:

  • PHP Code Checker
  • W3 Markup Validation Service
  • PHP code Syntax Check 

Here are some tips of the most common syntax mistakes to look out for right off the bat:

  • Make sure there’s only one opening (<?php) and closing tag (?>)per document
  • Add code shouldn’t be inserted in between a function
    • Check for functions that are broken up by other ones

Enable debugging

If you still have the error of the syntax error or the admin area does not work (or you have found the cause but you still want to dig more), you can enable debugging which will show you all the errors.

The problem is that when a fatal error occurs, the script stops executing. If this happens before any content is displayed, you will only see an empty white screen.

To enable debugging, you will need to open the wp-config.php file from your WordPress installation. Find the following line:

define(‘WP_DEBUG’, false);

Replace false with true and reload your site. If this line does not exist, add it at the top.

wordpress_debug_options_wp-config

Instead of the blank page, you will now have a blank page with error messages. It’s not much, but now you can start. If you have not disabled plugins and themes yet, you will be able to determine the source of the problem by viewing the error message.

It should indicate the file in which the error occurred. It could be something like this:

Cannot redeclare get_posts()in/var/www/html/wordpress/wp-content/plugins/my-test-plug my-test-plugin.php on line 38

At the end of the message, you can see that the problem is in line 38, and it’s a plugin called “my-test-plugin”. By disabling this plugin, the site should work.

You can correct this line if you like to change the codes. If it is a plugin from the repository, it would be better to write to the author instead of doing it yourself. By modifying the plugin, you will have to maintain all your modifications, which is a puzzle. It is best to wait for the developer to do it.

If you do not see any error after enabling debugging, try contacting your web host because it may be that debugging is not properly configured on your server.

Disable plugins and themes

Check if the error started when you activated a new theme or plugin, so you should replace it or contact the developer. Often this error does not allow you to log into WordPress, so you must use FTP to remove the plugin or theme.

Disabling all your plugins is one of the easiest and most common ways to solve the wordpress syntax error. A bad update of a plugin is often the cause. If you still have access to your admin area, you can quickly get there by going to “Plugins” to select “Deactivate” from the action menu.

This will disable all your plugins. If that solves the problem, all you have to do is find out which plugin is the culprit. Start activating them one by one while loading the site after each activation.

We hope this article helped you fix parse error syntax error wordpress. Now you know how to fix parse errors, what causes them, and how to avoid them in the future.


Read More About Other Common WordPress Errors:

  • How to Fix Error Establishing a Database Connection in WordPress?
  • Remove “This Site May Be Hacked” From WordPress in Google
  • How to fix “The link you followed has expired” in WordPress?
  • How to Fix Pluggable.php File Errors in WordPress?
  • How To Fix WordPress Upload Failed To Write File To Disk Error?
  • WordPress HTTP Image Upload Error – How To Fix It?

If you’ve ever updated a plugin or pasted code into your WordPress website, chances are you’ve problem seen the parse error syntax error unexpected end in WordPress message. This is a common error because it only takes one character to cause it. In this article, we’ll explore what causes this error and see how to fix it.

  • 1
    What Does Parse Error: Syntax Error, Unexpected End in WordPress Mean?

  • 2
    How to Solve Parse Error: Syntax Error Unexpected End in WordPress

  • 3
    Testing the Parse Error Syntax Error Unexpected End in WordPress

    • 3.1
      Editing Plugin Code

  • 4
    Fixing the Parse Error When You Can’t Find the Error

    • 4.1
      Debug Mode

    • 4.2
      Debugging Plugin

  • 5
    Fixing the Parse Error if You’re Locked Out of WordPress

  • 6
    Restoring a Previous File

    • 6.1
      Upload a Clean Copy of WordPress

  • 7
    Ending Thoughts on the Parse Error Syntax Error Unexpected End in WordPress

What Does Parse Error: Syntax Error, Unexpected End in WordPress Mean?

Parse error syntax error unexpected end in WordPress can be the simplest of errors and still cause a big problem.

The error has two parts:

Syntax Error – This error is caused by an error in the PHP structure when a character is missing or added that shouldn’t be there.

Unexpected – This means the code is missing a character and PHP reaches the end of the file without finding what it’s looking for. The error will include information at the end that explains what it saw that was unexpected.

If you see Parse Error: Syntax Error, Unexpected end in WordPress, it just means that WordPress detected that something in the code is missing or added. It can be something as simple as a comma, semi-colon, a closing parenthesis, or one too many brackets.

The missing syntax can be within code that you’ve written or pasted into your website, or within a theme or plugin that you’ve installed or updated.

Fortunately, it’s not that difficult to find and fix. However, you will need to understand how code works and how to edit it.

How to Solve Parse Error: Syntax Error Unexpected End in WordPress

How to Solve Parse Error

The actual parse error syntax error unexpected end in WordPress will have a different ending depending on what’s causing the error.

Examples include:

  • 1) syntax error, unexpected end of file
  • 2) syntax error, unexpected token
  • 3) syntax error, unexpected variable
  • 4) syntax error, unexpected identifier

The error message will usually identify the specific token, variable, identifier, etc., that it doesn’t like. We’ll see a few examples of this as we go.

Testing the Parse Error Syntax Error Unexpected End in WordPress

WordPress has made lots of improvements in how it handles code. Now, instead of running bad code and killing your website, if it has a previous version of the code that ran, it tries to use that code instead when displaying the site to visitors.

This keeps your site from displaying the error to your visitors and keeps you from being locked out. It is still possible for your site to go down and lock you out, but it’s more difficult now.

Also, the code editors now show markup, so it’s easy to identify variables and other code elements. This makes it easier to test code within the plugin and theme code editors within WordPress.

Unfortunately, WordPress doesn’t always give you a clear message. Sometimes there is no message, content is missing, or it just doesn’t show the website. All of these can be fixed, but they might take a little more troubleshooting.

Let’s look at a few examples. We’ll start with something easy.

Editing Plugin Code

Editing Plugin Code

First, start with what you did last. In this example, I’ve edited code in a plugin file. The file reverted to the last known good code, so my changes are not working. Look at the error. It will tell you what’s causing the error code and the line of code with the error.

In this example, WordPress is seeing an unexpected bracket when it’s expecting to see a semi-colon.

This one is simple. First, look at the line above it. We see the word break, ending case 4. We’re fortunate in that we have other cases to compare to. Above it is case 3, which also ends with break, but this one has a closing semi-colon.

Editing Plugin Code

Next, edit the code that caused the error.

Editing Plugin Code

Here’s another example in the same plugin file. This one is showing the error on line 488. However, that line of code is correct. It’s giving me a clue, though. It’s identifying this as an unexpected variable.

Editing Plugin Code

If we look at the code above 488, we see that it’s missing a closing bracket. This causes WordPress to see the next line incorrectly.

Editing Plugin Code

Simply add the closing bracket and update the file. The code now works correctly.

These problems were simple, but most of the time you see a parse error syntax error unexpected end in WordPress, it’s exactly like these examples.

Fixing the Parse Error When You Can’t Find the Error

There are two ways to find the parse error if it doesn’t display for you or you’re not sure where it’s coming from. Here’s a look at both methods.

Debug Mode

The first step is to enable the WordPress error log. Go to your wp-config file using FTP or cPanel. Search for a line of code that looks like this:

define( 'WP_DEBUG', false );

If you have this code, change false to true.

If you don’t have this line of code, look for a line that says:

“Stop editing! Happy blogging.” and paste this code:

define( 'WP_DEBUG', true );

Load the website. This will display the error and you now have a place to start troubleshooting.

Debugging Plugin

Query Monitor

Query Monitor is one of the most popular debugging plugins. It provides tools that you can access from the frontend and backend from the top menu bar and as an overlay.

Query Monitor

This will enable several debugging tools including an error log where you can find the information you need.

Fixing the Parse Error if You’re Locked Out of WordPress

Fixing the Parse Error if You’re Locked Out of WordPress

If you’re locked out of the admin dashboard, you’ll need to make your changes another way. You’ll need to download the file from the server that contains the error and open it in a code editor to make your edits.

In my case, I was making changes in the functions.php file for the Twenty Twenty One theme. I made an error in my syntax and my site went down. All it shows is this error that doesn’t help.

Fixing the Parse Error if You’re Locked Out of WordPress

The best options are to use FTP or your host’s cPanel. I’ll use cPanel for this example, but the process is the same. First, open File Manager in cPanel.

Fixing the Parse Error if You’re Locked Out of WordPress

Next, open the folder for the website you’re working on. If it’s the primary site, you might see a globe icon. Otherwise, open the folder with the name of the website.

Fixing the Parse Error if You’re Locked Out of WordPress

Navigate to the wp-content folder.

Fixing the Parse Error if You’re Locked Out of WordPress

Navigate to the folder with the theme or plugin you want to edit. In this case, I’m editing a theme.

Fixing the Parse Error if You’re Locked Out of WordPress

Select the folder of the theme or plugin. I’m selecting the folder for the Twenty Twenty One theme.

Fixing the Parse Error if You’re Locked Out of WordPress

Next, go to the file you were editing when the problem occurred. I was editing the functions.php file. Either download the file to work offline or edit the file. I recommend downloading a backup before making changes.

Fixing the Parse Error if You’re Locked Out of WordPress

Your code editor might provide information about the error. In my case, it’s showing that it’s expecting a parenthesis on line 29. In reality, it’s missing a bracket on line 17, which causes the editor to think it needs a parenthesis.

Fixing the Parse Error if You’re Locked Out of WordPress

Adding the bracket removes the error. I can now upload my new file to replace the current file or save it if I’m using the online editor.

Fixing the Parse Error if You’re Locked Out of WordPress

My website now works as normal.

Restoring a Previous File

Restoring a Previous File

If you’re not sure what’s changed in the code and you want to restore a previous file that you know works, go to the file in FTP or cPanel.

Sometimes WordPress doesn’t tell you where the problem is coming from. In this case, you can rename the folders one at a time to see if the problem goes away. Start with your plugins.

If you do know where the problem is coming from, you can upload a replacement file. For a plugin or theme in the WordPress repository, you can delete the folder and reinstall it.

If you prefer, you can download the theme or plugin from the WordPress repository (or where you got it from), unzip the file, and only replace the file you need to. It works similarly to how we’ll replace WordPress in the next section.

Upload a Clean Copy of WordPress

Upload a Clean Copy of WordPress

If the problem is the WordPress core, you can upload a new version of WordPress without deleting your files. Download a new copy of WordPress and unzip it.

Upload a Clean Copy of WordPress

Next, delete the wp-content folder and the file called wp-config-sample.php.

Upload a Clean Copy of WordPress

Next, upload the WordPress files from the unzipped folder into your WordPress root folder. This will overwrite all files except for the two you deleted. Your site should work now.

Ending Thoughts on the Parse Error Syntax Error Unexpected End in WordPress

The parse error syntax error unexpected end in WordPress is a common error for anyone handling code. It’s not difficult to fix, but it can sometimes take time to track it down. The steps are simple:

  • If you’ve added code, start there.
  • If you’ve installed a plugin or theme, deactivate it.
  • When you can’t find the problem, replace the suspected files.
  • When all else fails, restore a backup.

Following a few troubleshooting steps will help get your site running smoothly as fast as possible.

We want to hear from you. Have you had the parse error syntax error unexpected end in WordPress? Let us know how you fixed it in the comments below.

Featured Image via alexdndz / shutterstock.com

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Parse error syntax error unexpected use
  • Parse error syntax error unexpected token echo
  • Parse error syntax error unexpected t string expecting t function
  • Parse error syntax error unexpected t string expecting t constant encapsed string or
  • Parse error syntax error unexpected t object operator

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии