Bitrix parse error syntax error unexpected

На битриксе стоит 2 сайта, на одном шаблон работает, на другом выдает такую ошибку:Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ')' in /home/www/z70998/htdocs/request/index.php on line 36Кто может помочь?

На перво странице сайта пишет: 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
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

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

Всем добрый вечер, прошу помочь разобраться с ошибкой
Сыпятся вот такая ошибка PHP Parse error:  syntax error, unexpected ‘[‘ in /home/*/*******/********/public_html/bitrix/modules/main/lib/httprequest.php on line 387

Выделил 387 строку красным

private function fetchHeaders(Server $server)
{
$headers = [];
foreach ($server as $name => $value)
{
if (substr($name, 0, 5) === ‘HTTP_’)
{
$headerName = substr($name, 5);
$headers[$headerName] = $value;
}
}

return $this->normalizeHeaders($headers);
}

 

Пользователь 90886

Гуру

Сообщений: 2455
Баллов: 424
Авторитет:

41

Рейтинг пользователя:

1

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

У вас старая версия PHP, 5.3.x, а нужно уже не менее 5.6, но лучше 7.

 

Пользователь 1005987

Заглянувший

Сообщений: 31
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

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

 

Пользователь 90886

Гуру

Сообщений: 2455
Баллов: 424
Авторитет:

41

Рейтинг пользователя:

1

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

А что выводит на этом же сайте phpinfo()?

 

Пользователь 1005987

Заглянувший

Сообщений: 31
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

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

 

Пользователь 90886

Гуру

Сообщений: 2455
Баллов: 424
Авторитет:

41

Рейтинг пользователя:

1

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

Ошибка из публичной части сайта, или при запуске скриптов из планировщика?

 

Пользователь 1005987

Заглянувший

Сообщений: 31
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

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

письма с крона вроде)
Cron <******@bitrix238> /usr/local/bin/php /home/*/******/*****/public_html/bitrix/modules/main/tools/cron_events.php

 

Пользователь 90886

Гуру

Сообщений: 2455
Баллов: 424
Авторитет:

41

Рейтинг пользователя:

1

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

#8

0

26.03.2018 22:19:06

Через SSH выполните

Код
/usr/local/bin/php -v

Скорее всего это версия php другая подключается. Если покажет не 7.1.9, значит нужно определить какой путь к этой версии.
Какой хостинг?

Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем

 

Пользователь 1005987

Заглянувший

Сообщений: 31
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

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

 

Пользователь 1005987

Заглянувший

Сообщений: 31
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

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

#10

0

26.03.2018 22:24:57

PHP 5.3.29 (cli) (built: Aug 19 2016 17:49:16)                                                                                                                                                                                  
Copyright © 1997-2014 The PHP Group                                                                                                                                                                                          
Zend Engine v2.3.0, Copyright © 1998-2014 Zend Technologies                                                                                                                                                                  
   with the ionCube PHP Loader v10.0.3, Copyright © 2002-2017, by ionCube Ltd.                                                                                                                                              
   with Zend Guard Loader v3.3, Copyright © 1998-2010, by Zend Technologies

 

Пользователь 1005987

Заглянувший

Сообщений: 31
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

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

#11

0

26.03.2018 22:27:14

но у них же есть фишка переключения версий php к каждому домену и там я указал 7.1, настройки в dbcon и settings сделал. два проекта работают на этом аккаунте

 

Пользователь 90886

Гуру

Сообщений: 2455
Баллов: 424
Авторитет:

41

Рейтинг пользователя:

1

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

#12

0

26.03.2018 22:28:18

Да.
Попробуйте это:

Код
/opt/php71/bin/php -v

Если да, то в кроне нужно заменить

Код
/usr/local/bin/php

на

Код
/opt/php71/bin/php

Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем

 

Пользователь 139282

Посетитель

Сообщений: 90
Баллов: 8
Авторитет:

0

Рейтинг пользователя:

0

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

#13

0

26.03.2018 22:28:24

а в чем проблема $headers=array();
?

 

Пользователь 90886

Гуру

Сообщений: 2455
Баллов: 424
Авторитет:

41

Рейтинг пользователя:

