Syntax error unexpected token expecting php

Различные части языка PHP внутренне представлены токенами. Фрагмент кода, содержащий недопустимую последовательность токенов, может привести к таким ошибкам, как Parse error: syntax error, unexpected token "==", expecting "(" in script.php on line 10.", где токен == внутренне представлен как T_IS_EQUAL.

Различные части языка PHP внутренне представлены токенами.
Фрагмент кода, содержащий недопустимую последовательность токенов, может привести к таким ошибкам, как Parse error: syntax error, unexpected token "==", expecting "(" in script.php on line 10.",
где токен == внутренне представлен как T_IS_EQUAL.

В следующей таблице перечислены все токены. Они также доступны как константы PHP.

Замечание:
Использование T_* констант

Значения T_* констант автоматически генерируются на основе базовой инфраструктуры синтаксического анализатора PHP.
Это означает, что конкретное значение метки может изменяться
между двумя версиями PHP.
Это означает, что ваш код никогда не должен напрямую полагаться
на исходные значения T_*, взятые из версии PHP X.Y.Z,
чтобы обеспечить некоторую совместимость между несколькими версиями PHP.

Чтобы использовать T_* константы в нескольких версиях PHP, неопределённые константы
могут быть определены пользователем (с использованием больших чисел, таких как 10000)
с соответствующей стратегией, которая будет работать как с версиями PHP, так и со значениями T_*.


<?php
// До PHP 7.4.0 значение T_FN не определено.
defined('T_FN') || define('T_FN', 10001);

Метки

