На перво странице сайта пишет: Parse error: syntax error, unexpected T_ELSE in /home/bitrix/www/index.php on line 25
Помогите понять где закралась оибка и как её исправить?
Содержимое файла <?
require($_SERVER[«DOCUMENT_ROOT»].»/bitrix/header.php»);
if(!$_REQUEST[«ORDER_ID»]){
$APPLICATION->SetTitle(«Ваша корзина»);
}else{
$APPLICATION->SetTitle(«Заказ оформлен»);
}
?>
<?
if($USER->IsAuthorized()){
if(!isset($_GET[‘ORDER_ID’])){
?>
<div class=»area-step2 container-fluid»>
<div class=»wrapper»>
<div class=»row»>
<div class=»col-md-8″>
<h2>Оформление заказа <small>шаг 2 из 3</small></h2>
<?}?>
<?$APPLICATION->IncludeComponent(«bitrix:sale.order.ajax», «order», Array(
«PAY_FROM_ACCOUNT» => «N», // Позволять оплачивать с внутреннего счета
«ONLY_FULL_PAY_FROM_ACCOUNT» => «N», // Позволять оплачивать с внутреннего счета только в полном объеме
«COUNT_DELIVERY_TAX» => «N», // Рассчитывать налог для доставки
«ALLOW_AUTO_REGISTER» => «Y», // Оформлять заказ с автоматической регистрацией пользователя
«SEND_NEW_USER_NOTIFY» => «N», // Отправлять пользователю письмо, что он зарегистрирован на сайте
«DELIVERY_NO_AJAX» => «N», // Рассчитывать стоимость доставки сразу
«DELIVERY_NO_SESSION» => «N», // Проверять сессию при оформлении заказа
«TEMPLATE_LOCATION» => «.default», // Шаблон местоположения
«DELIVERY_TO_PAYSYSTEM» => «d2p», // Последовательность оформления
«USE_PREPAYMENT» => «N», // Использовать предавторизацию для оформления заказа (PayPal Express Checkout)
«PROP_1» => «», // Не показывать свойства для типа плательщика «Физическое лицо» (s1)
«ALLOW_NEW_PROFILE» => «Y», // Разрешить множество профилей покупателей
«SHOW_PAYMENT_SERVICES_NAMES» => «Y», // Отображать названия платежных систем
«SHOW_STORES_IMAGES» => «N», // Показывать изображения складов в окне выбора пункта выдачи
«PATH_TO_BASKET» => «/order/», // Страница корзины
«PATH_TO_PERSONAL» => «index.php», // Страница персонального раздела
«PATH_TO_PAYMENT» => «payment.php», // Страница подключения платежной системы
«PATH_TO_AUTH» => «/auth/», // Страница авторизации
«SET_TITLE» => «Y», // Устанавливать заголовок страницы
«DISABLE_BASKET_REDIRECT» => «Y», // Оставаться на странице, если корзина пуста
«PRODUCT_COLUMNS» => «», // Дополнительные колонки таблицы товаров заказа
),
false
);?>
<?
if($USER->IsAuthorized()){
if(!isset($_GET[‘ORDER_ID’])){
?>
<?$APPLICATION->IncludeComponent(
«bitrix:sale.basket.basket»,
«»,
array(
«COLUMNS_LIST» => array(
0 => «NAME»,
1 => «PROPS»,
2 => «DELETE»,
3 => «PRICE»,
4 => «QUANTITY»,
5 => «SUM»,
),
«PATH_TO_ORDER» => «/order/»,
«HIDE_COUPON» => «N»,
«PRICE_VAT_SHOW_VALUE» => «N»,
«USE_PREPAYMENT» => «N»,
«QUANTITY_FLOAT» => «N»,
«SET_TITLE» => «N»,
«ACTION_VARIABLE» => «action»
),
false
);?>
<?
}}
?>
<?if(!isset($_GET[‘ORDER_ID’])){?>
</div>
<div class=»col-md-4 «>
<?$APPLICATION->ShowViewContent(‘cart’);?>
<?$APPLICATION->IncludeComponent(«bitrix:news.list», «cart_faq», Array(
«ACTIVE_DATE_FORMAT» => «d.m.Y», // Формат показа даты
«ADD_SECTIONS_CHAIN» => «N», // Включать раздел в цепочку навигации
«AJAX_MODE» => «N», // Включить режим AJAX
«AJAX_OPTION_ADDITIONAL» => «», // Дополнительный идентификатор
«AJAX_OPTION_HISTORY» => «N», // Включить эмуляцию навигации браузера
«AJAX_OPTION_JUMP» => «N», // Включить прокрутку к началу компонента
«AJAX_OPTION_STYLE» => «Y», // Включить подгрузку стилей
«CACHE_FILTER» => «N», // Кешировать при установленном фильтре
«CACHE_GROUPS» => «Y», // Учитывать права доступа
«CACHE_TIME» => «36000000», // Время кеширования (сек.)
«CACHE_TYPE» => «A», // Тип кеширования
«CHECK_DATES» => «Y», // Показывать только активные на данный момент элементы
«DETAIL_URL» => «», // URL страницы детального просмотра (по умолчанию — из настроек инфоблока)
«DISPLAY_BOTTOM_PAGER» => «Y», // Выводить под списком
«DISPLAY_DATE» => «Y», // Выводить дату элемента
«DISPLAY_NAME» => «Y», // Выводить название элемента
«DISPLAY_PICTURE» => «Y», // Выводить изображение для анонса
«DISPLAY_PREVIEW_TEXT» => «Y», // Выводить текст анонса
«DISPLAY_TOP_PAGER» => «N», // Выводить над списком
«FIELD_CODE» => array( // Поля
0 => «»,
1 => «»,
),
«FILTER_NAME» => «», // Фильтр
«HIDE_LINK_WHEN_NO_DETAIL» => «N», // Скрывать ссылку, если нет детального описания
«IBLOCK_ID» => «1», // Код информационного блока
«IBLOCK_TYPE» => «news», // Тип информационного блока (используется только для проверки)
«INCLUDE_IBLOCK_INTO_CHAIN» => «N», // Включать инфоблок в цепочку навигации
«INCLUDE_SUBSECTIONS» => «Y», // Показывать элементы подразделов раздела
«MESSAGE_404» => «», // Сообщение для показа (по умолчанию из компонента)
«NEWS_COUNT» => «4», // Количество новостей на странице
«PAGER_BASE_LINK_ENABLE» => «N», // Включить обработку ссылок
«PAGER_DESC_NUMBERING» => «N», // Использовать обратную навигацию
«PAGER_DESC_NUMBERING_CACHE_TIME» => «36000», // Время кеширования страниц для обратной навигации
«PAGER_SHOW_ALL» => «N», // Показывать ссылку «Все»
«PAGER_SHOW_ALWAYS» => «N», // Выводить всегда
«PAGER_TEMPLATE» => «.default», // Шаблон постраничной навигации
«PAGER_TITLE» => «Новости», // Название категорий
«PARENT_SECTION» => «», // ID раздела
«PARENT_SECTION_CODE» => «», // Код раздела
«PREVIEW_TRUNCATE_LEN» => «», // Максимальная длина анонса для вывода (только для типа текст)
«PROPERTY_CODE» => array( // Свойства
0 => «»,
1 => «»,
),
«SET_BROWSER_TITLE» => «N», // Устанавливать заголовок окна браузера
«SET_LAST_MODIFIED» => «N», // Устанавливать в заголовках ответа время модификации страницы
«SET_META_DESCRIPTION» => «N», // Устанавливать описание страницы
«SET_META_KEYWORDS» => «Y», // Устанавливать ключевые слова страницы
«SET_STATUS_404» => «N», // Устанавливать статус 404
«SET_TITLE» => «N», // Устанавливать заголовок страницы
«SHOW_404» => «N», // Показ специальной страницы
«SORT_BY1» => «ACTIVE_FROM», // Поле для первой сортировки новостей
«SORT_BY2» => «SORT», // Поле для второй сортировки новостей
«SORT_ORDER1» => «DESC», // Направление для первой сортировки новостей
«SORT_ORDER2» => «ASC», // Направление для второй сортировки новостей
),
false
);?>
</div>
</div>
</div>
</div>
<?}?>
<?} else{
LocalRedirect(«/login/»);
}?>
<?require($_SERVER[«DOCUMENT_ROOT»].»/bitrix/footer.php»);?>
Пользователь 1005987 Заглянувший Сообщений: 31 |
Всем добрый вечер, прошу помочь разобраться с ошибкой Выделил 387 строку красным private function fetchHeaders(Server $server) return $this->normalizeHeaders($headers); |
Пользователь 90886 Гуру Сообщений: 2455 |
У вас старая версия PHP, 5.3.x, а нужно уже не менее 5.6, но лучше 7. |
Пользователь 1005987 Заглянувший Сообщений: 31 |
|
Пользователь 90886 Гуру Сообщений: 2455 |
А что выводит на этом же сайте phpinfo()? |
Пользователь 1005987 Заглянувший Сообщений: 31 |
|
Пользователь 90886 Гуру Сообщений: 2455 |
Ошибка из публичной части сайта, или при запуске скриптов из планировщика? |
Пользователь 1005987 Заглянувший Сообщений: 31 |
письма с крона вроде) |
Пользователь 90886 Гуру Сообщений: 2455 |
#8 0 26.03.2018 22:19:06 Через SSH выполните
Скорее всего это версия php другая подключается. Если покажет не 7.1.9, значит нужно определить какой путь к этой версии. Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем |
||
Пользователь 1005987 Заглянувший Сообщений: 31 |
|
Пользователь 1005987 Заглянувший Сообщений: 31 |
#10 0 26.03.2018 22:24:57 PHP 5.3.29 (cli) (built: Aug 19 2016 17:49:16) |
Пользователь 1005987 Заглянувший Сообщений: 31 |
#11 0 26.03.2018 22:27:14 но у них же есть фишка переключения версий php к каждому домену и там я указал 7.1, настройки в dbcon и settings сделал. два проекта работают на этом аккаунте |
Пользователь 90886 Гуру Сообщений: 2455 |
#12 0 26.03.2018 22:28:18 Да.
Если да, то в кроне нужно заменить
на
Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем |
||||||
Пользователь 139282 Посетитель Сообщений: 90 |
#13 0 26.03.2018 22:28:24 а в чем проблема $headers=array(); |
Пользователь 90886 Гуру Сообщений: 2455 |
#14 0 26.03.2018 22:29:12
Да, все верно. Но запуск из крона не знает ничего об этом, т.к. запуск из крона не привязывается к домену или сайту, т.е. настройки в этом случае общие — дефолтные. Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем |
||
Пользователь 90886 Гуру Сообщений: 2455 |
#15 0 26.03.2018 22:30:06
Предлагаете внести изменение в файл ядра? Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем |
||
Пользователь 1005987 Заглянувший Сообщений: 31 |
#16 0 26.03.2018 22:33:03
/opt/php71/bin/php -v PHP 7.1.9 (cli) (built: Sep 27 2017 19:45:21) ( NTS ) |
||||
Пользователь 90886 Гуру Сообщений: 2455 |
#17 0 26.03.2018 22:34:54
Значит, то что нужно Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем |
||
Пользователь 1005987 Заглянувший Сообщений: 31 |
#18 0 26.03.2018 22:38:42
а подскажите,конечно глупый вопрос, как для crona это сделать? |
||
Пользователь 90886 Гуру Сообщений: 2455 |
#19 0 26.03.2018 22:41:44 В панели таймвеба есть пункт Crontab — там эта команда должна быть задана. |
Пользователь 1005987 Заглянувший Сообщений: 31 |
#20 0 26.03.2018 22:45:10 Нашел в справочнике таймвеба )) Например, чтобы запустить скрипт script.php из-под версии PHP 7.0, необходимо указать: /opt/php70/bin/php /home/u/user/папка_сайта/public_html/script.php |
Пользователь 1005987 Заглянувший Сообщений: 31 |
#21 0 26.03.2018 22:49:19 Денис Сон,Спасибо за помощь |
Пользователь 90886 Гуру Сообщений: 2455 |
#22 0 26.03.2018 22:50:42 Пожалуйста, обращайтесь Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем |
Содержание
- Parse error Ошибка в шаблоне
- parsing — PHP parse/syntax errors; and how to solve them
- Answer
- Solution:
- What are the syntax errors?
- Most important tips
- How to interpret parser errors
- Solving syntax errors
- White screen of death
- Answer
- Solution:
- Using a syntax-checking IDE means:
- Answer
- Solution:
- Unexpected <-code-11>-code-1>
- Unexpected <-code-21>closing square bracket
- Answer
- Solution:
- Unexpected 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 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 "<-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: 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. Источник
- Missing semicolon
- String concatenation
- Missing expression operators
- Lists
- Class declarations
- Variables after ident<-code-19>iers
- Missing parentheses after language constructs
- Else does not expect conditions
- Need brackets <-code-14<-code-16>closure
- Invisible whitespace
- See also
- Answer
- Solution:
- Unexpected T_CONSTANT_ENCAPSED_STRING Unexpected T_ENCAPSED_AND_WHITESPACE
- Incorrect variable interpolation
- Missing concatenation
- Confusing string quote enclosures
- Missing opening quote
- Array lists
- Function parameter lists
- Runaway strings
- HEREDOC indentation
- Answer
- Solution:
- Unexpected
- Misquoted strings
- Unclosed strings
- Non-programming string quotes
- The missing semicolon <-code-29>again
- Short open tags and <-code-23>headers in PHP scripts
- Share solution ↓
- Additional Information:
- Didn’t find the answer?
- Similar questions
- Write quick answer
- About the technologies asked in this question
- Laravel
- JavaScript
- MySQL
- Welcome to programmierfrage.com
- Get answers to specific questions
- Help Others Solve Their Issues
Parse error Ошибка в шаблоне
Цитата |
---|
На битриксе стоит 2 сайта, на одном шаблон работает, на другом выдает такую ошибку: Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ‘)’ in /home/www/z70998/htdocs/request/index.php on line 36 Кто может помочь? |
У меня такая же ошибка
Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ‘)’ in /www/mfpaon01/www/htdocs/bitrix/templates/MFPA-ONLINE/components/bitrix/news/mfnews/detail.php on line 116
Что можно сделать?
Цитата |
---|
MiG-Z пишет: У меня такая же ошибка |
Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ‘)’ in /www/mfpaon01/www/htdocs/bitrix/templates/MFPA-ONLINE/components/bitrix/news/mfnews/detail.php on line 116
Что можно сделать?
Вот такая ошибка
Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING in z:home172.22.48.26wwworiflameconfig.php on line 2
скобки и апострофы вроде все проверил,все на месте. В чем проблема?? помогите! кидаю сам файл конфиг!
Цитата |
---|
/home/i/ingsystem/public_html/services/faq/index.php |
Господа, таже проблема, но псле преноса сайта на агаву.
Выдает:
Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘>’ in /home/polusdm1/public_html/bitrix/modules/main/include.php on line 1
Добрый день!
После обновлений не могу зайти в админку: Parse error: syntax error, unexpected ‘
Может кто нибудь помочь? Спасибо!
На перво странице сайта пишет: Parse error: syntax error, unexpected T_ELSE in /home/bitrix/www/index.php on line 25
Помогите понять где закралась оибка и как её исправить?
Содержимое файла SetTitle(«Ваша корзина»);
>else <
$APPLICATION->SetTitle(«Заказ оформлен»);
Источник
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:
- The code you can easily ident<-code-18>-code-11>y as correct,
- The parts you<-code-18>-code-8>re unsure about,
- 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 <-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.
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 "<-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
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 "<-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:
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.
Источник
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.
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. -
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 nestedif
conditions. -
Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.)
-
Add newlines between:
- The code you can easily identify as correct,
- The parts you’re unsure about,
- 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 plainif
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.
- Adopt a source code versioning system. You can always view a
-
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.
Konsole 0 / 0 / 0 Регистрация: 13.09.2011 Сообщений: 15 |
||||||||
1 |
||||||||
30.01.2012, 17:12. Показов 5282. Ответов 1 Метки нет (Все метки)
Здравствуйте, помогите пожалуйста, не понимаю в чем дело пишет ошибку
манипулировал только с этом таблицей, то есть копировал и вставлял только ее, она и раньше была… не подскажете что нужно вставить за тег? Добавлено через 20 минут
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
30.01.2012, 17:12 |
Ответы с готовыми решениями: Не могу разобраться с ошибкой PHP Parse error: syntax error, unexpected Ошибка Parse error: syntax error, unexpected T_STRING, expecting ‘,’ or ‘;’ in PHP Parse error: syntax error, unexpected ‘$APPLICATION’ (T_VARIABLE) Parse error: syntax error, unexpected end of file in Parse error: syntax error,… 1 |
insideone 3685 / 962 / 114 Регистрация: 10.01.2010 Сообщений: 2,550 |
||||
31.01.2012, 02:23 |
2 |
|||
Строка 1 — открывается тег PHP. Начинается анализ кода. Parse error: syntax error — Ошибка разбора, синтаксическая ошибка. Это всегда означает что вы допустили в коде ошибку, или как в случае выше — забыли закрыть код, благодаря чему в код просочился сторонний текст который естественно является ошибкой для анализатора
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
31.01.2012, 02:23 |
Помогаю со студенческими работами здесь Parse error: syntax error, unexpected ‘)’ in /home/life-plus/life-plus.ru/docs/classes/mysql.php on line 132 <? class… IPB Parse error: syntax error, unexpected T_STRING PHP Parse error: syntax error, unexpected ‘(‘, expecting variable (T_VARIABLE) or ‘$’ in PHP Parse error: … Выборка из двух таблиц: Parse error: syntax error, unexpected T_STRING in Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 2 |
Устанавливаем и настраиваем Битрикс
Туториал по установке чистого Битрикса, без каких-либо шаблонов и дополнений.
Вступление
В этой статье разберем, как установить чистый Битрикс, без каких-либо шаблонов и дополнений. Перед началом убедитесь, что ваш хостинг соответствует техническим требованиям Битрикса, их можно посмотреть по этой ссылке: https://www.1c-bitrix.ru/products/cms/requirements.php
Загружаем дистрибутив Битрикса на свой сайт
Скачиваем архив с официального сайта 1c-bitrix.ru, прямая ссылка на страницу загрузок: https://www.1c-bitrix.ru/download/cms.php
Здесь в блоке «Дистрибутивы» видим ссылки на различные редакции Битрикса: Старт, Стандарт, Малый бизнес и т.п.:
Не буду детально разбирать различия между редакциями, но чем «старше» редакция, тем больше функционала в ней есть и тем дороже она стоит
Мы будем делать простейший сайт, поэтому скачиваем самую «младшую» редакцию – Старт. Загружайте архив на свой хостинг в директорию сайта и распаковывайте.
Устанавливаем Битрикс
Если во время установки возникнет непреодолимая ошибка – поищите решение проблемы в конце этой статьи в блоке Ошибки, которые могут возникнуть на этапе установки.
Открываем главную страницу сайта и начинаем процесс установки. На первом экране жмем «Далее»:
Принимаем лицензионное соглашение (предварительно прочитав его, конечно же) и снова жмем «Далее»:
Мы устанавливаем демо-версию, поэтому регистрировать Битрикс пока что не будем => убираем галочку «Я хочу зарегистрировать свою копию продукта, устанавливать решения из Маркетплейс и получать обновления». Сайт будем устанавливать в кодировке UTF-8 => отмечаем чекбокс «Установить в кодировке UTF-8» и жмем «Далее»:
Если по каким-либо причинам нужно установить сайт в кодировке windows-1251 – просто не отмечайте чекбокс «Установить в кодировке UTF-8».
Теперь нам нужно убедиться, что настройки хостинга соответствуют требованиям Битрикса. В моем случае два параметра подсвечены красным цветом:
Версия веб-сервера не выяснен – если в самом начале вы убедились, что версия веб-сервера соответствует требованиям Битрикса, то на это предупреждение можно не обращать внимания. Практика показывает, что скрипт установщика очень часто не может определить версию веб-сервера, даже если она соответствует требованиям Битрикса.
mbstring.func_overload – а вот этот параметр обязательно нужно исправить. Обычно его можно изменить в настройках PHP, в личном кабинете хостинга.
Устанавливаю нужное значение mbstring.func_overload в настройках хостинга и продолжаю установку.
Если у вас при установке красным цветом подсвечены другие параметры – их нужно постараться исправить. В противном случае могут возникнуть проблемы в работе сайта.
Следующий шаг – настройка соединения с базой данных. Вводим нужные параметры и нажимаем «Далее»:
Теперь ждем окончания установки:
Далее появляется окно для ввода данных администратора. Вводим необходимую информацию и снова жмем «Далее»:
На следующем шаге Битрикс предлагает нам установить одно из готовых решений (шаблонов). Т.к. мы планируем делать свой шаблон — готовые решения нам не нужны. Чтобы ничего не устанавливать — выбираем вариант «Демо-сайт для разработчиков», жмем «Далее»:
И отменяем установку решения, нажав «Отмена», а затем «Ок» во всплывающем окне:
Отлично, решение не установилось, жмем кнопку «Перейти на сайт»:
На этом установка Битрикса завершена, а мы попали на главную страницу. В самом верху у нас отображается панель администратора с вкладками «Сайт» и «Администрирование». Вкладка «Сайт» — это публичный раздел (который виден всем посетителям). Вкладка «Администрирование» — это админка. На протяжении работы с сайтом мы будем переключаться между этими вкладками:
Удаляем лишние установщики
Вы наверняка заметили, что дистрибутив Битрикса был очень объемным (около 200 мегабайт в моем случае). Удалим лишние файлы, чтобы сайт занимал немного меньше места.
Удалим предустановленное решение из раздела «Маркетплейс». Идем на вкладку «Администрирование», далее Marketplace => Установленные решения и удаляем имеющееся там решение:
Это еще не всё, после удаления снова возвращаемся в список решений, нажав кнопку «Вернуться в список»:
Решение всё еще осталось на сайте. Теперь нам нужно его стереть:
В итоге в списке решений должно быть пусто:
Отлично, теперь идем в Настройки => Настройки продукта => Список мастеров и удаляем установщик демо-сайта:
Супер, своими действиями мы только что уменьшили размер сайта примерно на 60 мегабайт.
Запускаем проверку системы
В Битриксе есть инструмент «Проверка системы», который помогает найти причины проблем в работе сайта. У нас никаких проблем и ошибок в работе сайта нет, но после установки Битрикса все-таки стоит запустить этот инструмент. В админ панели идем в раздел Настройки => Инструменты => Проверка системы и нажимаем кнопку «Начать тестирование»:
В моем случае есть несколько ошибок и замечаний, а именно:
Справа у каждого пункта есть иконка вопроса, нажав на которую можно получить подробную информацию. Разберем эти ошибки.
Ошибка! Параметр default_socket_timeout = 10, требуется 60
Значение max_input_vars должно быть не ниже 10000. Текущее значение: 1000
Эти две ошибки можно исправить, добавив 2 строчки в файл .htaccess, который лежит в корне сайта:
php_value max_input_vars 10000
php_value default_socket_timeout 60
Если это не решает проблему – обратитесь в техподдержку своего хостинга, вам должны подсказать, как правильно настроить указанные параметры.
Замечание. Агенты выполняются на хитах, рекомендуется перевести выполнение агентов на cron
Это не критичное замечание. Пока что не будем вникать в то, что собой представляют Агенты в Битриксе. Просто отмечу, что до тех пор, пока вы не создаете своих Агентов, можно не беспокоиться о переводе Агентов на CRON.
Замечание. Возможны проблемы в работе с длинными строками из-за системных ограничений
И это замечание тоже не критично, если сайт работает без ошибок – это предупреждение можно игнорировать (на моей практике из-за него никогда не возникало проблем).
Ошибка! Переменная sql_mode в MySQL должна быть пустая, текущее значение: NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
Кликаем на знак вопроса справа от этого пункта и получаем решение проблемы:
Вносим указанный код в указанные файлы.
После исправления всех ошибок заново запустим тестирование системы, чтобы убедиться, что в этот раз всё в порядке.
Ошибки, которые могут возникнуть на этапе установки Битрикса
Parse error: syntax error, unexpected ‘::’ (T_PAAMAYIM_NEKUDOTAYIM)
Эта ошибка может появляться при первоначальном открытии сайта. Полный текст ошибки выглядит примерно так:
Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in /home/users/p/polzovatel/domains/bitrix.alfavitka.ru/bitrix/modules/main/lib/orm/data/datamanager.php on line 77
Скорее всего, проблема кроется в версии PHP. На момент написания этого урока рекомендуемая версия PHP для Битрикса – 7.2. Попробуйте выбрать её в настройках хостинга.
Актуальные минимальные технические требования Битрикса можно посмотреть по ссылке: https://www.1c-bitrix.ru/products/cms/requirements.php
Ваша версия MySql не удовлетворяет минимальным техническим требованиям продукта.
Эта ошибка возникает после ввода параметров соединения с базой данных:
Скорее всего, на хостинге используется устаревшая версия MySQL. На момент написания этого урока версия MySQL должна быть не ниже 5.6.
Актуальные минимальные технические требования Битрикса можно посмотреть по ссылке:
https://www.1c-bitrix.ru/products/cms/requirements.php
Если ваш хостинг использует старую версию MySQL и её никак нельзя обновить – вам пора задуматься о смене хостинга.