1

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

#14

0

26.03.2018 22:29:12

Цитата
Dima написал:
но у них же есть фишка переключения версий php к каждому домену и там я указал 7.1, настройки в dbcon и settings сделал. два проекта работают на этом аккаунте

Да, все верно. Но запуск из крона не знает ничего об этом, т.к. запуск из крона не привязывается к домену или сайту, т.е. настройки в этом случае общие — дефолтные.

Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем

 

Пользователь 90886

Гуру

Сообщений: 2455
Баллов: 424
Авторитет:

41

Рейтинг пользователя:

1

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

#15

0

26.03.2018 22:30:06

Цитата
Алексей Кудрявцев написал:
а в чем проблема $headers=array();

Предлагаете внести изменение в файл ядра?

Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем

 

Пользователь 1005987

Заглянувший

Сообщений: 31
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

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

#16

0

26.03.2018 22:33:03

Цитата
Денис Сон написал:
Цитата
Попробуйте это:Код/opt/php71/bin/php -v

/opt/php71/bin/php -v                                                                                                                                                                                      PHP 7.1.9 (cli) (built: Sep 27 2017 19:45:21) ( NTS )                                                                                                                                                                          
Copyright © 1997-2017 The PHP Group                

 

Пользователь 90886

Гуру

Сообщений: 2455
Баллов: 424
Авторитет:

41

Рейтинг пользователя:

1

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

#17

0

26.03.2018 22:34:54

Цитата
Dima написал:
opt/php71/bin/php -v                                                                                                                                                                                      PHP 7.1.9 (cli) (built: Sep 27 2017 19:45:21) ( NTS )                        

Значит, то что нужно

Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем

 

Пользователь 1005987

Заглянувший

Сообщений: 31
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

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

#18

0

26.03.2018 22:38:42

Цитата
Денис Сон написал:
Если да, то в кроне нужно заменитьКод/usr/local/bin/php
наКод/opt/php71/bin/php

а подскажите,конечно глупый вопрос, как для crona это сделать?

 

Пользователь 90886

Гуру

Сообщений: 2455
Баллов: 424
Авторитет:

41

Рейтинг пользователя:

1

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

#19

0

26.03.2018 22:41:44

В панели таймвеба есть пункт Crontab — там эта команда должна быть задана.

 

Пользователь 1005987

Заглянувший

Сообщений: 31
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

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

#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
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

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

#21

0

26.03.2018 22:49:19

Денис Сон,Спасибо за помощь

 

Пользователь 90886

Гуру

Сообщений: 2455
Баллов: 424
Авторитет:

41

Рейтинг пользователя:

1

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

#22

0

26.03.2018 22:50:42

Пожалуйста, обращайтесь :)

Бесплатные консультации по Битриксу | Исправление ошибок на сайте, решение сложных проблем

Содержание

  1. Parse error Ошибка в шаблоне
  2. parsing — PHP parse/syntax errors; and how to solve them
  3. Answer
  4. Solution:
  5. What are the syntax errors?
  6. Most important tips
  7. How to interpret parser errors
  8. Solving syntax errors
  9. White screen of death
  10. Answer
  11. Solution:
  12. Using a syntax-checking IDE means:
  13. Answer
  14. Solution:
  15. Unexpected <-code-11>-code-1>
  16. Unexpected <-code-21>closing square bracket
  17. Answer
  18. Solution:
  19. 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. Источник
  20. Missing semicolon
  21. String concatenation
  22. Missing expression operators
  23. Lists
  24. Class declarations
  25. Variables after ident<-code-19>iers
  26. Missing parentheses after language constructs
  27. Else does not expect conditions
  28. Need brackets <-code-14<-code-16>closure
  29. Invisible whitespace
  30. See also
  31. Answer
  32. Solution:
  33. Unexpected T_CONSTANT_ENCAPSED_STRING Unexpected T_ENCAPSED_AND_WHITESPACE
  34. Incorrect variable interpolation
  35. Missing concatenation
  36. Confusing string quote enclosures
  37. Missing opening quote
  38. Array lists
  39. Function parameter lists
  40. Runaway strings
  41. HEREDOC indentation
  42. Answer
  43. Solution:
  44. Unexpected
  45. Misquoted strings
  46. Unclosed strings
  47. Non-programming string quotes
  48. The missing semicolon <-code-29>again
  49. Short open tags and <-code-23>headers in PHP scripts
  50. Share solution ↓
  51. Additional Information:
  52. Didn’t find the answer?
  53. Similar questions
  54. Write quick answer
  55. About the technologies asked in this question
  56. Laravel
  57. JavaScript
  58. MySQL
  59. Welcome to programmierfrage.com
  60. Get answers to specific questions
  61. 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:

  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.