Метка Синтаксис Ссылка
T_ABSTRACT abstract Абстрактные классы
T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG & Объявление типов (доступно, начиная с PHP 8.1.0)
T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG & Объявление типов (доступно, начиная с PHP 8.1.0)
T_AND_EQUAL &= операторы присваивания
T_ARRAY array() array(), синтаксис массива
T_ARRAY_CAST (array) приведение типа
T_AS as foreach
T_ATTRIBUTE #[ attributes (доступно с PHP 8.0.0)
T_BAD_CHARACTER   все, что ниже ASCII 32 исключая t (0x09), n (0x0a) и r (0x0d)
(доступно с PHP 7.4.0)
T_BOOLEAN_AND && логические операторы
T_BOOLEAN_OR || логические операторы
T_BOOL_CAST (bool) или (boolean) приведение типа
T_BREAK break break
T_CALLABLE callable callable
T_CASE case switch
T_CATCH catch Исключения
T_CLASS class классы и объекты
T_CLASS_C __CLASS__ магические константы
T_CLONE clone классы и объекты
T_CLOSE_TAG ?> или %> PHP-код внутри HTML
T_COALESCE ?? операторы сравнения
T_COALESCE_EQUAL ??= операторы присваивания
(доступно с PHP 7.4.0)
T_COMMENT // или #, и /* */ комментарии
T_CONCAT_EQUAL .= операторы присваивания
T_CONST const константы класса
T_CONSTANT_ENCAPSED_STRING «foo» или ‘bar’ строковой синтаксис
T_CONTINUE continue continue
T_CURLY_OPEN {$ переменные внутри строки
T_DEC операторы инкрементадекремента
T_DECLARE declare declare
T_DEFAULT default switch
T_DIR __DIR__ магические константы
T_DIV_EQUAL /= операторы присваивания
T_DNUMBER 0.12 и т.д. числа с плавающей точкой
T_DO do do..while
T_DOC_COMMENT /** */ PHPDoc-комментарии
T_DOLLAR_OPEN_CURLY_BRACES ${ переменная внутри строки
T_DOUBLE_ARROW => синтаксис массивов
T_DOUBLE_CAST (real), (double) или (float) приведение типов
T_DOUBLE_COLON :: смотрите ниже T_PAAMAYIM_NEKUDOTAYIM
T_ECHO echo echo
T_ELLIPSIS аргументы функции
T_ELSE else else
T_ELSEIF elseif elseif
T_EMPTY empty empty()
T_ENCAPSED_AND_WHITESPACE » $a» константная часть строки с переменными
T_ENDDECLARE enddeclare declare, альтернативный синтаксис
T_ENDFOR endfor for, альтернативный синтаксис
T_ENDFOREACH endforeach foreach, альтернативный синтаксис
T_ENDIF endif if, альтернативный синтаксис
T_ENDSWITCH endswitch switch, альтернативный синтаксис
T_ENDWHILE endwhile while, альтернативный синтаксис
T_ENUM enum Перечисления (доступно, начиная с PHP 8.1.0)
T_END_HEREDOC   синтаксис heredoc
T_EVAL eval() eval()
T_EXIT exit или die exit(), die()
T_EXTENDS extends extends, классы и объекты
T_FILE __FILE__ магические константы
T_FINAL final Ключевое слово final
T_FINALLY finally Исключения
T_FN fn стрелочные функции
(доступно с PHP 7.4.0)
T_FOR for for
T_FOREACH foreach foreach
T_FUNCTION function функции
T_FUNC_C __FUNCTION__ магические константы
T_GLOBAL global область видимости переменной
T_GOTO goto goto
T_HALT_COMPILER __halt_compiler() __halt_compiler
T_IF if if
T_IMPLEMENTS implements Интерфейсы объектов
T_INC ++ операторы инкрементадекремента
T_INCLUDE include() include
T_INCLUDE_ONCE include_once() include_once
T_INLINE_HTML   текст вне PHP
T_INSTANCEOF instanceof операторы типа
T_INSTEADOF insteadof Трейты
T_INTERFACE interface Интерфейсы объектов
T_INT_CAST (int) или (integer) приведение типов
T_ISSET isset() isset()
T_IS_EQUAL == операторы сравнения
T_IS_GREATER_OR_EQUAL >= операторы сравнения
T_IS_IDENTICAL === операторы сравнения
T_IS_NOT_EQUAL != или <> операторы сравнения
T_IS_NOT_IDENTICAL !== операторы сравнения
T_IS_SMALLER_OR_EQUAL <= операторы сравнения
T_LINE __LINE__ магические константы
T_LIST list() list()
T_LNUMBER 123, 012, 0x1ac и т.д. целые числа
T_LOGICAL_AND and логические операторы
T_LOGICAL_OR or логические операторы
T_LOGICAL_XOR xor логические операторы
T_MATCH match match (доступно с PHP 8.0.0)
T_METHOD_C __METHOD__ магические константы
T_MINUS_EQUAL -= операторы присваивания
T_MOD_EQUAL %= операторы присваивания
T_MUL_EQUAL *= операторы присваивания
T_NAMESPACE namespace пространства имён
T_NAME_FULLY_QUALIFIED AppNamespace пространства имён (доступно, начиная с PHP 8.0.0)
T_NAME_QUALIFIED AppNamespace пространства имён (доступно, начиная с PHP 8.0.0)
T_NAME_RELATIVE namespaceNamespace пространства имён (доступно, начиная с PHP 8.0.0)
T_NEW new классы и объекты
T_NS_C __NAMESPACE__ пространства имён
T_NS_SEPARATOR пространства имён
T_NUM_STRING «$a[0]» цифровой индекс массива внутри строки
T_OBJECT_CAST (object) приведение типов
T_OBJECT_OPERATOR -> классы и объекты
T_NULLSAFE_OBJECT_OPERATOR ?-> классы и объекты
T_OPEN_TAG <?php, <? или <% PHP-код внутри HTML
T_OPEN_TAG_WITH_ECHO <?= или <%= PHP-код внутри HTML
T_OR_EQUAL |= операторы
присваивания
T_PAAMAYIM_NEKUDOTAYIM :: ::. Также определяется как
T_DOUBLE_COLON.
T_PLUS_EQUAL += операторы
присваивания
T_POW ** арифметические операторы
T_POW_EQUAL **= операторы присваивания
T_PRINT print() print
T_PRIVATE private классы и объекты
T_PROTECTED protected классы и объекты
T_PUBLIC public классы и объекты
T_READONLY readonly классы и объекты (доступно, начиная с PHP 8.1.0)
T_REQUIRE require() require
T_REQUIRE_ONCE require_once() require_once
T_RETURN return возвращаемые значения
T_SL << побитовые операторы
T_SL_EQUAL <<= операторы присваивания
T_SPACESHIP <=> Операторы сравнения
T_SR >> побитовые операторы
T_SR_EQUAL >>= операторы присваивания
T_START_HEREDOC <<< синтаксис heredoc
T_STATIC static область видимости переменной
T_STRING parent, self и т.п.. идентификаторы, например, ключевые слова вроде parent и self,
сюда подходят также имена функций, классов и некоторые другие.
Смотрите также T_CONSTANT_ENCAPSED_STRING
T_STRING_CAST (string) приведение типов
T_STRING_VARNAME «${a переменные внутри строки
T_SWITCH switch switch
T_THROW throw Исключения
T_TRAIT trait Трейты
T_TRAIT_C __TRAIT__ __TRAIT__
T_TRY try Исключения
T_UNSET unset() unset()
T_UNSET_CAST (unset) приведение типов
T_USE use пространства имён
T_VAR var классы и объекты
T_VARIABLE $foo переменные
T_WHILE while while, do..while
T_WHITESPACE t rn  
T_XOR_EQUAL ^= операторы
присваивания
T_YIELD yield генераторы
T_YIELD_FROM yield from generators

Смотрите также token_name().

nathan at unfinitydesign dot com

14 years ago


T_ENCAPSED_AND_WHITESPACE is whitespace which intersects a group of tokens. For example, an "unexpected T_ENCAPSED_AND_WHITESPACE" error is produced by the following code:

<?php

$main_output_world
= 'snakes!';

echo(
'There are' 10 $main_output_world);

?>



Note the missing concatenation operator between the two strings leads to the whitespace error that is so named above. The concatenation operator instructs PHP to ignore the whitespace between the two code tokens (the so named "encapsed" data"), rather than parse it as a token itself.

The correct code would be:

<?php

$main_output_world
= 'snakes!';

echo(
'There are' . 10 . $main_output_world);

?>



Note the addition of the concatenation operator between each token.


fgm at osinet dot fr

14 years ago


T_ENCAPSED_AND_WHITESPACED is returned when parsing strings with evaluated content, like "some $value" or this example from the Strings reference page:

<?php
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some
{$foo->bar[1]}.
This should print a capital 'A': x41
EOT;
?>

This last example is tokenized as:
T_ECHO
  echo
T_WHITESPACE
  %20 (a space character)
T_START_HEREDOC
  <<
T_ENCAPSED_AND_WHITESPACE
  My name is "
T_VARIABLE
  $name
T_ENCAPSED_AND_WHITESPACE   
  ". I am printing some
T_VARIABLE   
  $foo
T_OBJECT_OPERATOR   
  ->
T_STRING   
  foo
T_ENCAPSED_AND_WHITESPACE   
  . Now, I am printing some
T_CURLY_OPEN   
  {
T_VARIABLE   
  $foo
T_OBJECT_OPERATOR   
  ->
T_STRING   
  bar
(terminal)
  [
T_LNUMBER   
  1
(terminal)
  ]
(terminal)
  }
T_ENCAPSED_AND_WHITESPACE   
  . This should print a capital 'A': x41
T_END_HEREDOC
  EOT
(terminal)
  ;


Содержание

  1. Ошибка: Syntax error: unexpected token 17 февраля 2016 · HTML & CSS, JavaScript и Блог · 2 мин чтения
  2. Чаще всего
  3. Простой пример
  4. Возможное решение (первое)
  5. Возможное решение (второе)
  6. Так же ошибка возникает бывает…
  7. Личный опыт
  8. Послесловие
  9. Uncaught SyntaxError: Unexpected token — что это означает?
  10. Что делать с ошибкой Uncaught SyntaxError: Unexpected token
  11. parsing — PHP parse/syntax errors; and how to solve them
  12. Answer
  13. Solution:
  14. What are the syntax errors?
  15. Most important tips
  16. How to interpret parser errors
  17. Solving syntax errors
  18. White screen of death
  19. Answer
  20. Solution:
  21. Using a syntax-checking IDE means:
  22. Answer
  23. Solution:
  24. Unexpected <-code-11>-code-1>
  25. Unexpected <-code-21>closing square bracket
  26. Answer
  27. Solution:
  28. Unexpected An &quot<-code-13<-code-16>unexpected <-code-1<-code-16>&quot <-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 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: String concatenation 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 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 Missing expression operators Of course the same issue can arise in other expressions <-code-8<-code-16> <-code-14<-code-16>instance arithmetic operations: PHP can’t guess here <-code-19>the variable should have been added <-code-8<-code-16>subtracted or compared etc Lists Or functions parameter <-code-11<-code-16>s: 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: 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 Variables after ident<-code-19>iers 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 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: Solution: add the missing opening <-code-23>between statement and variable The curly < brace does not open the code block<-code-8<-code-16>without closing the <-code-19>expression with the ) closing parenthesis first Else does not expect conditions Solution: Remove the conditions from else or use Need brackets <-code-14<-code-16>closure Solution: Add brackets around $var Invisible whitespace As mentioned in the reference answer on &quot<-code-13<-code-16>Invisible stray Unicode&quot <-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: 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 See also Answer Solution: Unexpected T_CONSTANT_ENCAPSED_STRING Unexpected T_ENCAPSED_AND_WHITESPACE The unwieldy names T_CONSTANT_ENCAPSED_STRING and T_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. Incorrect variable interpolation And it comes up most frequently for incorrect PHP variable interpolation: 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: Nested arrays or deeper object references however require the complex curly string expression 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. 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: While it’s obvious to you and me, PHP just can’t guess that the string was meant to be appended there. 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. 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: While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently. Missing opening quote Here the ‘, ‘ would become a string literal after a bareword, when obviously login was meant to be a string parameter. Array lists If you miss a , comma in an array creation block, the parser will see two consecutive strings: 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. Function parameter lists Runaway strings A common variation are quite simply forgotten string terminators: Here PHP complains about two string literals directly following each other. But the real cause is the unclosed previous string of course. HEREDOC indentation Prior PHP 7.3, the heredoc string end delimiter can’t be prefixed with spaces: Solution: upgrade PHP or find a better hoster. See also 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. 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: 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: 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 Unclosed strings It<-code-6>s not just literal s which the parser may protest then. Another frequent variation is an for unquoted literal HTML. 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: 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. 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: 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. 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: Share solution ↓ Additional Information: 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 (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 (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. Источник
  29. Missing semicolon
  30. String concatenation
  31. Missing expression operators
  32. Lists
  33. Class declarations
  34. Variables after ident<-code-19>iers
  35. Missing parentheses after language constructs
  36. Else does not expect conditions
  37. Need brackets <-code-14<-code-16>closure
  38. Invisible whitespace
  39. See also
  40. Answer
  41. Solution:
  42. Unexpected T_CONSTANT_ENCAPSED_STRING Unexpected T_ENCAPSED_AND_WHITESPACE
  43. Incorrect variable interpolation
  44. Missing concatenation
  45. Confusing string quote enclosures
  46. Missing opening quote
  47. Array lists
  48. Function parameter lists
  49. Runaway strings
  50. HEREDOC indentation
  51. Answer
  52. Solution:
  53. Unexpected
  54. Misquoted strings
  55. Unclosed strings
  56. Non-programming string quotes
  57. The missing semicolon <-code-29>again
  58. Short open tags and <-code-23>headers in PHP scripts
  59. Share solution ↓
  60. Additional Information:
  61. Didn’t find the answer?
  62. Similar questions
  63. Write quick answer
  64. About the technologies asked in this question
  65. Laravel
  66. JavaScript
  67. MySQL
  68. Welcome to programmierfrage.com
  69. Get answers to specific questions
  70. Help Others Solve Their Issues

Ошибка: Syntax error: unexpected token 17 февраля 2016 · HTML & CSS, JavaScript и Блог · 2 мин чтения

В этой записи я хочу рассказать про данную ошибку и из-за чего она может проявляться.

Чаще всего

Давайте представим обычный AJAX запрос. В целом, я думаю, что всем понятно что это из-за себя представляет. Вы указываете путь к файлу обработчика данный и пишите в каком формате вы хотите получить данные обратно. Для более точного разъяснения проблемы, я написал небольшой пример AJAX запроса, который указан ниже.

Простой пример

В примере ниже, я использую POST запрос, к файлу по пути ajax/ajax-form.php . Ответ я ожидаю в формате JSON. Я отправляю данные в виде, , при удачном получении данных, сработает success , а при ошибке error . При success или error ответ будет показан в консоли браузера.

Сама частая причина возникновения ошибки Syntax error: unexpected token — это когда вы делаете AJAX запрос к обработчику (например — ajax/ajax-form.php из примера выше), а его нет по указанному пути ( ajax/имя-файла.php ) и в итоге возвращается 404 ошибка (не найдено).

404 ошибка, вернет вам (HTML формат), а скриптом ожидается JSON dataType: ‘json’ и поэтому возникает такая ошибка.

Возможное решение (первое)

Проверьте правильно ли прописан путь и/или имя файла обработчика.

Возможное решение (второе)

Возможно вы не правильно возвращаете ответ со стороны обработчика, например вы прописали JSON, а возвращается в HTML или наоборот.

Так же ошибка возникает бывает…

Если вы 100% уверены в том, что ошибка не происходит из-за того, что вы неправильно прописали путь для обработчика — то второй причиной возникновения ошибки может быть синтаксическая ошибка.

Например если вы пропустили «;» или вместо type: «POST» указали type «POST» . Постарайтесь внимательно пройтись по коду и если ошибок все равно нет, то оставьте его на некоторое время и чуть позже вернитесь к нему.

Личный опыт

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

И да, после вторичного просмотра кода я вношу массу поправок и исправляю ошибки (если они были).

Послесловие

На этом все. Если у вас есть какой-либо вопрос по данной теме, то пожалуйста напишите его ниже под этой записью.

Источник

Uncaught SyntaxError: Unexpected token — что это означает?

Самая популярная ошибка у новичков.

Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:

for var i = 1; i // какой-то код
>

После запуска в браузере цикл падает с ошибкой:

❌ Uncaught SyntaxError: Unexpected token ‘var’

Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.

Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.

Что делать с ошибкой Uncaught SyntaxError: Unexpected token

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

Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:

По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:

    Проверьте, так ли пишется эта конструкция на вашем языке. В случае JavaScript тут не хватает скобок. Должно быть for (var i=1; i ВКонтактеTelegramТвиттер

Источник

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

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:

Closely related references:

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.

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.

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.

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 a d<-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.

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&nbsp<-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

&lt<-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.

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

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, say test.php :

Then invoke the failing code by accessing this wrapper script.

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):

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> .

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

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.

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:

Confusing <-code-11>-code-1> with opening curly braces <-code-11>or parentheses <-code-12>is a common oversight.

Or trying to dereference <-code-16>ants <-code-12>before PHP 5.6 <-code-23>as arrays:

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:

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:

Or trying to end an array where there isn’t one:

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

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.

Answer

Solution:

Unexpected

An &quot<-code-13<-code-16>unexpected <-code-1<-code-16>&quot <-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

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:

String concatenation

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

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

Missing expression operators

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

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

Lists

Or functions parameter <-code-11<-code-16>s:

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:

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

Variables after ident<-code-19>iers

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

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:

Solution: add the missing opening <-code-23>between statement and variable

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

Else does not expect conditions

Solution: Remove the conditions from else or use

Need brackets <-code-14<-code-16>closure

Solution: Add brackets around $var

Invisible whitespace

As mentioned in the reference answer on &quot<-code-13<-code-16>Invisible stray Unicode&quot <-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:

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

See also

Answer

Solution:

Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE

The unwieldy names T_CONSTANT_ENCAPSED_STRING and T_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.

Incorrect variable interpolation

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

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:

Nested arrays or deeper object references however require the complex curly string expression 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.

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:

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

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.

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:

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

Missing opening quote

Here the ‘, ‘ would become a string literal after a bareword, when obviously login was meant to be a string parameter.

Array lists

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

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.

Function parameter lists

Runaway strings

A common variation are quite simply forgotten string terminators:

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

HEREDOC indentation

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

Solution: upgrade PHP or find a better hoster.

See also

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.

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:

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:

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

Unclosed strings

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

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:

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.

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:

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.

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:

Additional Information:

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 (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 (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.

Источник

В этой записи я хочу рассказать про данную ошибку и из-за чего она может проявляться.

Чаще всего

Давайте представим обычный AJAX запрос. В целом, я думаю, что всем понятно что это из-за себя представляет. Вы указываете путь к файлу обработчика данный и пишите в каком формате вы хотите получить данные обратно. Для более точного разъяснения проблемы, я написал небольшой пример AJAX запроса, который указан ниже.

Простой пример

В примере ниже, я использую POST запрос, к файлу по пути ajax/ajax-form.php. Ответ я ожидаю в формате JSON. Я отправляю данные в виде, {key:1,title:'nice title'}, при удачном получении данных, сработает success, а при ошибке error. При success или error ответ будет показан в консоли браузера.

$.ajax({
            type : 'POST',
            url : 'ajax/ajax-form.php',
            dataType : 'json',
            data: {key:1,title:'nice title'},
            success : function(data){
                 console.log('data');
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {    
                 console.log("XMLHttpRequest " + XMLHttpRequest[0]);alert(" errorThrown: " + errorThrown);
                 console.log( " textstatus : " + textStatus);    
            }
});

Сама частая причина возникновения ошибки Syntax error: unexpected token < — это когда вы делаете AJAX запрос к обработчику (например — ajax/ajax-form.php из примера выше), а его нет по указанному пути (ajax/имя-файла.php) и в итоге возвращается 404 ошибка (не найдено).

404 ошибка, вернет вам  <html></html> (HTML формат), а скриптом ожидается JSON dataType: 'json' и поэтому возникает такая ошибка.

Возможное решение (первое)

Проверьте правильно ли прописан путь и/или имя файла обработчика.

Возможное решение (второе)

Возможно вы не правильно возвращаете ответ со стороны обработчика, например вы прописали JSON, а возвращается в HTML или наоборот.

Так же ошибка возникает бывает…

Если вы 100% уверены в том, что ошибка не происходит из-за того, что вы неправильно прописали путь для обработчика — то второй причиной возникновения ошибки может быть синтаксическая ошибка.

Например если вы пропустили «;» или вместо type: "POST" указали type "POST". Постарайтесь внимательно пройтись по коду и если ошибок все равно нет, то оставьте его на некоторое время и чуть позже вернитесь к нему.

Личный опыт

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

И да, после вторичного просмотра кода я вношу массу поправок и исправляю ошибки (если они были).

Послесловие

На этом все. Если у вас есть какой-либо вопрос по данной теме, то пожалуйста напишите его ниже под этой записью.

Об авторе

0 / 0 / 0

Регистрация: 10.03.2014

Сообщений: 15

1

07.04.2014, 20:16. Показов 7516. Ответов 13


Здравствуйте, возникла следующая проблема, в cms, при загрузке файла вылетает следующая ошибка: SyntaxError: Unexpected token <. Что это может быть и как ее решить?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



249 / 249 / 98

Регистрация: 26.07.2010

Сообщений: 1,685

08.04.2014, 11:57

2

ищите строку где эта ошибка, скиньте сюда код

Добавлено через 1 минуту
вам пишет что символ < там не нужен



0



Petbka123

0 / 0 / 0

Регистрация: 10.03.2014

Сообщений: 15

08.04.2014, 13:07

 [ТС]

3

V@D!k,
file.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
<?php
require_once "initd.php";
//---------------------------------------------------------------------------------------------------------------
//Подключение дополнительных модулей
//---------------------------------------------------------------------------------------------------------------
require_once "extra/readValue.php";
require_once "extra/selectStorage.php";
require_once "extra/convertFileName.php";
//----------------------------------------------------------------------------------------------------------------
//Если пользователю разрешено редактировать книги
//---------------------------------------------------------------------------------------------------------------
if ($objOptions -> getOption("BookEdit") == "yes") {
    //Если переданные данные имеют цифровой формат
    if (readValueNum("bookID")) {
        //Если пользователю разрешено редактировать все книги
        if ($objOptions -> getOption("BookEditAll") == "yes") {
            //Проверяем наличие книги в БД
            $data = $objDB -> select("SELECT * FROM booksList WHERE ID = " . readValue("bookID") . " AND approved LIKE 'no';");
        }
        //Если пользователю запрещено редактировать все книги
        else {
            //Проверяем наличие книги в БД и что книга принадлежит пользователю
            $data = $objDB -> select("SELECT * FROM booksList WHERE ID = " . readValue("bookID") . " AND userID = " . $objSession -> getUserID() . " AND approved LIKE 'no';");
        }
        //Если проверки книги прошли успешно
        if ($data) {
            switch(readValue("action")) {
                //-----------------------------------------------------------------------------------------------------------
                //Если событие "Привязать файл к книге"
                //-----------------------------------------------------------------------------------------------------------
                case "addToBook" :
                    //Получаем данные
                    $fileName = readValue("localFileName");
                    $storage = selectStorage();
 
                    if (empty($fileName)) {
                        $fileName = readValue("remoteFileName");
                        $storage = 0;
                    }
                    //-------------------------------------------------------------------------------------------------------
                    //Создаем массив с информацией об файле
                    //-------------------------------------------------------------------------------------------------------
                    $arrFile = Array();
                    $arrFile['pages'] = readValueNum('pages');
                    $arrFile['fileFormat'] = readValue('fileFormat');
                    $arrFile['fileName'] = convertFileName($fileName);
                    $arrFile['bookID'] = readValueNum("bookID");
                    //-------------------------------------------------------------------------------------------------------
                    //Если формат принятых данных верен
                    //-------------------------------------------------------------------------------------------------------
                    if ($arrFile['pages'] && $arrFile['fileFormat'] && $arrFile['fileName'] && $arrFile['bookID']) {
                        $data = $objDB -> select("SELECT COUNT(ID) FROM booksFileList WHERE bookID = " . $arrFile["bookID"] . ";");
                        //Если кол-во файлов привязанык к книге не превышает лимит
                        if (@$data[0]['COUNT(ID)'] < MAX_FILE_COUNT) {
                            //-----------------------------------------------------------------------------------------------
                            //Если файл локальный
                            //-----------------------------------------------------------------------------------------------
                            if ($storage > 0) {
                                //Если файл присутсвует в папке пользователя
                                if (is_file(USER_STORAGE . $objSession -> getUserPath() . "/" . $fileName)) {
                                    //Если в папке хранения не существует файла с таким же именем
                                    if (!is_file(FILES_STORAGE . $storage . "/" . $fileName)) {
                                        //Если удалось скопировать файл из папки пользователя в папку хранения
                                        //echo(USER_STORAGE . $objSession -> getUserPath() . "/" . $fileName . "". FILES_STORAGE . $storage . "/" . $arrFile['fileName']);
                                        if (copy(USER_STORAGE . $objSession -> getUserPath() . "/" . $fileName, FILES_STORAGE . $storage . "/" . $arrFile['fileName'])) {
                                            //Удаляем файл из папки пользователя
                                            unlink(USER_STORAGE . $objSession -> getUserPath() . "/" . $fileName);
                                            //Получаем дополнительную информацию об файле
                                            $arrFile['fileSize'] = filesize(FILES_STORAGE . $storage . "/" . $arrFile['fileName']);
                                            $arrFile['storage'] = $storage;
                                            //Если удалось добавить запись в базу
                                            if ($objDB -> insert("booksFileList", $arrFile)) {
                                                //Выводим об этом сообщение
                                                $objTheme -> success("{LANG_ADD_TRUE}");
                                            }
                                            //Если не удалось добавить запись в базу
                                            else {
                                                //Выводим сообщение об этом
                                                $objTheme -> error("{LANG_ADD_FALSE}");
                                            }
                                        }
                                        //Если не удалось скопировать файл из папки пользователя в папку хранения
                                        else {
                                            //Выводим сообщение об этом
                                            $objTheme -> error("{LANG_FILE_FALSE}");
                                        }
                                    }
                                    //Если в папке хранения существует файл с таким же именем
                                    else {
                                        //Выводим сообщение об этом
                                        $objSession -> warning("{LANG_FILE_SAME_NAME}");
                                    }
                                }
                                //Если файл отсутсвует в папке пользователя
                                else {
                                    //Выводим сообщение об этом
                                    $objTheme -> error("{LANG_FILE_NO_PRESENT}");
                                }
                            }
                            //-----------------------------------------------------------------------------------------------
                            //Если файл удаленный(добавляется только ссылка в базу)
                            //-----------------------------------------------------------------------------------------------
                            else {
                                //Получаем дополнительную информацию об файле
                                $arrFile['fileSize'] = readValueNum("fileSize");
                                //Если удалось добавить запись в базу
                                if ($objDB -> insert("booksFileList", $arrFile)) {
                                    //Выводим об этом сообщение
                                    $objTheme -> success("{LANG_ADD_TRUE}");
                                }
                                //Если не удалось добавить запись в базу
                                else {
                                    //Выводим сообщение об этом
                                    $objTheme -> error("{LANG_ADD_FALSE}");
                                }
                            }
                        }
                        //Если кол-во файлов привязанык к книге превышает лимит
                        else {
                            //Выводим сообщение об этом
                            $objTheme -> error("{LANG_LIMIT_REACHED}");
                        }
                    }
                    //-------------------------------------------------------------------------------------------------------
                    //Если формат принятых данных не верен
                    //-------------------------------------------------------------------------------------------------------
                    else {
                        //Выводим сообщение об этом
                        $objTheme -> warning("{LANG_ERROR_READ_FORM}");
                    }
                    break;
                //-----------------------------------------------------------------------------------------------------------
                //Если событие "Удалить привязку файла к книге"
                //-----------------------------------------------------------------------------------------------------------
                case "delFromBook" :
                    //Если формат принятых данных верен
                    if (readValueNum("bookID") && readValueNum("fileID")) {
                        //Получаем информацию об записи
                        $data = $objDB -> select("SELECT * FROM booksFileList WHERE bookID = " . readValue("bookID") . " AND ID = " . readValue("fileID") . ";");
                        //Если запись присутсвует в базе
                        if ($data) {
                            //Получаем массив с данными
                            $data = $data[0];
                            //Если файл локальный
                            if ($data['storage'] > 0) {
                                //Если удалось удалить файл из папки хранения либо идет принудительное удаление
                                if (@unlink(FILES_STORAGE . $data['storage'] . "/" . $data['fileName']) || readValue("forceDel") == "yes") {
                                    //Если удалось удалить запись из базы
                                    if ($objDB -> delete("booksFileList", Array("bookID" => readValue("bookID"), "ID" => readValue("fileID")))) {
                                        //Выводим сообщение об этом
                                        $objTheme -> success("{LANG_DEL_TRUE}");
                                    }
                                    //Если не удалось удалить запись из базы
                                    else {
                                        //Выводим сообщение об этом
                                        $objTheme -> error("{LANG_DEL_FALSE}");
                                    }
                                }
                                //Если не удалось удалить файл из папки хранения
                                else {
                                    //Выводим сообщение об этом
                                    $objTheme -> error("{LANG_FILE_UNLINK_ERROR}");
                                }
                            }
                            //Если файл удаленный
                            else {
                                //Если удалось удалить запись из базы
                                if ($objDB -> delete("booksFileList", Array("bookID" => readValue("bookID"), "ID" => readValue("fileID")))) {
                                    //Выводим сообщение об этом
                                    $objTheme -> success("{LANG_DEL_TRUE}");
                                }
                                //Если не удалось удалить запись из базы
                                else {
                                    //Выводим сообщение об этом
                                    $objTheme -> error("{LANG_DEL_FALSE}");
                                }
                            }
                        }
                        //Если запись отсутствует в базе
                        else {
                            //Выводим сообщение об этом
                            $objTheme -> warning("{LANG_LINE_EMPTY}");
                        }
                    }
                    //Если формат принятых данных не верен
                    else {
                        //Выводим сообщение об этом
                        $objTheme -> warning("{LANG_ERROR_READ_FORM}");
                    }
                    break;
                //-----------------------------------------------------------------------------------------------------------
                //Если событие не определенно
                //-----------------------------------------------------------------------------------------------------------
                default :
                    //Выводим сообщение об этом
                    $objTheme -> warning("{LANG_ERROR_READ_FORM}");
                    break;
            }
        }
        //Если проверки книг прошли не успешно
        else {
            //Выводим сообщение об этом
            $objTheme -> warning("{LANG_HAVE_NO_ELEMENT}");
        }
    }
    //Если идентефикатор книги не цифровой
    else {
        //Выводим сообщение об этом
        $objTheme -> warning("{LANG_ERROR_READ_FORM}");
    }
}
//----------------------------------------------------------------------------------------------------------------
//Если пользователю запрещено редактировать книги
//----------------------------------------------------------------------------------------------------------------
else {
    //Выводим сообщение об этом
    $objTheme -> warning("{LANG_EDIT_PROHIBITED}");
}
//---------------------------------------------------------------------------------------------------------------
//Вывод шаблона в браузер и очистка памяти
//---------------------------------------------------------------------------------------------------------------
require_once "end.php";
?>

filemanager.php

PHP
1
2
3
4
5
6
7
8
9
10
11
<?php
//Первоначальная инициализация
//---------------------------------------------------------------------------------------------------------------
require_once "initd.php";
//Вывод формы загрузки в браузер
$objTheme -> define(Array("MAIN_CONTENT" => "uploadForm.tpl"));
//---------------------------------------------------------------------------------------------------------------
//Вывод шаблона в браузер и очистка памяти
//---------------------------------------------------------------------------------------------------------------
require_once "end.php";
?>



0



249 / 249 / 98

Регистрация: 26.07.2010

Сообщений: 1,685

08.04.2014, 13:11

4

в какой строке ошибку пишет?



0



0 / 0 / 0

Регистрация: 10.03.2014

Сообщений: 15

08.04.2014, 13:20

 [ТС]

5

V@D!k, в том то и проблема что я не знаю где именно эта ошибка, cms не моя. Могу скинуть модуль в котором она выпадает. Вот скрин ошибки: []http://i33.***********/big/2014/0408/01/540bb49d0691b4bd727032f29c43af01.png[/]

Добавлено через 16 секунд



0



Vovan-VE

08.04.2014, 15:13



0



sMockingbird

284 / 283 / 73

Регистрация: 06.05.2013

Сообщений: 1,613

08.04.2014, 15:21

7

PHP
1
                      if (@$data[0]['COUNT(ID)'] < MAX_FILE_COUNT)

54 строка. Символ в начале не лишний?

А вообще, если ошибка выдаётся, то выдаётся и строка, на которой ошибка



0



13207 / 6595 / 1041

Регистрация: 10.01.2008

Сообщений: 15,069

08.04.2014, 15:28

8

Цитата
Сообщение от Petbka123
Посмотреть сообщение

SyntaxError: Unexpected token

Вообще, PHP дословно вот так никогда не говорит.



0



0 / 0 / 0

Регистрация: 10.03.2014

Сообщений: 15

08.04.2014, 16:04

 [ТС]

9

Vovan-VE,

Миниатюры

Ошибка SyntaxError: Unexpected token <
 



0



0 / 0 / 0

Регистрация: 10.03.2014

Сообщений: 15

08.04.2014, 16:05

 [ТС]

10

sMockingbird, кроме SyntaxError: Unexpected token <, больше ничего не выдает



0



284 / 283 / 73

Регистрация: 06.05.2013

Сообщений: 1,613

08.04.2014, 16:07

11

Petbka123, да я вижу уже)
может там размер блока с ошибкой ограничен, может остальная часть ошибки скрыта получилась? посмотрите код



0



0 / 0 / 0

Регистрация: 10.03.2014

Сообщений: 15

08.04.2014, 19:55

 [ТС]

12

sMockingbird, да нет, тоже самое выдает(



0



0 / 0 / 0

Регистрация: 01.02.2013

Сообщений: 21

09.03.2016, 09:28

13

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



0



Эксперт PHP

4839 / 3852 / 1598

Регистрация: 24.04.2014

Сообщений: 11,300

09.03.2016, 12:16

14

Цитата
Сообщение от AssVolt
Посмотреть сообщение

Движок тот же, ошибка такая же, ничего не помогает.

Это ошибка не php, а js. Как правило происходит при получении неверных данных в ответе ajax запроса, или какой-то скрипт не подгрузился



0



Technical Problem Cluster First Answered On
August 7, 2021

Popularity
10/10

Helpfulness
1/10

Contents

Code Examples

  • syntax error, unexpected token «}», expecting «,» or «;» php
  • syntax error, unexpected token «}», expecting «,» or «;» php
  • syntax error, unexpected token «}», expecting «,» or «;» php
  • syntax error, unexpected token «}», expecting «,» or «;» php
  • syntax error, unexpected token «}», expecting «,» or «;» php
  • syntax error, unexpected token «}», expecting «,» or «;» php
  • syntax error, unexpected token «}», expecting «,» or «;» php
  • syntax error, unexpected token «}», expecting «,» or «;» php
  • Related Problems

  • syntax error unexpected token expecting ) php
  • leantime php parse error: syntax error, unexpected ‘=’, expecting ‘)’
  • syntax error: word unexpected (expecting «do»)
  • unexpected ‘+’, expecting $end; input:
  • in finder.php line 588: syntax error, unexpected token «)»
  • php parse error: syntax error, unexpected ‘<‘, expecting end of file
  • syntax error, unexpected identifier «__data», expecting «)»
  • syntax error unexpected token expecting ) laravel
  • «syntax error, unexpected end of file, expecting function (t_function) or const (t_const)»
  • syntax error, unexpected ‘|’, expecting variable (t_variable) in /vendor/psr/log/src/loggerinterface.php
  • php parse error: syntax error, unexpected ‘|’, expecting variable (t_variable) in /usr/share/php/composer/io/baseio.php on line 163
  • php parse error: syntax error, unexpected t_string on line 1
  • TPC Matrix View Full Screen

    syntax error, unexpected token «}», expecting «,» or «;» php


    Popularity

    8/10 Helpfulness
    1/10
    Language
    php

    ximoxfedox

    Contributed on Aug 07 2021

    ximoxfedox

    12 Answers  Avg Quality 2/10


    syntax error, unexpected token «}», expecting «,» or «;» php


    Popularity

    7/10 Helpfulness
    1/10
    Language
    php

    ximoxfedox

    Contributed on Aug 07 2021

    ximoxfedox

    12 Answers  Avg Quality 2/10


    syntax error, unexpected token «}», expecting «,» or «;» php


    Popularity

    7/10 Helpfulness
    1/10
    Language
    php

    ximoxfedox

    Contributed on Aug 07 2021

    ximoxfedox

    12 Answers  Avg Quality 2/10


    syntax error, unexpected token «}», expecting «,» or «;» php


    Popularity

    7/10 Helpfulness
    1/10
    Language
    php

    ximoxfedox

    Contributed on Aug 07 2021

    ximoxfedox

    12 Answers  Avg Quality 2/10


    syntax error, unexpected token «}», expecting «,» or «;» php


    Popularity

    7/10 Helpfulness
    1/10
    Language
    php

    ximoxfedox

    Contributed on Aug 07 2021

    ximoxfedox

    12 Answers  Avg Quality 2/10


    syntax error, unexpected token «}», expecting «,» or «;» php


    Popularity

    7/10 Helpfulness
    1/10
    Language
    php

    ximoxfedox

    Contributed on Aug 07 2021

    ximoxfedox

    12 Answers  Avg Quality 2/10


    syntax error, unexpected token «}», expecting «,» or «;» php


    Popularity

    8/10 Helpfulness
    1/10
    Language
    php

    ximoxfedox

    Contributed on Aug 07 2021

    ximoxfedox

    12 Answers  Avg Quality 2/10


    syntax error, unexpected token «}», expecting «,» or «;» php


    Popularity

    8/10 Helpfulness
    1/10
    Language
    php

    ximoxfedox

    Contributed on Aug 07 2021

    ximoxfedox

    12 Answers  Avg Quality 2/10


    Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:

    for var i = 1; i < 10; i++ {
    <span style="font-weight: 400;">  // какой-то код</span>
    <span style="font-weight: 400;">}</span>

    После запуска в браузере цикл падает с ошибкой:

    ❌ Uncaught SyntaxError: Unexpected token ‘var’

    Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.

    Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.

    Что делать с ошибкой Uncaught SyntaxError: Unexpected token

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

    Интерпретатор обязательно показывает номер строки, где произошла ошибка Uncaught SyntaxError: Unexpected token

    Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:

    Строка с ошибкой Uncaught SyntaxError: Unexpected token

    По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:

    • Проверьте, так ли пишется эта конструкция на вашем языке. В случае JavaScript тут не хватает скобок. Должно быть for (var i=1; i<10; i++) {}
    • Посмотрите на предыдущие команды. Если там не закрыта скобка или кавычка, интерпретатор может ругаться на код немного позднее.

    Попробуйте сами

    Каждый из этих фрагментов кода даст ошибку Uncaught SyntaxError: Unexpected token. Попробуйте это исправить.

    if (a==b) then  {}
    function nearby(number, today, oneday, threeday) {
      if (user_today == today + 1 || user_today == today - 1)
        (user_oneday == oneday + 1 || user_oneday == oneday - 1)
          && (user_threeday == threeday + 1 || user_threeday == threeday - 1)
      return true
      
      else
         return false
    }
    var a = prompt('Зимой и летом одним цветом');
    if (a == 'ель'); {
      alert("верно");
    } else {
      alert("неверно");
    }
    alert(end);

    Понравилась статья? Поделить с друзьями:
  • Syntax error unexpected t logical or
  • Syntax error insert variabledeclarators to complete localvariabledeclaration
  • Syntax error unexpected t boolean or
  • Syntax error unexpected symbol expecting register
  • Syntax error unexpected string at end of statement