Источник

What are the syntax errors?

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

Function definition syntax abstract

Most important tips

There are a few basic precautions you can always take:

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

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

    Expected: semicolon

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

How to interpret parser errors

A typical syntax error message reads:

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

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

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

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

Solving syntax errors

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

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

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

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

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

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

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

  • Look at the syntax colorization!

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

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

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

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

  • Whitespace is your friend.
    Follow any coding style.

  • Break up long lines temporarily.

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

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

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

    • Add newlines between:

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

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

  • Comment out offending code.

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

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

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

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

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

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

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

  • The most prevalent newcomer mistakes are:

    • Missing semicolons ; for terminating statements/lines.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    • You are looking at the wrong file!

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

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

    • php -v for the command line interpreter

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

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

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

  • Trial-and-error is your last resort.

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

Further guides:

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

White screen of death

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

  • error_reporting = E_ALL
  • display_errors = 1

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

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

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

Then invoke the failing code by accessing this wrapper script.

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

Konsole

0 / 0 / 0

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

Сообщений: 15

1

30.01.2012, 17:12. Показов 5282. Ответов 1

Метки нет (Все метки)


Здравствуйте, помогите пожалуйста, не понимаю в чем дело пишет ошибку
Parse error: syntax error, unexpected ‘<‘ in /home1/optov116/public_html/bitrix/templates/.default/components/bitrix/catalog/catalog_center/bitrix/catalog.section.list/.default/template.php on line 41
а на этой строчку начинается <table class=»indtab» cellspacing=»0″ cellpadding=»0″>

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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>
 
<?if (count($arResult["SECTIONS"])>0){$GLOBALS["filter"] = 1;?>
<?
 
?>
 
<div style="float:left; text-align:center; border-bottom:1px solid #991A46; width:500px;">
<p style="color: rgb(70, 8, 31); font-weight: bold; font-size: 16px; padding-top: 0px; margin-top: 0px;">Выберите интересующую Вас группу товара</p>
</div>
<div class="bask">
 <?$APPLICATION->IncludeComponent("bitrix:sale.basket.basket.line", "cart3", array(
    "PATH_TO_BASKET" => "/personal/cart/",
    "PATH_TO_PERSONAL" => "/personal/",
    "SHOW_PERSONAL_LINK" => "N"
    ),
    false,
    array(
    "ACTIVE_COMPONENT" => "Y"
    )
);?></div>
<br /><br /><br />
<?if ($_GET["SECTION_ID"]):?>
<table cellpadding="0" cellspacing="0" width="100%" class="spisok1"><tr>
<?$count=0;?>
<?foreach($arResult["SECTIONS"] as $arItem):?>
<?$count++;?>
<td align="left" width="50%" style="padding-bottom:30px;"><table cellpadding="0" cellspacing="0"><tr><td><img src="
<?=$arItem[PICTURE][SRC]?>" /></td><td style="vertical-align:middle;"><a href="<?=$arItem["SECTION_PAGE_URL"]?>"><?=$arItem["NAME"]?></a></td></tr></table></td>
 
 
<?if ($_GET["SECTION_ID"] == "100"){if ($arItem["NAME"]=="Сорочки, пеньюары и многое другое"){
 
echo '<td width="50%" style="padding-bottom:30px;"><table cellpadding="0" cellspacing="0">
<tr>
<td align="left"><img src="/upload/iblock/1f2/ero.png" /></td>
<td style="vertical-align:middle;"><a href="/catalog/?SECTION_ID=155">Мужская коллекция</a></td>
</tr>
</table>
</td>';
 
<table class="indtab" cellspacing="0" cellpadding="0">
  <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/kors.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=94">Корсетные изделия</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/shelk.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=95">Шелковое предпостельное белье</a></td>
           </tr>
          </table>
       </td>
   </tr>
 
  <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/man.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=101">Мужское белье</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/ero.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=100">Эротическое белье</a></td>
           </tr>
          </table>
       </td>
   </tr>
   
   
     <tr>
           <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/fam.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=98">Женский трикотаж</a></td>
           </tr>
          </table>
       </td>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/acs.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=104">Аксессуары</a></td>
           </tr>
          </table>
       </td>
 
 
   </tr>
   
   
   
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/plag.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=103">Пляжная одежда</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/kol.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=99">Колготки</a></td>
           </tr>
          </table>
       </td>
   </tr>
   
   
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/kind.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=102">Детское белье</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/mahr.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=96">Махровые халаты и другая домашняя одежда</a></td>
           </tr>
          </table>
       </td>
   </tr>
   
   
   
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/big.png" /></td>
              <td><a href="/catalog/big/">Большие размеры</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/fbt.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=97">Женский бельевой трикотаж</a></td>
           </tr>
          </table>
       </td>
   </tr>
 
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/new.png" width="88"/></td>
              <td><a href="/catalog/index.php?SECTION_ID=185">Новые поступления</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
       </td>
   </tr>
 
</table>
 
<table class="indtab" cellspacing="0" cellpadding="0">
  <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/kors.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=94">Корсетные изделия</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/shelk.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=95">Шелковое предпостельное белье</a></td>
           </tr>
          </table>
       </td>
   </tr>
 
  <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/man.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=101">Мужское белье</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/ero.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=100">Эротическое белье</a></td>
           </tr>
          </table>
       </td>
   </tr>
   
   
     <tr>
           <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/fam.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=98">Женский трикотаж</a></td>
           </tr>
          </table>
       </td>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/acs.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=104">Аксессуары</a></td>
           </tr>
          </table>
       </td>
 
 
   </tr>
   
   
   
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/plag.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=103">Пляжная одежда</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/kol.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=99">Колготки</a></td>
           </tr>
          </table>
       </td>
   </tr>
   
   
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/kind.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=102">Детское белье</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/mahr.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=96">Махровые халаты и другая домашняя одежда</a></td>
           </tr>
          </table>
       </td>
   </tr>
   
   
   
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/big.png" /></td>
              <td><a href="/catalog/big/">Большие размеры</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/fbt.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=97">Женский бельевой трикотаж</a></td>
           </tr>
          </table>
       </td>
   </tr>
 
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/new.png" width="88"/></td>
              <td><a href="/catalog/index.php?SECTION_ID=185">Новые поступления</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
       </td>
   </tr>
 
</table>
 
 
 
}?>
<?if (($count % 2)==0) {
echo "</tr><tr>";}?>
<?$arIBType[IBLOCK_TYPE_ID] = $arItem[IBLOCK_TYPE_ID];?>
<?endforeach?>
 
 
 
</tr>
</table>
 
<div>
<?
 echo $arResult[SECTION][DESCRIPTION];
?>
</div>
 
 
<?
else:?>
 
<?endif;?>
<?}?>

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

Добавлено через 20 минут
Точнее вот такое:

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
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>
 
<?if (count($arResult["SECTIONS"])>0){$GLOBALS["filter"] = 1;?>
<?
 
?>
 
<div style="float:left; text-align:center; border-bottom:1px solid #991A46; width:500px;">
<p style="color: rgb(70, 8, 31); font-weight: bold; font-size: 16px; padding-top: 0px; margin-top: 0px;">Выберите интересующую Вас группу товара</p>
</div>
<div class="bask">
 <?$APPLICATION->IncludeComponent("bitrix:sale.basket.basket.line", "cart3", array(
    "PATH_TO_BASKET" => "/personal/cart/",
    "PATH_TO_PERSONAL" => "/personal/",
    "SHOW_PERSONAL_LINK" => "N"
    ),
    false,
    array(
    "ACTIVE_COMPONENT" => "Y"
    )
);?></div>
<br /><br /><br />
<?if ($_GET["SECTION_ID"]):?>
<table cellpadding="0" cellspacing="0" width="100%" class="spisok1"><tr>
<?$count=0;?>
<?foreach($arResult["SECTIONS"] as $arItem):?>
<?$count++;?>
<td align="left" width="50%" style="padding-bottom:30px;"><table cellpadding="0" cellspacing="0"><tr><td><img src="
<?=$arItem[PICTURE][SRC]?>" /></td><td style="vertical-align:middle;"><a href="<?=$arItem["SECTION_PAGE_URL"]?>"><?=$arItem["NAME"]?></a></td></tr></table></td>
 
 
<?if ($_GET["SECTION_ID"] == "100"){if ($arItem["NAME"]=="Сорочки, пеньюары и многое другое"){
 
echo '<td width="50%" style="padding-bottom:30px;"><table cellpadding="0" cellspacing="0">
<tr>
<td align="left"><img src="/upload/iblock/1f2/ero.png" /></td>
<td style="vertical-align:middle;"><a href="/catalog/?SECTION_ID=155">Мужская коллекция</a></td>
</tr>
</table>
</td>';
<table class="indtab" cellspacing="0" cellpadding="0">
<tr><td align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/kors.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=94">Корсетные изделия</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/shelk.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=95">Шелковое предпостельное белье</a></td>
           </tr>
          </table>
       </td>
   </tr>
 
  <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/man.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=101">Мужское белье</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/ero.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=100">Эротическое белье</a></td>
           </tr>
          </table>
       </td>
   </tr>
   
   
     <tr>
           <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/fam.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=98">Женский трикотаж</a></td>
           </tr>
          </table>
       </td>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/acs.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=104">Аксессуары</a></td>
           </tr>
          </table>
       </td>
 
 
   </tr>
   
   
   
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/plag.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=103">Пляжная одежда</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/kol.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=99">Колготки</a></td>
           </tr>
          </table>
       </td>
   </tr>
   
   
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/kind.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=102">Детское белье</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/mahr.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=96">Махровые халаты и другая домашняя одежда</a></td>
           </tr>
          </table>
       </td>
   </tr>
   
   
   
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/big.png" /></td>
              <td><a href="/catalog/big/">Большие размеры</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/fbt.png" /></td>
              <td><a href="/catalog/index.php?SECTION_ID=97">Женский бельевой трикотаж</a></td>
           </tr>
          </table>
       </td>
   </tr>
 
     <tr>
      <td  align="left">
         <table cellspacing="0" cellpadding="0">
           <tr>
              <td class="pic"><img src="/image/new.png" width="88"/></td>
              <td><a href="/catalog/index.php?SECTION_ID=185">Новые поступления</a></td>
           </tr>
          </table>
       </td>
 
      <td  align="left">
       </td>
   </tr>
 
</table>
 
 
 
}?>
<?if (($count % 2)==0) {
echo "</tr><tr>";}?>
<?$arIBType[IBLOCK_TYPE_ID] = $arItem[IBLOCK_TYPE_ID];?>
<?endforeach?>
 
 
 
</tr>
</table>
 
<div>
<?
 echo $arResult[SECTION][DESCRIPTION];
?>
</div>
 
 
<?
else:?>
 
<?endif;?>
<?}?>

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



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

30.01.2012, 17:12

Ответы с готовыми решениями:

Не могу разобраться с ошибкой PHP Parse error: syntax error, unexpected
Всем добрый вечер, прошу помочь разобраться с ошибкой
Сыпятся вот такая ошибка PHP Parse error: …

Ошибка Parse error: syntax error, unexpected T_STRING, expecting ‘,’ or ‘;’ in
Подскажите, как исправить эту ошибку? Parse error: syntax error, unexpected T_STRING, expecting ‘,’…

PHP Parse error: syntax error, unexpected ‘$APPLICATION’ (T_VARIABLE)
Здравствуйте, помогите пожалуйста, не могу понять в чем дело, был в настройках компонента и когда…

Parse error: syntax error, unexpected end of file in
Всем привет, доброе утро. Проблема вот в чем.Захожу на сайт и вижу

Parse error: syntax error,…

1

insideone

Автор FAQ

3685 / 962 / 114

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

Сообщений: 2,550

31.01.2012, 02:23

2

PHP
1
2
3
4
5
6
7
8
9
10
11
<?if ($_GET["SECTION_ID"] == "100"){if ($arItem["NAME"]=="Сорочки, пеньюары и многое другое"){
 
echo '<td width="50%" style="padding-bottom:30px;"><table cellpadding="0" cellspacing="0">
<tr>
<td align="left"><img src="/upload/iblock/1f2/ero.png" /></td>
<td style="vertical-align:middle;"><a href="/catalog/?SECTION_ID=155">Мужская коллекция</a></td>
</tr>
</table>
</td>';
 
<table class="indtab"

Строка 1 — открывается тег PHP. Начинается анализ кода.
Строка 11 — начинается HTML-код. Но PHP-тег не закрыт. PHP думает что это PHP-код, а там HTML-код. Происходит ошибка анализа и страница завершается с ошибкой

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
Вообще не вижу где ошибка. помогите пожалуйста.
У меня даже строки такой нету

&lt;? class…

IPB Parse error: syntax error, unexpected T_STRING
Parse error: syntax error, unexpected T_STRING in…

PHP Parse error: syntax error, unexpected ‘(‘, expecting variable (T_VARIABLE) or ‘$’ in
Всем привет!
Делаю один скрипт, когда пытаюсь запустить — вижу ошибку:

PHP Parse error: …

Выборка из двух таблиц: Parse error: syntax error, unexpected T_STRING in
Здравствуйте, замучился уже с этим запросом, подскажите, что тут не так?
$sql_top=mysql_query…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

2

Устанавливаем и настраиваем Битрикс

Туториал по установке чистого Битрикса, без каких-либо шаблонов и дополнений.

Вступление

В этой статье разберем, как установить чистый Битрикс, без каких-либо шаблонов и дополнений. Перед началом убедитесь, что ваш хостинг соответствует техническим требованиям Битрикса, их можно посмотреть по этой ссылке: https://www.1c-bitrix.ru/products/cms/requirements.php

Загружаем дистрибутив Битрикса на свой сайт

Скачиваем архив с официального сайта 1c-bitrix.ru, прямая ссылка на страницу загрузок: https://www.1c-bitrix.ru/download/cms.php

Здесь в блоке «Дистрибутивы» видим ссылки на различные редакции Битрикса: Старт, Стандарт, Малый бизнес и т.п.:

Дистрибутивы на сайте 1c-bitrix.ru

Не буду детально разбирать различия между редакциями, но чем «старше» редакция, тем больше функционала в ней есть и тем дороже она стоит :)

Мы будем делать простейший сайт, поэтому скачиваем самую «младшую» редакцию – Старт. Загружайте архив на свой хостинг в директорию сайта и распаковывайте.

Устанавливаем Битрикс

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

Открываем главную страницу сайта и начинаем процесс установки. На первом экране жмем «Далее»:

Первый экран при установке Битрикса

Принимаем лицензионное соглашение (предварительно прочитав его, конечно же) и снова жмем «Далее»:

Лицензионное соглашение

Мы устанавливаем демо-версию, поэтому регистрировать Битрикс пока что не будем => убираем галочку «Я хочу зарегистрировать свою копию продукта, устанавливать решения из Маркетплейс и получать обновления». Сайт будем устанавливать в кодировке UTF-8 => отмечаем чекбокс «Установить в кодировке UTF-8» и жмем «Далее»:

Параметры установки

Если по каким-либо причинам нужно установить сайт в кодировке windows-1251 – просто не отмечайте чекбокс «Установить в кодировке UTF-8».

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

Проверка настроек хостинга

Версия веб-сервера не выяснен – если в самом начале вы убедились, что версия веб-сервера соответствует требованиям Битрикса, то на это предупреждение можно не обращать внимания. Практика показывает, что скрипт установщика очень часто не может определить версию веб-сервера, даже если она соответствует требованиям Битрикса.

mbstring.func_overload – а вот этот параметр обязательно нужно исправить. Обычно его можно изменить в настройках PHP, в личном кабинете хостинга.

Устанавливаю нужное значение mbstring.func_overload в настройках хостинга и продолжаю установку.

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

Следующий шаг – настройка соединения с базой данных. Вводим нужные параметры и нажимаем «Далее»:

Вводим параметры соединения с базой данных

Теперь ждем окончания установки:

Ждем, пока Битрикс установится

Далее появляется окно для ввода данных администратора. Вводим необходимую информацию и снова жмем «Далее»:

Вводим данные администратора

На следующем шаге Битрикс предлагает нам установить одно из готовых решений (шаблонов). Т.к. мы планируем делать свой шаблон — готовые решения нам не нужны. Чтобы ничего не устанавливать — выбираем вариант «Демо-сайт для разработчиков», жмем «Далее»:

Выбираем решение для установки

И отменяем установку решения, нажав «Отмена», а затем «Ок» во всплывающем окне:

Отменяем установку стандартного решения

Отлично, решение не установилось, жмем кнопку «Перейти на сайт»:

Всё ок, решение не установилось.

На этом установка Битрикса завершена, а мы попали на главную страницу. В самом верху у нас отображается панель администратора с вкладками «Сайт» и «Администрирование». Вкладка «Сайт» — это публичный раздел (который виден всем посетителям). Вкладка «Администрирование» — это админка. На протяжении работы с сайтом мы будем переключаться между этими вкладками:

Вкладки "Сайт" и "Администрирование"

Удаляем лишние установщики

Вы наверняка заметили, что дистрибутив Битрикса был очень объемным (около 200 мегабайт в моем случае). Удалим лишние файлы, чтобы сайт занимал немного меньше места.

Удалим предустановленное решение из раздела «Маркетплейс». Идем на вкладку «Администрирование», далее  Marketplace => Установленные решения и удаляем имеющееся там решение:

Удаляем решение из раздела "Маркетплейс"

Это еще не всё, после удаления снова возвращаемся в список решений, нажав кнопку «Вернуться в список»:

Возвращаемся к списку решений

Решение всё еще осталось на сайте. Теперь нам нужно его стереть:

Стираем решение

В итоге в списке решений должно быть пусто:

В списке решений теперь ничего нет

Отлично, теперь идем в Настройки => Настройки продукта => Список мастеров и удаляем установщик демо-сайта:

Удаляем установщик демо-сайта

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

Запускаем проверку системы

В Битриксе есть инструмент «Проверка системы», который  помогает найти причины проблем в работе сайта. У нас никаких проблем и ошибок в работе сайта нет, но после установки Битрикса все-таки стоит запустить этот инструмент. В админ панели идем в раздел Настройки => Инструменты => Проверка системы и нажимаем кнопку «Начать тестирование»:

Запускаем проверку системы

В моем случае есть несколько ошибок и замечаний, а именно:

Ошибки default_socket_timeout и max_input_vars

Замечание про агенты

Замечание про длинные строки

Ошибка переменной sql_mode

Справа у каждого пункта есть иконка вопроса, нажав на которую можно получить подробную информацию. Разберем эти ошибки.

Ошибка! Параметр 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

Кликаем на знак вопроса справа от этого пункта и получаем решение проблемы:

Решение проблемы с sql_mode

Вносим указанный код в указанные файлы.

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

Ошибки, которые могут возникнуть на этапе установки Битрикса

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. На момент написания этого урока версия MySQL должна быть не ниже 5.6.

Актуальные минимальные технические требования Битрикса можно посмотреть по ссылке:

https://www.1c-bitrix.ru/products/cms/requirements.php

Если ваш хостинг использует старую версию MySQL и её никак нельзя обновить – вам пора задуматься о смене хостинга.

Понравилась статья? Поделить с друзьями:
  • Bitrix mysql query error 1271 illegal mix of collations for operation union 400
  • Bitrix mysql query error 1054
  • Bitrix mysql connect error localhost 2002 no such file or directory 400
  • Bitrix main db connectionexception mysql connect error localhost
  • Bitrix main argumentexception json error 1 100