|
Ok!
|
|
|
Ok!
|
---|---|---|---|---|
1 | function rus2translit($string) { $converter = array( 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', 'ь' => 'j', 'ы' => 'y', 'ъ' => 'j', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya', 'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z', 'И' => 'I', 'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O', 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C', 'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch', 'Ь' => 'j', 'Ы' => 'Y', 'Ъ' => 'j', 'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya', ' ' => '_', '№' => 'No' ); return strtr($string, $converter); } function str2url($str) { $str = rus2translit($str); $str = strtolower($str); $str = preg_replace('~[^-a-z0-9_]+~u', '-', $str); $str = trim($str, "-"); return $str; } | translit, транслит, php | 15 | Транслит |
2 | $text = iconv(mb_detect_encoding($det, mb_detect_order(), true), "UTF-8", $det); | encoding, кодировка, перекодировать, Конвертация | 150 | Конвертация из любой кодировки в utf-8 |
3 | setlocale( LC_ALL, "ru_RU.UTF-8" ); strftime("%A %e %B %Y", mktime(0, 0, 0, 1, 1, 2016)); | дата по-русски, php дата | 100 | Вывод даты в php в русской локали |
4 | Character Meaning Example . Matches any single character – c.t will match cat, cot, cut, etc. + Repeats the previous match one or more times – a+ matches a, aa, aaa, etc * Repeats the previous match zero or more times. – a* matches all the same things a+ matches, but will also match an empty string. ? Makes the match optional. colou?r will match color and colour. ^ Called an anchor, matches the beginning of the string ^a matches a string that begins with a $ The other anchor, this matches the end of the string. a$ matches a string that ends with a. ( ) Groups several characters into a single unit, and captures a match for use in a backreference. (ab)+ matches ababab - that is, the + applies to the group. For more on backreferences see below. [ ] A character class - matches one of the characters c[uoa]t matches cut, cot or cat. [^ ] Negative character class - matches any character not specified c[^/]t matches cat or c=t but not c/t | регулярные выражения, regexp | 10 | Значения символов регулярного выражения |
5 | function cmp($a,$b){ return strtotime($a['PROPERTY_DATER_VALUE'])<strtotime($b['PROPERTY_DATER_VALUE']); } usort($item_happ,"cmp"); | функция, сравнение дат, даты, php | 30 | Пример функции сравнения в php |
6 | foreach($quest['METRO'] as $n => $station) echo ($n > 0 ? ', ' : '').$station['VALUE_ENUM']; | через запятую, массив, элементы | 40 | Элементы массива, выводимые через запятую. Очень элегантное решение |
7 | <input type="tel" name="phone" class="form-control form-block" placeholder="+7(999)999-99-99" pattern="[+]d{1}[(]d{3}[)]d{4}[-]d{2}[-]d{2}" value=""> | html, phone, pattern, regex | 160 | Regex паттерн для проверки номера телефона. Пример html валидации |
8 | onclick="$('html, body').animate({scrollTop:6500}, 'slow'); | jquery, scrollTop, скролл, плавный | 190 | Плавный скролл до точки, jQuery |
9 | CModule::IncludeModule("iblock"); $res = CIBlockElement::GetByID(273); if($obRes = $res->GetNextElement()) { $ar_mir = $obRes->GetProperty("href_mir"); $ar_gil = $obRes->GetProperty('href_gil'); echo $ar_mir['VALUE']['TEXT']; echo $ar_gil['VALUE']['TEXT']; } | битрикс, свойство блока, свойство инфоблока, свойство, инфоблок | 29 | Получить свойство инфоблока по ID элемента |
10 | require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php"); | битрикс пролог, prolog_before | 1040 | Подключение пролога вместо вывода шапки Битрикс |
11 | $(document).ready(function(){ /**function for slider change*/ var sizeSl = $('.slq-wrap li.slide-q').length; var indexSl = 0; var fSlq = function(indexSl){ $('.slq-wrap li.slide-q').removeClass('activ'); $('.slq-wrap li.slide-q').eq(indexSl).addClass('activ'); if ($('.slq-wrap li.slide-q').eq(indexSl).hasClass('video_sl')) { $('.paly-sl-q').show(); } else { $('.paly-sl-q').hide(); } } $('.left-c-sl').click(function(){ clearTimeout(R); /*pause on left click*/ var active_index = 0; window.Int; if (typeof(video)!='object'){ var video = $('slide-q').length; } for(var i=0; i<video.length; i++){ if($(".video_sl").eq(i).hasClass('activ')){ active_index = i; } } var jVideo = document.getElementsByTagName('video'); if(document.getElementsByTagName('video').length!=0){ if (!jVideo[active_index].paused) { $('video').eq(active_index).trigger('pause'); var button = $('.paly-sl-q.comm'); button.removeClass('paused'); } } if (indexSl == 0) { indexSl = sizeSl - 1; } else { indexSl = indexSl - 1; } fSlq(indexSl); }); $('.right-c-sl').click(function(){ /*pause on right click*/ clearTimeout(R); var active_index = 0; window.Int; if (typeof(video)!='object'){ var video = $('slide-q').length; } for(var i=0; i<video.length; i++){ if($(".slide-q").eq(i).hasClass('activ')){ active_index = i; } } var jVideo = document.getElementsByTagName('video'); if(document.getElementsByTagName('video').length!=0){ if (!jVideo[active_index].paused) { $('video').eq(active_index).trigger('pause'); var button = $('.paly-sl-q.comm'); button.removeClass('paused'); } } // console.log(indexSl) if (indexSl == sizeSl - 1) { indexSl = 0; } else { indexSl = indexSl + 1; } fSlq(indexSl); }); }); | видео, ютьюб, youtube, видео пауза | 190 | При переключении видео в Ютьюб в списке ставит прошлое на паузу |
12 | $items_sel = (new CIBlockElement())->GetList([], $filter, 0, 0, ['ID']); $arResult['ITEMS_SELECTED'] = $items_sel->SelectedRowsCount(); if(!$arResult['ITEMS_SELECTED']) $ids = []; else while($item = $items_sel->Fetch()) $ids[] = $item['ID']; | select, iblock, bitrix | 100 | Выбор айблоков в Битрикс |
13 | $was_id = intval($DB->LastID()); | last id, последний id | 150 | Выбрать из базы последний добавленный ID при autoincrement |
14 | (in_array($r[1] % 10, array(2, 3, 4)) && $r[1] < 10 ) ? "отзыва" : ($r[1] == 1 ? "отзыв" : "отзывов") | человека, человек | 1050 | PHP выражение для вывода "человека или человек" в зависимости от цифры |
15 | $useragent=$_SERVER['HTTP_USER_AGENT']; $mob = 0; if(preg_match('/(android|bbd+|meego).+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian|treo|up.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i',substr($useragent,0,4))){ $mob = 1; } | mobile detect, мобильные php, пхп мобильный | 129 | Код определения мобильных телефонов через PHP |
16 | function getCoordinates($address){ $address = urlencode($address); $url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=" . $address; $response = file_get_contents($url); $json = json_decode($response,true); $lat = $json['results'][0]['geometry']['location']['lat']; $lng = $json['results'][0]['geometry']['location']['lng']; return array($lat, $lng); } | координаты, гугл, php | 1050 | Функция получения координат через Гугл на php |
17 | if($arParams["PREVIEW_TRUNCATE_LEN"] > 0 && strlen($arItem["PREVIEW_TEXT"])>5) $arItem["PREVIEW_TEXT"] = $obParser->html_cut($arItem["PREVIEW_TEXT"], $arParams["PREVIEW_TRUNCATE_LEN"]); | truncate, bitrix, prewiew text | 400 | Функция Битрикс для обрезки превью текста, если обрезка автоматически не работает |
18 | Use the "update-ping" mechanism to permanently remove content from the Google AMP Cache after the content has been removed from its origin. For example, to purge content formerly served at https://cdn.ampproject.org/i/s/example.com/favicon.ico, send an update ping request to: https://cdn.ampproject.org/update-ping/i/s/example.com/favicon.ico. Cached content that no longer exists will eventually get removed from the cache; it's just faster to use "update-ping". Google's Remove AMP content "documentation" | amp, удалить, гугл сео | 1234 | Убрать AMP описание удаленной страницы из Гугла |
19 | К картинкам <img src="/img/eyes-l.jpg" srcset="/img/eyes-m.jpg 1x, /img/eyes.jpg 2x" alt="Глаза" height="375" width="500" data-p="/img/eyes.jpg"> <a href="#" rel="prefetch">Ссылка</a> | srcset, prefetch | 100 | srcset для изображений, предпросмотр для ссылок |
20 | :root { font-size: calc(1vw + 1vh + .5vmin); } Now you can utilize the root em unit based on the value calculated by :root: body { font: 1rem/1.6 sans-serif; } | css, шрифт, адаптивно | 20 | Установка размера шрифта в CSS адаптивно изменяющегося к любой ширине экрана |
21 | <img src="http://bit.ly/2heoc2H" alt="Simon's cat" width="200" height="200"> img { object-fit: cover; // magic goes here } | картинка, по ширине, по высоте, подогнать картинку, вместо background-size, object-fit | 190 | Решение с изображением, чтобы отображалось без сжатия и не бэкграунд |
22 | // Create an iframe: const iframe = document.createElement('iframe'); // Put it in the document (but hidden): iframe.style.display = 'none'; document.body.appendChild(iframe); // Wait for the iframe to be ready: iframe.onload = () => { // Ignore further load events: iframe.onload = null; // Write a dummy tag: iframe.contentDocument.write('<streaming-element>'); // Get a reference to that element: const streamingElement = iframe.contentDocument.querySelector('streaming-element'); // Pull it out of the iframe & into the parent document: document.body.appendChild(streamingElement); // Write some more content - this should be done async: iframe.contentDocument.write('<p>Hello!</p>'); // Keep writing content like above, and then when we're done: iframe.contentDocument.write('</streaming-element>'); iframe.contentDocument.close(); }; // Initialise the iframe iframe.src = ''; | iframe vs link | 1755 | Возможный способ ускорения загрузки через Javascript |
23 | $mySignatureValue = md5("$nOutSum:$nInvId:$mrh_pass1:shpdate=$shpdate:shpphone=$shpphone:shppin=$shppin:shptime=$shptime"); | signature value, robokassa | 450 | Строка signature value для платежей через Робокассу |
24 | $rs_Section = CIBlockSection::GetList( array('DEPTH_LEVEL' => 'desc'), $ar_Filter, false, array('ID', 'NAME', 'IBLOCK_SECTION_ID', 'DEPTH_LEVEL', 'SORT') ); $ar_SectionList = array(); $ar_DepthLavel = array(); while($ar_Section = $rs_Section->GetNext(true, false)) { $ar_SectionList[$ar_Section['ID']] = $ar_Section; $ar_DepthLavel[] = $ar_Section['DEPTH_LEVEL']; } $ar_DepthLavelResult = array_unique($ar_DepthLavel); rsort($ar_DepthLavelResult); $i_MaxDepthLevel = $ar_DepthLavelResult[0]; for( $i = $i_MaxDepthLevel; $i > 1; $i-- ) { foreach ( $ar_SectionList as $i_SectionID => $ar_Value ) { if( $ar_Value['DEPTH_LEVEL'] == $i ) { $ar_SectionList[$ar_Value['IBLOCK_SECTION_ID']]['SUB_SECTION'][] = $ar_Value; unset( $ar_SectionList[$i_SectionID] ); } } } function __sectionSort($a, $b) { if ($a['SORT'] == $b['SORT']) { return 0; } return ($a['SORT'] < $b['SORT']) ? -1 : 1; } usort($ar_SectionList, "__sectionSort"); | битрикс, массив, перебор | 780 | Перебор массива Битрикс в виде дерева |
25 | SELECT CONVERT(CONVERT(message USING BINARY) USING cp1251) AS cp1251, CONVERT(CONVERT(message USING BINARY) USING utf8) AS utf8 FROM b_event_message bem WHERE CONVERT(message USING BINARY) RLIKE CONCAT('[', UNHEX('80'), '-', UNHEX('FF'), ']') | sql, script, detect wrong encoding | 506 | Обнаружить не так кодированную ячейку в таблице mysql |
26 | <!--script src="http://maps.api.2gis.ru/2.0/loader.js?pkg=full"></script--> <!--script type="text/javascript"> var map; DG.then(function () { map = DG.map('map', { center: [55.753276, 37.783386], zoom: 15 }); myIcon = DG.icon({ iconUrl: '/wp-content/uploads/2016/12/berkana-marker.png', iconSize: [43, 50] }); DG.marker([55.754244, 37.778933], {icon: myIcon}).addTo(map) }); </script--> | карта, 2gis, скрипт | 1800 | Карта 2Gis |
27 | <?php function Escape_win ($path) { $path = strtoupper ($path); return strtr($path, array("U0430"=>"а", "U0431"=>"б", "U0432"=>"в", "U0433"=>"г", "U0434"=>"д", "U0435"=>"е", "U0451"=>"ё", "U0436"=>"ж", "U0437"=>"з", "U0438"=>"и", "U0439"=>"й", "U043A"=>"к", "U043B"=>"л", "U043C"=>"м", "U043D"=>"н", "U043E"=>"о", "U043F"=>"п", "U0440"=>"р", "U0441"=>"с", "U0442"=>"т", "U0443"=>"у", "U0444"=>"ф", "U0445"=>"х", "U0446"=>"ц", "U0447"=>"ч", "U0448"=>"ш", "U0449"=>"щ", "U044A"=>"ъ", "U044B"=>"ы", "U044C"=>"ь", "U044D"=>"э", "U044E"=>"ю", "U044F"=>"я", "U0410"=>"А", "U0411"=>"Б", "U0412"=>"В", "U0413"=>"Г", "U0414"=>"Д", "U0415"=>"Е", "U0401"=>"Ё", "U0416"=>"Ж", "U0417"=>"З", "U0418"=>"И", "U0419"=>"Й", "U041A"=>"К", "U041B"=>"Л", "U041C"=>"М", "U041D"=>"Н", "U041E"=>"О", "U041F"=>"П", "U0420"=>"Р", "U0421"=>"С", "U0422"=>"Т", "U0423"=>"У", "U0424"=>"Ф", "U0425"=>"Х", "U0426"=>"Ц", "U0427"=>"Ч", "U0428"=>"Ш", "U0429"=>"Щ", "U042A"=>"Ъ", "U042B"=>"Ы", "U042C"=>"Ь", "U042D"=>"Э", "U042E"=>"Ю", "U042F"=>"Я")); } $str = "u0430u043fu044bu0443u043au0435u043f "; print Escape_win ($str); ?> | json, decode | 1030 | Преобразовать в русскоязычные символы |
28 | function mail_utf8($to, $from_user, $from_email, $subject = '(No subject)', $message = '') { $from_user = "=?UTF-8?B?".base64_encode($from_user)."?="; $subject = "=?UTF-8?B?".base64_encode($subject)."?="; $headers = "From: $from_user <$from_email> ". "MIME-Version: 1.0" . " " . "Content-type: text/plain; charset=UTF-8" . " "; return mail($to, $subject, $message, $headers); } | utf-8, mail, php | 90 | Функция mail utf-8 |
29 | @media all and (min-width: 1001px) { #sidebar ul li a:after { content: " (" attr(data-email) ")"; font-size: 11px; font-style: italic; color: #666; } } | media, content | 2360 | Текст тега из атрибуте data-* |
30 | <script> $(document).ready(function () { var elts = $('.resource-children-item'); var div = "<div id='pagination'>"; window.m = Math.floor(elts.length/10); for(var i=1; i<=window.m;i++){ if(i==1){ div = div + "<a class='prev inactive'>← Предыдущая</a>"; } div = div + "<a class='pag-a' data-p='" + i + "'>" + i + "</a>"; } div = div + "<a class=next>Следующая →</a></div>"; $('.resource-view').append(div); $(".pag-a").eq(0).addClass("active"); var act = $(".pag-a.active").attr("data-p"); $('.block_' + act).addClass('active'); $(".pag-a").click(function(){ var act = $(this).text(); $('.resource-children-item, .pag-a').removeClass('active'); $('.block_' + act).addClass('active'); $(this).addClass('active'); $('.prev, .next').removeClass('inactive'); if(act == 1){ $('.prev').addClass('inactive'); } if(act == window.m){ $('.next').addClass('inactive'); } }); $(".next").click(function() { var ind = parseInt($(".pag-a.active").text()); $('.resource-children-item, .pag-a').removeClass('active'); $('.block_' + (ind + 1)).addClass('active'); $(".pag-a").eq(ind).addClass('active'); $('.prev, .next').removeClass('inactive'); if(ind == parseInt(window.m)-1){ $('.next').addClass('inactive'); } }); $(".prev").click(function(){ var ind = parseInt($(".pag-a.active").text()); $('.resource-children-item, .pag-a').removeClass('active'); $('.block_' + (ind - 1)).addClass('active'); $(".pag-a").eq(ind - 2).addClass('active'); $('.prev, .next').removeClass('inactive'); if(ind == 2){ $('.prev').addClass('inactive'); } }); }) $(document).keydown(function(e) { var ind = parseInt($(".pag-a.active").text()); console.log(e.keyCode + ',' + window.m + "," + ind ); if(e.keyCode == 39 && ind < window.m){ $('.resource-children-item, .pag-a').removeClass('active'); $('.block_' + (ind + 1)).addClass('active'); $(".pag-a").eq(ind).addClass('active'); $('.prev, .next').removeClass('inactive'); if(ind == parseInt(window.m)-1){ $('.next').addClass('inactive'); } } if(e.keyCode == 37 && ind > 1){ $('.resource-children-item, .pag-a').removeClass('active'); $('.block_' + (ind - 1)).addClass('active'); $(".pag-a").eq(ind - 2).addClass('active'); $('.prev, .next').removeClass('inactive'); if(ind == 2){ $('.prev').addClass('inactive'); } } }); </script> | пагинация, стрелки, pagination | 1290 | Пагинация jQuery со стрелками влево, вправо |
31 | $rsUser = CUser::GetByID($arPost["AUTHOR_ID"]); $arUser = $rsUser->Fetch(); echo CFile::ShowImage($arUser['PERSONAL_PHOTO'], 98, 98, 'border=0', '', true); | фото пользователя, битрикс | 100 | Вывод фотки пользователя Битрикс |
32 | function find_closed() { var tr = $('tr'); if($('#searchfield').val() != "") { for (var i = 0; i < tr.length; i++) { if (tr.eq(i).text().toLowerCase().indexOf($('#searchfield').val().toLowerCase()) > -1) { tr.eq(i).addClass('opened'); /*tr.eq(i).css({'background': '#A8E9FF'});*/ var found = 1; }else{ tr.eq(i).removeClass('opened'); } } if (found < 1) { $('.not-found').text('Не найдено') } } } | javascript, поиск в таблице | 5400 | JS функция ищет соответствие в словах скрытых строк таблицы. Если найдет — открывает строку, нет — закрывает |
33 | SET @a = 100; UPDATE b_iblock_property_enum bipe set SORT = @a:=@a+5 WHERE PROPERTY_ID = 371 ORDER BY VALUE ASC; | update, mysql, increment | 250 | Изменить колонку SORT в таблице с увеличением на 5 |
34 | UPDATE wp_posts SET post_content = REPLACE(post_content, 'http://rosmid.ru/', '/') WHERE post_content LIKE '%http://rosmid.ru/%' UPDATE b_iblock_element SET CODE = REPLACE(CODE, '.', '_') WHERE CODE LIKE '%.%' | заменить, mysql | 1809 | Заменить конкретные фразы в солонке таблицы mysql |
35 | $page = file_get_contents('http://touch.facebook.com'); $doc = new DOMDocument(); $doc->loadHTML($page); $divs = $doc->getElementsByTagName('div'); foreach($divs as $div) { if ($div->getAttribute('id') === 'content') { echo $div->nodeValue; } } | parse, php, parser | 1000 | Парсер страницы или блока страницы |
36 | div.wpcf7 .screen-reader-response { color: black!important; background: white; padding: 3em; border: 1px solid rgba(1,1,1,.1); margin: 2em; box-sizing: border-box; width: 500px; position: absolute; } | pre, php | 1004 | PRE php |
37 | <?=date ("d-m-Y H:i:s", filemtime(__FILE__))?> | публикация, дата публикации | 110 | Дата публикации, время последнего изменения файла php |
38 | var thisPageName = $('html').find('title').text(); var addrString = document.URL.split('/').splice(-2,1).toString() var reach = "yaCounter48115721.reachGoal('" + addrString + "'); return true;"; $('form.wpcf7-form').append('<input type="hidden" name="pageUrlFrom" value="' + document.URL + '"/>'); $('form.wpcf7-form').append('<input type="hidden" name="pageNameFrom" value="' + thisPageName + '"/>'); $('form.wpcf7-form').find('input[type="submit"]').attr('onclick', reach); | цель, метрика, добавить цели | 1234 | Яваскрипт, jQuery код добавки события reachGoal в форму сайта с учетом адреса страницы |
39 | var docWidth = document.documentElement.offsetWidth; [].forEach.call( document.querySelectorAll('*'), function(el) { if (el.offsetWidth > docWidth) { console.log(el); } } ); | консоль, выступающих, horizontal scroll, поиск в консоли | 100 | Функция поиска выступающих за пределы ширины элементов в консоли Хром |
40 | Если в Joomla выдается ошибка "Неправильно указан путь к папкам tmp и logs", то проще его указать в конфиге как <pre>public $log_path = __DIR__ . '/logs'; public $tmp_path = __DIR__ . '/tmp';</pre> если эти папки лежат в корне сайта | joomla, config path, joomla tmp | 200 | Конфиг Joomla путь до папок |
41 | RewriteEngine On RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^(?:www.)?(.*)$ [NC] RewriteRule (.*) https://%1%{REQUEST_URI} [L,R=301] | redirect, редирект | 3500 | Редирект с http на https + с www на non-www |
42 | Фильтрация по свойству типа строка global $arrFilter; $arrFilter = array("=PROPERTY_STRING"=>"VALUE"); | Битрикс, фильтр, свойство | 500 | Фильтр инфоблока Битрикс по свойству |
43 | $file = CFile::ResizeImageGet($uInfo['PERSONAL_PHOTO'], array('width'=>150, 'height'=>150), BX_RESIZE_IMAGE_PROPORTIONAL, true); | cache, resize, cfile | 1290 | Resize Image Get. Получить массив файла по ID |
44 | @supports (-webkit-overflow-scrolling: touch) {} | iPhone, стили для Apple, стили для iPhone | 2300 | Добавить стили ТОЛЬКО для iPhone, так как он единственный поддерживает owerflow-scrolling |
45 | <? $str = "1234567890"; echo TruncateText($str, 7); // результатом будет строка "1234567..." ?> | bitrix, truncate, text, truncate text | 3100 | Обрезка текста в Битрикс |
46 | $filename = 'files/' . $ident . '.xml'; $ctype="application/force-download"; header("Pragma: public"); // required header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); // required for certain browsers header("Content-Type: $ctype"); // change, added quotes to allow spaces in filenames, by Rajkumar Singh header("Content-Disposition: attachment; filename="".basename($filename)."";" ); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($filename)); readfile("$filename"); | download file, php | 10030 | Сформировать файл и передать его на загрузку в браузер |
47 | ' for ' " for " | замена кавычек, кавычки, quotes | 340 | Замена для кавычек в php |
48 | json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); | json, json_encode, utf-8 символы | 450 | Кодировать в json без преобразования кириллических символов и слэш |
49 | $fp = fopen('tovary.xml',"r"); $arr = file_get_contents('tovary.xml'); $gruops = []; fclose($fp); #[2] => Окрашивание волос #[33] => Перманентная краска $details['category'] = "Перманентная краска"; $s = new SimpleXMLElement($arr); $groups = []; foreach($s->Классификатор->Группы->Группа as $g) { $naim = $g->Наименование; $tid = $g->Ид; $groups[] = [ $tid[0] . "", $naim[0] . "" ]; foreach ( $g->Группы->Группа as $gr_parent ) { $naim = $gr_parent->Наименование; $tid = $gr_parent->Ид; $groups[] = [ $tid[0] . "", $naim[0] . "" ]; } } foreach($groups as $gr){ if($gr[1] == $details['category']){ echo $gr[0]; } } | битрикс, парсинг, xml, товары, каталог | 7090 | Парсить группы (категории) товаров в xml экспорте товаров Битрикс |
50 | <script> jQuery('.order-form-submit').click(function send_order(){ gtag('event', 'purchase', { "transaction_id": <?=rand(1,1000)?>, "affiliation": "La Maree Buy", "value": {TOVAR_SUM}, "currency": "RUR", "tax": 1.18, "shipping": 350, "items": <?=json_encode( $GLOBALS['item'], JSON_UNESCAPED_UNICODE ); ?> }); }); </script> | gtag, js, аналитика, purchase | 4899 | Скрипт добавки товара в Аналитику gtag js |
51 | var ALERT_TITLE = ""; var ALERT_BUTTON_TEXT = "×"; if(document.getElementById) { window.alert = function(txt) { createCustomAlert(txt); } } function createCustomAlert(txt) { var d = document; if(d.getElementById("modalContainer")) return; var mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div")); mObj.id = "modalContainer"; //mObj.style.height = d.documentElement.scrollHeight + "px"; var alertObj = mObj.appendChild(d.createElement("div")); alertObj.id = "alertBox"; if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px"; alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px"; alertObj.style.visiblity="visible"; //h1 = alertObj.appendChild(d.createElement("h1")); //h1.appendChild(d.createTextNode(ALERT_TITLE)); var msg = alertObj.appendChild(d.createElement("p")); //msg.appendChild(d.createTextNode(txt)); msg.innerHTML = txt; var btn = alertObj.appendChild(d.createElement("a")); btn.id = "closeBtn"; btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT)); btn.href = "#"; btn.focus(); btn.onclick = function() { removeCustomAlert(); return false; } alertObj.style.display = "block"; } function removeCustomAlert() { document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); } | алерт, alert, custom alert | 120 | Функция замены обычного alert на кастомный |
52 | add_filter( 'jpeg_quality', function ( $arg ) { return 100; } ); | качество jpg, wp, jpg quality | 670 | Отменить кадрирование в вордпресс, установить качество 100: |
53 | remove_image_size('large'); remove_image_size('medium'); add_filter( 'wp_calculate_image_srcset_meta', '__return_null' ); Другое решение, сработало в другом месте add_filter( 'max_srcset_image_width', create_function( '', 'return 1;' ) ); | srcset, отменить srcset, wp | 590 | Отменить srcset в Вордпрессе |
54 | //Если с английского на русский, то передаём вторым параметром true. var transliterate = ( function() { var rus = "щ ш ч ц ю я ё ж ъ ы э а б в г д е з и й к л м н о п р с т у ф х ь".split(/ +/g), eng = "shh sh ch cz yu ya yo zh `` y e a b v g d e z i j k l m n o p r s t u f x ``".split(/ +/g); return function(text, engToRus) { var x; for(x = 0; x < rus.length; x++) { text = text.split(engToRus ? eng[x] : rus[x]).join(engToRus ? rus[x] : eng[x]); text = text.split(engToRus ? eng[x].toUpperCase() : rus[x].toUpperCase()).join(engToRus ? rus[x].toUpperCase() : eng[x].toUpperCase()); } return text; } } )(); | транслит, translit, латинский-русский, lat-cyr, javascript, js | 350 | Транслитерация с английского в русский Яваскрипт |
55 | var d = date_form.replace(/(d+)-(d+)-(d+)/, '$3.$2.$1') | дата, конверт, яваскрипт, дата по-русски, convert, javascript, js, date lat to rus | 250 | Яваскрипт преобразование (конверт) даты евро в русскую "2018-08-15" в "15.08.2018" |
56 | time = new Date().getHours() + ":" + new Date().getMinutes() | время, яваскрипт, время сейчас, js, time now, time | 90 | Время сейчас — часы : минуты |
57 | require_once("wp-load.php"); | wp, native functions, include | 980 | All important WordPress file that I needed to include in my custom PHP file was "wp-load.php" |
58 | UPDATE table_name SET `column_name` = LOWER( `column_name` ) | замена, mysql, строчные, нижний регистр | 907 | Приведение, замена записей mysql к нижнему регистру |
59 | $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; | protocol, https | 650 | Определить протокол |
60 | <meta name="viewport" content="width=device-width, initial-scale=1"> | viewport, meta, метатег | 9800 | Метатег viewport |
61 | <img src="image.svg" onerror="this.onerror=null; this.src='image.png'"> | ошибка картинки, ошибка изображений | 1004 | Обработка ошибки при загрузке изображений |
62 | count(preg_grep('~^[0-9]$~', str_split($str))) | считать сколько цифр, php цифр, count digits | 2390 | Посчитать число цифр в строке php |
63 | if($("[name=form_text_21]").val().replace(/D+/g, '').length == 11) | js,javascript,phone,длина телефона, число цифр в номере телефона | 1300 | Проверка числа цифр в номере телефона яваскрипт |
64 | function ProductsFilter(a) { var products = $('.catalog-item'); $.each(products, function () { if($(this).find('.catalog-item-name').text().indexOf(a) > -1){ $(this).prependTo($(".catalog-items-container")); } else{ $(this).remove() } }); } | товары, фильтр, jquery | 100 | jQuery фильтр по товарам |
65 | br{content:' ';} br:after{content:' ';} | br, пробел, абзац, новая строка | 1270 | CSS заменить тег <br> пробелами. Собрать строку из абзацев. |
66 | $(document).ready(function(){ // сли пользователь начинает вводить телефон с восьмерки она изменяется $('[name=user_f_5]').keyup(function (event) { if($('[name=user_f_5]').val().length === 4) { console.log('press') newText = event.target.value; $('[name=user_f_5]').val(newText.replace("8","")); } }); }); | восьмерка, телефон | 450 | Если пользователь начинает вводить телефон с восьмерки она изменяется |
67 | <? $APPLICATION->AddHeadString('ваш_код',true); ?> | шапка, битрикс, head | 10900 | Добавить любую строку в шапку Битрикс |
68 | <img src="fake.jpg" data-src="real.jpg"/> <script> function init() { var imgDefer = document.getElementsByTagName('img'); for (var i=0; i<imgDefer.length; i++) { if(imgDefer[i].getAttribute('data-src')) { imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src')); } } } window.onload = init; </script> | defer, images | 90 | Отложенная загрузка изображений после загрузки страницы |
69 | SELECT * FROM table WHERE CHAR_LENGTH(column_name) < 5 | strlen, mysql | 430 | Выбрать из таблицы по длине строки |
70 | <div><a href="https://api.whatsapp.com/send?phone=79096414345" class="whatsapp"><img src="https://upload.wikimedia.org/wikipedia/commons/6/6b/WhatsApp.svg" width="20"></a></div> <div><a href="viber://contact?number=%2B79096414345" class="viber"><img src="https://seeklogo.com/images/V/viber-logo-02B562CBA7-seeklogo.com.png" width="18"></a></div> | viber, whatsapp | 100 | Вацбер и Вотсап ссылки для сайта |
71 | function resi($src,$w,$h) { $im_array = explode('/', $src); $folder = "/" . $im_array[1] . "/" . $im_array[2] . "/"; $file = end($im_array); $root_path = "/home/d/dlmlru/shop_beta/public_html"; if(!is_file( $root_path . "/images/products/" . 'N_'. $file)) { $inFile = $root_path . $src; $outFile = $folder . 'N_' . $file; $image = new Imagick($inFile); $image->thumbnailImage($w, $h); $image->writeImage($root_path . $outFile); return $folder . 'N_' . $file; }else{ return $folder . 'N_' . $file; } } # example <img src="<?echo resi('/images/products/DSC08794_КМГ613_1600.jpg', 200, 133);?>" width="200"/> | resize, php | 12000 | Ресайз картинок php |
72 | .modal { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } | absmiddle,center screen, center position | 100 | Центрировать блок по середине экрана по высоте и ширине |
73 | function urlRusDecode($str) { $to = array("а", "б", "в", "г", "д", "е", "ё", "ж", "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы", "ь", "э", "ю", "я", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ы", "Ь", "Э", "Ю", "Я"); $from = array("%D0%B0", "%D0%B1", "%D0%B2", "%D0%B3", "%D0%B4", "%D0%B5", "%D1%91", "%D0%B6", "%D0%B7", "%D0%B8", "%D0%B9", "%D0%BA", "%D0%BB", "%D0%BC", "%D0%BD", "%D0%BE", "%D0%BF", "%D1%80", "%D1%81", "%D1%82", "%D1%83", "%D1%84", "%D1%85", "%D1%86", "%D1%87", "%D1%88", "%D1%89", "%D1%8A", "%D1%8B", "%D1%8C", "%D1%8D", "%D1%8E", "%D1%8F", "%D0%90", "%D0%91", "%D0%92", "%D0%93", "%D0%94", "%D0%95", "%D0%81", "%D0%96", "%D0%97", "%D0%98", "%D0%99", "%D0%9A", "%D0%9B", "%D0%9C", "%D0%9D", "%D0%9E", "%D0%9F", "%D0%A0", "%D0%A1", "%D0%A2", "%D0%A3", "%D0%A4", "%D0%A5", "%D0%A6", "%D0%A7", "%D0%A8", "%D0%A9", "%D0%AA", "%D0%AB", "%D0%AC", "%D0%AD", "%D0%AE", "%D0%AF"); return str_ireplace($from,$to,$str); } | urlrusdecode | 250 | urldecode, конвертация url-символов в русские |
74 | print <<<INDEX_MED INDEX_MED; | печать блока php | 340 | Форматированная печать блока php |
75 | $widthPreview = 200; $heightPreview = 200; if ($arResult["DETAIL_PICTURE"]) { $file = CFile::ResizeImageGet($arResult["DETAIL_PICTURE"], array('width'=> $widthPreview, 'height'=> $heightPreview), BX_RESIZE_IMAGE_EXACT, true); $arResult["PREVIEW_PICTURE"]["SRC"] = $file["src"]; $arResult["PREVIEW_PICTURE"]["WIDTH"] = $file["width"]; $arResult["PREVIEW_PICTURE"]["HEIGHT"] = $file["height"]; } elseif($arResult["PREVIEW_PICTURE"]) { $file = CFile::ResizeImageGet($arItem["PREVIEW_PICTURE"], array('width'=> $widthPreview, 'height'=> $heightPreview), BX_RESIZE_IMAGE_EXACT, true); $arResult["PREVIEW_PICTURE"]["SRC"] = $file["src"]; $arResult["PREVIEW_PICTURE"]["WIDTH"] = $file["width"]; $arResult["PREVIEW_PICTURE"]["HEIGHT"] = $file["height"]; } | resizeImageGet, resize, bitrix | 250 | result_modifier для кеширования и ресайза картинок |
76 | <?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die(); use BitrixIblock; $sectionsID = array(); foreach ($arResult["ITEMS"] as $arItem) { if ($arItem["IBLOCK_SECTION_ID"]) { $sectionsID[] = $arItem["IBLOCK_SECTION_ID"]; } } $sectionsID = array_unique($sectionsID); $result = IblockSectionTable::getList(array( "select" => array( "ID", "NAME", ), "filter" => array( "ID" => $sectionsID, "IBLOCK_ID" => $arResult["IBLOCK_ID"], ), )); $arResult["SECTIONS"] = array(); while ($row = $result->fetch()) { $arResult["SECTIONS"][$row["ID"]] = $row; } | sections, bitrix, sections by id | 120 | Выбор секций каталога Битрикс по ID элемента |
77 | <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-115977538-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-115977538-1'); </script> | gtag, google tagmanager | 1090 | Google Tag Manager |
79 | <?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die(); $widthPreview = 300; $heightPreview = 200; $widthPreviewBig = 300*2; $heightPreviewBig = 200*2; foreach($arResult['ITEMS'] as $i => $arItem) { $file = CFile::ResizeImageGet($arItem['FIELDS']["DETAIL_PICTURE"]['ID'], array('width' => $widthPreviewBig, 'height' => $heightPreviewBig), BX_RESIZE_IMAGE_EXACT, true); $arResult['ITEMS'][$i]["FIELDS"]["DETAIL_PICTURE"]["SRC"] = $file["src"]; $arResult['ITEMS'][$i]["FIELDS"]["DETAIL_PICTURE"]["WIDTH"] = $file["width"]; $arResult['ITEMS'][$i]["FIELDS"]["DETAIL_PICTURE"]["HEIGHT"] = $file["height"]; $file = CFile::ResizeImageGet($arItem["PREVIEW_PICTURE"]['ID'], array('width' => $widthPreview, 'height' => $heightPreview), BX_RESIZE_IMAGE_EXACT, true); $arResult['ITEMS'][$i]["PREVIEW_PICTURE"]["SRC"] = $file["src"]; $arResult['ITEMS'][$i]["PREVIEW_PICTURE"]["WIDTH"] = $file["width"]; $arResult['ITEMS'][$i]["PREVIEW_PICTURE"]["HEIGHT"] = $file["height"]; } | resizeImageGet, resize, bitrix | 2300 | Ресайз |
80 | <mytag> <![CDATA[Your text goes here. Btw: 5<6 and 6>5]]> </mytag> | cdata, xml, wrong tags | 20300 | Если заполнение xml параметра выдает текстовую ошибку из-за несовместимого символа, то все символы прячутся в тег CDATA |
81 | <picture> <source srcset="img/awesomeWebPImage.webp" type="image/webp"> <source srcset="img/creakyOldJPEG.jpg" type="image/jpeg"> <img src="img/creakyOldJPEG.jpg" alt="Alt Text!"> </picture> | html, webp | 1560 | Еще способ ставить или webp или jpg |
82 | function convertArrayToXML($arr,$key=NULL,$depth=0) { if (is_object($arr)) $arr=toArray($arr); if (is_array($arr)) { $out=" ".str_repeat(" ", $depth); foreach($arr as $k=>$v) { if (is_int($k)) { $fl=true; if ($k) $out.="</".$key.">"." ".str_repeat(" ", $depth-1)."<".$key.">"; $out.=convertArrayToXML($v,$k,$depth); } else { $fl=false; $out.="<".$k.">".convertArrayToXML($v,$k,$depth+1)."</".$k.">"." ".str_repeat(" ", $depth); } } if (!$fl && $key!==NULL) $out=substr($out,0,-2); } else { $out=$arr; } return $out; } | array, xml | 340 | Перевод массива в XML |
83 | <script> setInterval(function(){remSovet()}, 100); // убираем советника function remSovet(){ if($('button[title="О программе"]').length){ console.log('sov'); $('button[title="О программе"]').parent().parent().parent().parent().remove(); $('html').attr('style', ''); } } </script> | советник, яндекс | 230 | Функция Убрать советника Яндекс |
84 | INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE name="A", age=19 | update, duplicate | 100 | Если есть уже такой ключ в базе, то обновить значение |
85 | document.addEventListener("DOMContentLoaded", function(event) { console.log("DOM fully loaded and parsed"); }); | domcontentloaded | 200 | По окончании загрузки страницы без jQuery |
86 | RewriteCond %{HTTPS} off RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTP_HOST} !^www. [NC] RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] | https, www | 8700 | Любой редирект на https + www |
87 | var setResponsive = function () { if ($(window).height() > $("#adminmenuwrap").height() + 50) { $('#adminmenuwrap').css('position', 'fixed'); } else { $('#adminmenuwrap').css('position', 'relative'); } } $(window).resize(setResponsive); setResponsive(); | wp, overflow, height | 500 | Функция WP для отображения кнопок левого меню админки пр низком экране |
88 | document.addEventListener("DOMContentLoaded", function(event) { var cl = document.getElementById('#all_otz'); cl.onclick = function(ev) { var post = {}; post['num_otz'] = 20; post['ajax'] = 'y'; node = BX('video_feed_block'); if (!!node) { BX.ajax.post( 'https://www.brtclinic.ru/index.php', post, function (data) { var el = data.getElementById('video_feed_block'); node.innerHTML = el.innerHTML(); } ); } } }); | битрикс, битрикс аякс | 1090 | Битрикс функция вместо jQuery ajax |
89 | $post = get_post(); $t = strtotime($post->post_modified_gmt); $str = 'Last-Modified: '.gmdate('D, d M Y H:i:s', $t).' GMT'; header('Last-Modified: '.gmdate('D, d M Y H:i:s', $t).' GMT'); | daremodified, wp, php | 1200 | WP date modified php file |
90 | center iframe { width: 100%; height: calc(100vw * 9 / 16 ); } | iframe, youtube, height | 120 | Установить размер iframe видео с Youtube, подогнать его под мобильный размер. При условии, что видео 100% ширны. |
91 | При ошибке 502 в импорте инфоблоков Битрикс Заменить в файле /bitrix/modules/iblock/admin/iblock_xml_import.php if($obXMLFile->ReadXMLToDatabase($fp, $NS, $INTERVAL)) на if($obXMLFile->ReadXMLToDatabase($fp, $NS, 10, $INTERVAL)) | 502, битрикс, инфоблок, ошибка импорта | 140 | Ошибка импорта инфоблока Битрикс 502 |
92 | $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $path = $protocol . $_SERVER['HTTP_HOST'] . SITE_TEMPLATE_PATH; | битрикс, путь | 1450 | Путь до файла без слеша на конце |
93 | <?=($this->GetFolder().'/images/ .... ?> | картинка шаблона инфоблока | 3200 | Путь картинки из папки images размещенной в шаблоне компонента |
94 | $webpsupport = (strpos($_SERVER['HTTP_ACCEPT'], 'image/webp') >= 0); if($webpsupport) { $this->attemptToServeWebP($pathinfo, $matches, $width, $height, $density); } else { $this->attemptToServeNormal($pathinfo, $matches, $width, $height, $density); } | webp,support | 100 | Определить, поддерживает ли браузер webp картинки |
95 | <?=(webps() && is_file($_SERVER['DOCUMENT_ROOT'] . str_replace('.jpg', '.webp', $arItem["DETAIL_PICTURE"]["SRC"])))?'style="background-image: url('.str_replace('.jpg', '.webp', $arItem["DETAIL_PICTURE"]["SRC"]).')':'style="background-image: url('.$arItem["DETAIL_PICTURE"]["SRC"].')'?>" | webp,support | 120 | Бэкграунд если готов файл webp |
96 | function resizeAndConvertImageWebP( $width, $height, $density, $originalFilepath, $resizedFilepath) { $newWidth = $width * $density; $newHeight = $height * $density; $image = new Imagick($originalFilepath); $origImageDimens = $image->getImageGeometry(); $origImgWidth = $origImageDimens['width']; $origImgHeight = $origImageDimens['height']; if($newWidth == 0) { $ratioOfHeight = $newHeight / $origImgHeight; $newWidth = $origImgWidth * $ratioOfHeight; } if($newHeight == 0) { $ratioOfWidth = $newWidth / $origImgWidth; $newHeight = $origImgHeight * $ratioOfWidth; } $widthRatios = $origImgWidth / $newWidth; $heightRatios = $origImgHeight / $newHeight; if($widthRatios <= $heightRatios) { $cropWidth = $origImgWidth; $cropHeight = $newWidth * $widthRatios; } else { $cropWidth = $newHeight * $heightRatios; $cropHeight = $origImgHeight; } $cropX = ($origImgWidth - $cropWidth) / 2; $cropY = ($origImgHeight - $cropHeight) / 2; $image->stripImage(); $image->cropImage($cropWidth, $cropHeight, $cropX, $cropY); $image->resizeImage($newWidth, $newHeight, imagick::FILTER_LANCZOS, 0.9); $image->setImageFormat('webp'); $image->setImageAlphaChannel(imagick::ALPHACHANNEL_ACTIVATE); $image->setBackgroundColor(new ImagickPixel('transparent')); $image->writeImage($resizedFilepath); } | webp,support,imagemagic | 140 | Конвертация картинки в webp в случае, если imageMagic поддрживает |
97 | <link rel="stylesheet" href="/animate.min.css" media="none" onload="if(media!='all')media='all'"><noscript><link rel="stylesheet" href="/animate.min.css"></noscript> | link, ускорение загрузки | 130 | Ускорение загрузки сайта уменьшением загрузки css |
98 | onerror="this.src='/bitrix/templates/persona/images/<?=strtolower(str_replace(' ', '-', $arItem['PROPERTY_BRAND_VALUE']))?>-pale.jpg'; this.setAttribute('data-err', 'true')" | дефолт, картинка, img | 220 | В случае, если картинки нет, то прописать свойство (здесь название бренда) в качестве дефолтной картинки |
99 | DELETE t1 FROM contacts t1 INNER JOIN contacts t2 WHERE t1.id < t2.id AND t1.email = t2.email; | удалить, mysql, дупликаты | 2900 | Удалить дублирующиеся строки базы |
100 | <?if($_REQUEST) { if ( htmlspecialchars( $_REQUEST['mail'], 3 ) != '' && strpos( htmlspecialchars( $_REQUEST['mail'], 3 ), '@' ) != false ) { $to = 'houghton@mail.ru'; $to2 .= htmlspecialchars( $_REQUEST['mail'] ); $subject = 'Сообщение с сайта' . $_SERVER['HTTP_HOST']; $subject2 = 'Ваше сообщение на сайт ' . $_SERVER['HTTP_HOST']; $message = ' <html> <head> <title>Сообщение с сайта ' . $_SERVER['HTTP_HOST'] . '</title> </head> <body> <p>С сайта отправлено соощение:</p> <table cellpadding=10> <tr> <th style="background-color:#ccc; color:white">Имя</th><th style="background-color:#ccc; color:white">Почта</th><th style="background-color:#ccc; color:white">Дата</th><th style="background-color:#ccc; color:white">Время</th> </tr> <tr> <td>' . htmlspecialchars( $_REQUEST['name'],3 ) . '</td><td>' . htmlspecialchars( $_REQUEST['mail'],3 ) . '</td><td>' . date( 'd-m-Y' ) . '</td><td>' . date( 'H:s' ) . '</td> </tr> <tr> <td colspan=4>' . htmlspecialchars( $_REQUEST['text'],3 ) . '</td> </tr> </table> </body> </html> '; $message2 = ' <html> <head> <title>Сообщение с сайта' . $_SERVER['HTTP_HOST'] . '</title> </head> <body> <p>Вы отправили сообщение на сайт ' . $_SERVER['HTTP_HOST'] . '. С вами свяжутся в ближайшее время, спасибо.</p> </body> </html> '; $headers = 'MIME-Version: 1.0' . " "; $headers .= 'Content-type: text/html; charset=utf-8' . " "; $headers .= 'To: Admin <' . $to . '>' . " "; $headers .= 'From: Reglass <' . $to . '>' . " "; $headers2 = 'MIME-Version: 1.0' . " "; $headers2 .= 'Content-type: text/html; charset=utf-8' . " "; $headers2 .= 'To: ' . htmlspecialchars( $_REQUEST['name'] ) . ' <' . htmlspecialchars( $_REQUEST['mail'] ) . '>' . " "; $headers2 .= 'From: Reglass <' . $to . '>' . " "; if($y = mail( $to, $subject, $message, $headers ) && $y2 = mail( $to2, $subject2, $message2, $headers2 )) { echo '<script>alert(Спасибо. Сообщение отправлено.); document.location="/"</script>'; } } } ?> | php, mail | 230 | Отправка письма php |
101 | /bitrix/modules/main/include.php replace OLDSITEEXPIREDATE by (exmpl) time() + 86400 * 3 | bitrix | 100 | replace old site expire date |
102 | "ELEMENT_SORT_FIELD" => "catalog_PRICE_1", "ELEMENT_SORT_ORDER" => "asc" | сортировка, цена, битрикс | 230 | Сортировка каталога по цене в Битрикс |
103 | $data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $data); var_dump(unserialize($data)); | replace, serialized | 510 | recalculating the length of the elements in serialized array |
104 | width: expression(((document.documentElement.clientWidth || document.body.clientWidth) < 1050)? "1050px" : "100%"); | expression, css | 690 | Применение expression в css |
105 | <a id="ajaxaction=add&ajaxaddid=<?=$ar_fields['ID'];?>" rel="nofollow" class="catalog-item-buy input-basket-submit" href="?action=ADD2BASKET&id=<?=$ar_fields['ID'];?>">В корзину</a> | bitrix, в корзину | 560 | Код кнопки добавления в корзину итрикс |
106 | window.i = 1; setInterval(function( ){ $.ajax({ type: 'get', url: 'https://shop.lamaree.ru/agree/letter.php?iter=' + window.i + '&pass=q12345Q&test=1', data: '', dataType: "html", success: function (data) { console.log(window.i); } }); ++window.i; },1000) | рассылка, скрипт, ajax | 3450 | Скрипт рассылки раз в секунду для консоли |
107 | \Bitrix\Main\Loader::includeModule("fileman"); if(CLightHTMLEditor::IsMobileDevice()){ $mob = 1; } | мобильный, битрикс | 450 | Проверка если битрикс мобильный |
108 | $row['cat_url'] = sb_check_chpu('', '', $row['cat_title'], 'sb_categs', 'cat_url', 'cat_id'); | чпу, сбилдер, sbuilder | 560 | Получить адрес категории в SBuilder |
109 | echo NormalizePhone("8 (2546) 27-27-10",14); echo check_email("maxkuku@gmail.com"); | проверка, битрикс, email, телефон | 390 | Функция преобразования телефона и проверки email в Битрикс |
110 | echo GetCountryByID ( GetCountryIdByCode("NL") ); | битрикс, страна | 780 | Вывести название страны по ее коду |
111 | define("LOG_FILENAME", "/home/d/dlmlru/bx/public_html/handmadelog.log"); $sText = "Интересное логирование"; AddMessage2Log($sText, $sModule = "", $traceDepth = 6, $bShowArgs = false); | лог, логирование, битрикс | 320 | Настройка логирования вручную в Битрикс |
112 | $r = GetCountries(); print_r($r); Array ( [0] => Array ( [ID] => 1 [CODE] => RU [NAME] => Россия ) [1] => Array ( [ID] => 2 [CODE] => AZ [NAME] => Азербайджан ) ) | страны, страна, битрикс, массив | 100 | Получить массив стран в Битрикс |
113 | HTMLToTxt($str, $strSiteUrl="", $aDelete=array(), $maxlen=70) | html, text, текст, преобразовать, битрикс | 450 | Преобразовать html в текст в Битриксе |
114 | $apiToken = "код_числом:код_присланный"; $data = [ 'chat_id' => '@Notifier_lamaree', 'text' => 'Goods Posuda import OK in '.date('d.m.Y H:i:s').'!' ]; $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" . http_build_query($data) ); | телеграм, бот сообщений, мессенджер | 110 | Телеграм бот для отправки сообщений любых с сайта |
115 | RewriteCond %{REQUEST_URI} !^/(catalog/special/action) RewriteCond %{REQUEST_URI} !^/(catalog/special/hit) RewriteCond %{REQUEST_URI} !^/(catalog/special/new) RewriteCond %{REQUEST_URI} ^/catalog/special/(.*)/ RewriteRule ^.*$ /404.php [L] | 404, редирект | 1090 | Редирект на 404 всех из списка кроме указанных |
116 | Добавьте в wp-config.php в самое начало (после <?php ): $_SERVER['HTTPS'] = 'on'; | https, wp, too many redirects | 1380 | При ошибке Wordpress TOO_MANY_REDIRECTS после указания адреса в настройках как https |
117 | SELECT * FROM news UNION SELECT * FROM news1 WHERE date = \'03.12.2015\' GROUP BY region ORDER BY id DESC | union, mysql | 980 | Объединить в один запрос выборку из двух баз с одинаковой структурой |
118 | var co = 4; var sht = ""; sht = (co%2==0|co%3==0|co%4==0)?"товара":((co%10==1&&co!=11)?"товар":"товаров") | товаров, падежи | 120 | Слово товар, штука, единица по падежам |
119 | <?if("{PRICE_1}" > 0){?> <offer id="{ID}" type="vendor.model" available="<?=("{V_NALICHII_TEKST_53}">0)?"true":"false"?>"> <model><![CDATA[{NAZVANIE_2}]]></model> <url>https://posuda.lamaree.ru/catalog/full/{CAT_URL}/{ELEM_URL}/</url> <price><?=(float)"{PRICE_1}"?></price> <currencyId>RUR</currencyId> <categoryId>{CAT_ID}</categoryId> <delivery>true</delivery> <picture>https://posuda.lamaree.ru/images/products/big/{FOTO_DLYA_KATALOGA_13}</picture> <local_delivery_cost>350</local_delivery_cost> <typePrefix>{TITLE}</typePrefix> <description><![CDATA[{OPISANIE_22}]]></description> <vendor>La Maree</vendor> <param name="Артикул">{ARTIKUL_1}</param> <param name="Категория">{CAT_TITLE}</param> </offer> <?}?> | export, yml | 1345 | Экспорт yml |
120 | В файле bitrix/php_interface/dbconn.php нужно добавить строчку ini_set ("SMTP", "XXX.XXX.XXX.XXX"), где XXX.XXX.XXX.XXX - IP почтовика | smtp | 1670 | smtp |
121 | img.svg { clip-path: inset(0px 11px 0px 11px); } | clip-path | 3460 | Обрезка картинок |
122 | $component = new CBitrixComponent(); $component->InitComponent('redesign:menu', 'mobile'); $component->initComponentTemplate(); $path = $component->__template->GetFolder(); | путь к компоненту, битрикс, bitrix | 120 | Путь к шаблону компонента в папке components |
123 | RewriteCond %{THE_REQUEST} ^GET./index.php [NC] RewriteRule (.*?)index.php/*(.*) /$1$2 [R=301,NE,L] | rewrite cond | 450 | Если Битрикс сам не переводит с index.php на слеш, то пишут 2 такие строки. Но файл переиндексации ...reindex.php туда же попадает и выдает ошибку. Чтоб не выдавал, ставим GET./ (слеш, а не звездочку) |
124 | А я помню вот до сих пор. J3QQ4-H7H2V-2HCH4-M3HK8-6M8VW для меня прям как стих из молодости | виндоус код, windows code | 5600 | Вдруг пригодится |
125 | <img id='side-diag' src='/bitrix/templates/redesign/images/diagnostic2.jpg' srcset='/bitrix/templates/redesign/images/diagnostic1.jpg 2x' alt='Записаться на диагностику'/> | srcset | 300 | srcset |
126 | document.URL.split('/')[document.URL.split('/').length - 2] | url, js, last folder, последняя папка, яваскрипт | 120 | js найти последнюю папку в УРЛ |
127 | if (strlen($hip) > 120) { $pos = 160; $crop = $hip; if (strlen($crop) > 160) { $pos = strpos($hip, ".", 120) + 1; } $lip = substr($hip, 0, $pos); } | обрезать, по точке, crop name | 2360 | Обрезать описание до точки если оно длиннее 120 знаков |
128 | $current_time = strtotime("now"); $sunrise = strtotime("09:00"); $sunset = strtotime("21:00"); if ($current_time > $sunrise && $current_time < $sunset && date('w') > 0 && date('w') < 6) { ?><a href="https://wa.me/<?=(mob_detect())?"+":""?>74951233121" target="_blank" class="chat_social_item chat_social_wh"></a><? } else { ?><div style="display: none" id="wa_wi" data-info="<?=$current_time . ' ' . $sunrise . ' ' . $sunset?>">С 09:00 до 21:00</div><? } | whatsupp | 5600 | whatsupp widget |
129 | $("#add_object__form").submit(function(event) { if(!flagSubmit){ event.preventDefault(); city = $('#CITY option:selected').text(); address = $('#ADDRESS').val(); if(city != "" && address != "") { city = $.trim(city); address = $.trim(address); $.ajax({ /*получаем координаты по ajax*/ data: "&geocode=" + city + " " + address + "&results=1", url: "https://geocode-maps.yandex.ru/1.x/?format=json", dataType: 'json', success: function(data) { console.log(data); try { if (data.hasOwnProperty('statusCode')) { if (data.statusCode !== 200) { console.warn("Проблема с получением координат предприятия"); flagSubmit = true; $('#add_object__form').submit(); } } else { $("#MAP").val(data.response.GeoObjectCollection.featureMember[0].GeoObject.Point.pos.split(' ').reverse().join(',')); flagSubmit = true; $('#add_object__form').submit(); } } catch(e) { $("#MAP").val(''); } }, fail: function (data) { console.warn("Проблема с получением координат предприятия"); flagSubmit = true; $('#add_object__form').submit(); } }); } else { flagSubmit = true; $('#add_object__form').submit(); } | яндекс геокод, yandex geocode | 120 | Нужен рабочий АПИ ключ |
130 | $fr = fopen("log_site_users.txt", "w+"); fwrite($fr, $result . " "); fclose($fr); | fwrite, запись в файл | 2300 | Запись лога в файл php |
131 | <? $APPLICATION->IncludeFile( SITE_TEMPLATE_PATH . "/bespl_kons.php", Array(), Array( "MODE" => "html" ) ); ?> | include, bitrix, включаемая область | 90 | Вставка включаемой области из html файла в Битрикс |
132 | <body class="<?=array_splice(explode('/', htmlspecialchars($_SERVER['PHP_SELF'])),-2,1)[0]?>"> | класс, класс для body | 1090 | Присвоить тегу body class с названием текущей папки в адресе страницы |
133 | <meta charset="utf-8"/> <center style="font-size:54px; font-family:Arial"> <h1>Кот на баяне</h1> (\_/)<br> (='.'=)<br> <span style="transform: rotateY(180deg);position: relative;display: inline-block;">3</span>[:]|||||[:]3<br> (")_(") </center> | кот, баян | 260 | Кот на баяне |
134 | WP ошибка: Функция has_cap вызвана с устаревшим аргументом. Ошибка в плагине rus_to_lat. В rus-to-lat.php в функции rtl_add_menu заменить 8 на 'edit_pages' | has_cap, WP | 230 | Вордпресс ошибка has_cap |
135 | SELECT * FROM int_posts p, int_postmeta m WHERE p.post_title LIKE '%Чикина%' AND p.post_type = 'page' AND (p.post_status = 'publish' OR p.post_status = 'private') AND p.ID = m.post_id | wp, sql, часть названия | 9800 | SQL запрос WP выборки записи (страницы) по слову из названия |
136 | /bitrix/admin/perfmon_table.php?lang=ru&table_name=b_event | mail list, список писем битрикс | 1350 | Адрес для списка писем Битрикс |
137 | if ($('#phone_inp').val().length){ var ph = $('#phone_inp').val().replace(/[^0-9.]/g, ""); if(ph.length == 11) { | телефон, цифры, digits, phone number, js | 130 | Проверка телефона на число заполненных цифр |
138 | var dayArr1 = $('.order-form input[name="user_f_9_2"]').val().split('.'); var dFor1 = dayArr1[1] + '-' + dayArr1[0] + '-' + '20' + dayArr1[2]; | covert date, js date | 9800 | Конвертировать дату в яваскрипт формат |
139 | <div class="itogo">Итого: <?=$pos?> <?=(in_array($pos % 10, array(2, 3, 4)) && $pos < 10 ) ? "позиции" : ($pos == 1 ? "позиция" : "позиций")?></div> | 10 позиций | 2090 | Множественное по-русски позиций |
140 | Производите подключение по SSH. Выполняете следующие команды: 1) wget http://ru2.php.net/get/php-5.2.11.tar.bz2/from/ru.php.net/mirror 2) tar -xjvf php-5.2.11.tar.bz2 3) cd php-5.2.11 ./configure --prefix=/storage/home/srvXXX/php --with-mysql=/usr/local --with-gd=/usr/local --enable-fastcgi 4) make make install 6) cp /storage/home/srvXXX/php/bin/php-cgi /storage/home/srvXXX/cgi-bin/php 7) chmod 755 /storage/home/srvXXX/cgi-bin/php 8) скопировать из /storage/home/srvXXX/php/etc/ - дистрибутивный php.ini файл и разместить в директорию /storage/home/srvXXX/cgi-bin/php.ini в файл .htaccess добавляете следующие директивы: Action php-script /cgi-bin/php AddHandler php-script .php | php cgi | 1390 | Настроить php через cgi |
141 | <?="<p>".implode("<p>", explode("|",$arResult['DETAIL_TEXT']))?> | разбить, explode | 9080 | Если нужно разбить текст по символу и вывести объединенный по другому символу |
142 | array("LOGIC"=>"OR","NAME"=>$q,"PREVIEW_TEXT"=>$q, "PROPERTY_CML2_ARTIKUL"=>$q), | фильтр с логикой, логика, битрикс, bitrix, logic | 500 | Фильтр с логикой в Битрикс |
143 | array_reverse(explode("/", $_SERVER['REQUEST_URI']))[1]; | last folder, последняя папка в УРЛ | 450 | Последняя папка в адресе УРЛ (URL) |
144 | $iterator = CIBlockElement::GetList( array(), array('IBLOCK_ID' => 2, '=AVAILABLE' => 'Y', '=TYPE' => 1, '>=PRICE' => 100, '<=PRICE' => 200, 'CURRENCY_FOR_SCALE' => 'USD'), false, false, array('ID', 'NAME', 'IBLOCK_ID') ); | итератор, iterator bitrix, iterator | 140 | Выборка элементов Битрикс из каталога или другого инфоблока. Итерация. |
145 | Ключ Описание TYPE Тип товара. Значения: 1 - Простой товар 2 - Комплект 3 - Товар с предложением 4 - Предложение AVAILABLE Доступность. BUNDLE Наличие набора. QUANTITY Доступное количество. QUANTITY_RESERVED Зарезервированное количество. QUANTITY_TRACE Включен количественный учет (с учетом значения "по умолчанию" в настройках модуля) - Y/N. QUANTITY_TRACE_RAW Включен количественный учет (необработанное значение) - Y/N/D. CAN_BUY_ZERO Разрешена покупка «в минус» (с учетом значения "по умолчанию" в настройках модуля) - Y/N. CAN_BUY_ZERO_RAW Разрешена покупка «в минус» (необработанное значение) - Y/N/D. SUBSCRIBE Разрешена подписка на уведомления о поступлении товара (с учетом значения "по умолчанию" в настройках модуля) - Y/N. SUBSCRIBE_RAW Разрешена подписка на уведомления о поступлении товара (необработанное значение) - Y/N/D. VAT_ID Идентификатор НДС товара. VAT_INCLUDED Признак «НДС включен в цену». PURCHASING_PRICE Закупочная цена. PURCHASING_CURRENCY Валюта закупочной цены. BARCODE_MULTI Множественность штрихкодов. WEIGHT Вес. WIDTH Ширина. LENGTH Длина. HEIGHT Высота. MEASURE Идентификатор единицы измерения. PAYMENT_TYPE Для продажи подписки. RECUR_SCHEME_LENGTH Для продажи подписки. RECUR_SCHEME_TYPE Для продажи подписки. TRIAL_PRICE_ID Для продажи подписки. WITHOUT_ORDER Для продажи подписки. | поля, товар, битрикс | 1300 | Поля товара Битрикс каталога |
146 | <?if($r['Stats']['ReviewsTotalCount'] > 10){?> <div class="pagination"> <ul> <?$tot = $r['Stats']['ReviewsTotalCount']; $page = htmlspecialchars($_REQUEST['page'],3) ; $pes = ceil($tot / 10); for($p=1; $p<=$pes; $p++){?> <li class="<?=($p==$page)?'active':''?>"><a href="/otzyvy/?page=<?=$p?>" rel="nofollow"><?=$p?></a></li> <?}?> </ul> </div> <?}?> | пагинация, pagination, php | 10290 | Php скрипт пагинации |
147 | $r = str_replace("ʹ", "", transliterator_transliterate('Any-Latin; Latin-ASCII', "Пробежаться на травалотре")); echo $r; | транслитератор, php, translit | 1470 | Транслитератор на php |
148 | $arFilter = Array("IBLOCK_ID"=>GOODS, "ACTIVE_DATE"=>"Y", "ACTIVE"=>"Y", "=PROPERTY_CML2_ARTIKUL_VALUE"=>$p_title); | bitrix filter value, filter bx, value | 1290 | Свойство элемента в Битрикс фильтре |
149 | <?$APPLICATION->IncludeFile(SITE_DIR."catalog/sidebar_".$arResult['ID'].".php",Array(),Array("MODE"=>"php"));?> | include, bitrix, включаемая область | 120 | Включаемая область |
150 | function find_wrap($string, $search){ $out = ""; $pos = 0; if(strpos(" " . $string, $search) > 0){ $in = str_replace($search, "<b>".$search."</b>", strip_tags($string)); $wordToFind = $search; $numWordsBefore = 3; $numWordsAfter = 10; $words = preg_split('/s+/', $in); $found_words = preg_grep("/^".$wordToFind.".*/", $words); $found_pos = array_keys($found_words); if(count($found_pos)) { $pos = $found_pos[0]; } if (isset($pos)) { $start = ($pos - $numWordsBefore > 0) ? $pos - $numWordsBefore : 0; $length = (($pos + ($numWordsAfter + 1) < count($words)) ? $pos + ($numWordsAfter + 1) : count($words) - 1) - $start; $slice = array_slice($words, $start, $length); $pre_start = ($start > 0) ? "...":""; $post_end = ($pos + ($numWordsAfter + 1) < count($words)) ? "...":""; $out = $pre_start.implode(' ', $slice).$post_end; } } return $out; } | wrap, фраза текста, поиск | 3400 | Возвращает искомое слово из текста плюс 3 слова до и 10 слов после |
151 | -webkit-hyphens: auto; hyphens: auto; | css, перенос, hyphens | 123 | Расстановка переносов в блоке css |
152 | $('[name=docviewer]').show(200, function(){$(document).on('click', function(e){ $("#docviewer").hide() })}); | iframe close, закрыть iframe | 10900 | После показа iframe закрыть его по щелчку снаружи |
153 | print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); выведет 1988-08-01 | печать даты, php | 5900 | Печать даты в php |
154 | AddEventHandler("main", "OnEndBufferContent", "ShowAuthorInsideNews"); function ShowAuthorInsideNews(&$content) { if (CModule::IncludeModule("iblock")) { if (strpos($content, '#YAKUBOV#') !== false) { $content = str_replace('#YAKUBOV#', author(), $content); } } } | функция, текст, инфоблок | 1340 | Обратотка вставки функции автора статьи. Когда в детальный текст инфоблока надо вставить функцию |
155 | a:focus { outline: 3px solid transparent; color: #0b0c0c; background-color: #ffdd00; box-shadow: 0 -2px #ffdd00, 0 4px #0b0c0c; text-decoration: none; } | ссылка, оформление | 120 | Очень смешное оформление ссылок |
156 | basename(__DIR__) | php, родительская папка, parent folder | 120 | одительская папка php текущей директории без начального слеш |
157 | <?$name = substr($arItem['PREVIEW_TEXT'], strpos($arItem['PREVIEW_TEXT'], "<b>") + 3, strpos($arItem['PREVIEW_TEXT'], "</b>") - strpos($arItem['PREVIEW_TEXT'], "<b>") - 3)?> | substr | 10900 | Часть строки между символами <b> и </b> |
158 | RewriteRule ^receipt/(.+)/$ receipt/full.php?tag=$1 [L] | редирект, строка на папку | 10970 | Перевод в htaccess с get параметра на папку и садресом |
159 | function lat2cyr($s) { $sb = ""; $i = 0; $lc = false; while ($i < strlen($s)) { $ch = substr($s, $i, 1); $lc = ctype_lower($ch); // true/false $ch = mb_strtoupper($ch); if ($ch == 'J') { // Префиксная нотация вначале $i++; // преходим ко второму символу сочетания $ch = strtoupper(substr($s, $i, 1)); switch ($ch) { case 'O': $sb .= ch('Ё', $lc); break; case 'H': if ($i + 1 < strlen($s) && mb_strtoupper(substr($s, $i + 1, 1) == 'H')){ // проверка на постфикс (вариант JHH) $sb .= ch('Ъ', $lc); $i++; // пропускаем постфикс } else{ $sb .= ch('Ь', $lc); } break; case 'U': $sb .= ch('Ю', $lc); break; case 'A': $sb = ch('Я', $lc); break; default: break; } } else if ($i + 1 < strlen($s) && mb_strtoupper(substr($s, $i + 1, 1)) == 'H') { // Постфиксная нотация, требует информации о двух следующих символах. Для потока придется сделать обертку с очередью из трех символов. switch ($ch) { case 'Z': $sb .= ch('Ж', $lc); break; case 'K': $sb .= ch('Х', $lc); break; case 'C': $sb .= ch('Ч', $lc); break; case 'S': if ($i + 2 < strlen($s) && mb_strtoupper(substr($s, $i + 2, 1)) == 'H') { // проверка на двойной постфикс $sb .= ch('Щ', $lc); $i++; // пропускаем первый постфикс } else { $sb .= ch('Ш', $lc); } break; case 'E': $sb .= ch('Э', $lc); break; case 'I': $sb .= ch('Ы', $lc); break; default: break; } $i++; // пропускаем постфикс } else {// одиночные символы switch ($ch) { case 'A': $sb .= ch('А', $lc); break; case 'B': $sb .= ch('Б', $lc); break; case 'V': $sb .= ch('В', $lc); break; case 'G': $sb .= ch('Г', $lc); break; case 'D': $sb .= ch('Д', $lc); break; case 'E': $sb .= ch('Е', $lc); break; case 'Z': $sb .= ch('З', $lc); break; case 'I': $sb .= ch('И', $lc); break; case 'Y': if (mb_strtoupper(substr($s, $i + 1, 1) === ' ')){ // проверка на пробел после Y $sb .= ch('И', $lc); $i++; // пропускаем постфикс } else{ $sb .= ch('Й', $lc); } break; case 'K': $sb .= ch('К', $lc); break; case 'L': $sb .= ch('Л', $lc); break; case 'M': $sb .= ch('М', $lc); break; case 'N': $sb .= ch('Н', $lc); break; case 'O': $sb .= ch('О', $lc); break; case 'P': $sb .= ch('П', $lc); break; case 'R': $sb .= ch('Р', $lc); break; case 'S': $sb .= ch('С', $lc); break; case 'T': $sb .= ch('Т', $lc); break; case 'U': $sb .= ch('У', $lc); break; case 'F': $sb .= ch('Ф', $lc); break; case 'C': $sb .= ch('Ц', $lc); break; default: $sb .= ch($ch, $lc); } } $i++; // переходим к следующему символу } return (string)$sb; } function cyrlat($ch) { switch ($ch) { case 'А': return "A"; case 'Б': return "B"; case 'В': return "V"; case 'Г': return "G"; case 'Д': return "D"; case 'Е': return "E"; case 'Ё': return "JO"; case 'Ж': return "ZH"; case 'З': return "Z"; case 'И': return "I"; case 'Й': return "Y"; case 'К': return "K"; case 'Л': return "L"; case 'М': return "M"; case 'Н': return "N"; case 'О': return "O"; case 'П': return "P"; case 'Р': return "R"; case 'С': return "S"; case 'Т': return "T"; case 'У': return "U"; case 'Ф': return "F"; case 'Х': return "KH"; case 'Ц': return "C"; case 'Ч': return "CH"; case 'Ш': return "SH"; case 'Щ': return "SHH"; case 'Ъ': return "JHH"; case 'Ы': return "IH"; case 'Ь': return "JH"; case 'Э': return "EH"; case 'Ю': return "JU"; case 'Я': return "JA"; default: return $ch; } } function cyr2lat($s) { $sb = ""; $ch = preg_split('//u', $s, null, PREG_SPLIT_NO_EMPTY); for ($i = 0; $i < count($ch); $i++) { $lc = preg_match('~^p{Lu}~u', $ch[$i]) ? 0 : 1; $v = $ch[$i]; $l = mb_strtoupper($v); $c = cyrlat($l); $lat = ch($c, $lc); $sb .= $lat; } return $sb; } /** * Вспомогательная функция для восстановления регистра */ function ch($ch, $tolower) { return $tolower ? mb_strtolower($ch) : mb_strtoupper($ch); } echo cyr2lat("провинции Арма") . " "; echo lat2cyr("Provinces of Lightness") . " "; | транслит, ретранслит | 100 | Транслит русско-латинский, латинско-русский |
160 | Было так $layout->addField('', new sbLayoutDelim()); Нужно для php7 исправить $layout(.*), new sbLayout(.*)((.*))); $l = new sbLayout$2($3); $layout$1, $l); | замена, sbuilder | 1500 | заменить первое на второе при редактировании нотисов php7 в сбилдер |
161 | function price($path, $part){ $file = fopen($path, "r"); $text = fread($file, filesize($path)); $lines = explode(PHP_EOL, $text); $v = false; $str = "<table>"; foreach ($lines as $i=>$line) { if (strpos($line, $part)) { $v = true; continue; } if(strpos($line, ";") > 2 && $v == true){ $l = explode(";", $line); $str .= "<tr><td>" . $l[0] . "</td><td>" . $l[1] . "</td></tr>"; } if(strpos($line, ";") === false && $v == true){ $str .= "<tr><th colspan='2'>" . $line . "</th></tr>"; } if (strpos(" ".$line, ";;") > 0 && $v == true) { $v = false; break; } } $str .= "</table>"; return $str; } | прайс, price, функция прайс | 10900 | Функция постройки прайса таблицы по текстовой таблице в файле |
162 | li:not(:last-child):not(:first-child) | ни первый ни послеадний, css | 100200 | ни первый ни послеадний из скписка |
163 | function string_clip($string, $length) { $string = preg_replace( "/ | /", "", strip_tags($string)); $string = explode(" ", $string); $string = array_slice($string, 0, $length); return implode(" ", $string); } | crop string | 1390 | Обрезать текст по числу слов |
164 | for messages_count in range(0, 100): remainder = messages_count % 10 if messages_count == 0: print('У вас нет новых сообщений') elif messages_count == 1 or (remainder == 1 and messages_count > 11): print('У вас ' + str(messages_count) + ' новое сообщение') elif (messages_count >= 2 and messages_count <= 4) or (remainder > 1 and remainder < 5 and messages_count > 20): print('У вас ' + str(messages_count) + ' новых сообщения') else: print('У вас ' + str(messages_count) + ' новых сообщений') | склонения чисел | 120 | Если 2, 3 или 4 – то сообщения, иначе сообщений |
165 | <link rel="canonical" href="<?= substr(strtolower($_SERVER['REQUEST_URI']), 0, strrpos($_SERVER['REQUEST_URI'], '/') + 1) ?>"/> | каноникал, canoncal | 90 | Сделать rel каноникал в php |
166 | <script> document.addEventListener("touchstart", function(e) { console.log(e.defaultPrevented); // will be false e.preventDefault(); // does nothing since the listener is passive console.log(e.defaultPrevented); // still false }, Modernizr.passiveeventlisteners ? {passive: true} : false); </script> | touchstart,passive,js | 100 | Пассивный ивент листнер |
167 | document.addEventListener("DOMContentLoaded", function (event) { setTimeout(function() { document.querySelectorAll('*').forEach.call( document.querySelectorAll('img[data-src]'), function (img) { img.setAttribute('src', img.getAttribute('data-src')); img.onload = function () { img.removeAttribute('data-src'); }; }); },200); }); | отложенная, загрузка | 120 | Отложенная загрузка изображений |
168 | add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' ); function custom_override_checkout_fields( $fields ) { //unset($fields['billing']['billing_first_name']);// имя unset($fields['billing']['billing_last_name']);// фамилия unset($fields['billing']['billing_company']); // компания unset($fields['billing']['billing_address_1']);// unset($fields['billing']['billing_address_2']);// unset($fields['billing']['billing_city']); unset($fields['billing']['billing_postcode']); unset($fields['billing']['billing_country']); unset($fields['billing']['billing_state']); //unset($fields['billing']['billing_phone']); //unset($fields['order']['order_comments']); //unset($fields['billing']['billing_email']); //unset($fields['account']['account_username']); //unset($fields['account']['account_password']); //unset($fields['account']['account_password-2']); unset($fields['billing']['billing_company']);// компания unset($fields['billing']['billing_postcode']);// индекс return $fields; } | woocommerce, лишние поля | 3400 | Удалить лишние поля для оформления заказа на woocommerce |
169 | /* javascript url кодирует сорсы всех картинок */ var arr = document.querySelectorAll('img') arr.forEach(function(item, i, arr) { var uri = arr[i].src; var encoded = encodeURI(uri); arr[i].src = encoded; }); | urlencode, имена картинок | 10090 | url кодировать все файлы картинок javascript |
170 | /bitrix/admin/perfmon_table.php?PAGEN_1=1&SIZEN_1=20&lang=ru&table_name=b_event&by=DATE_INSERT&order=desc | битрикс, отправленные письма | 11020 | Список отправленных писем в Битрикс |
171 | http://example.com/?_ym_debug=1 | метрика, counter test, проверка | 12300 | Проверка счетчиков и событий метрики в консоли |
172 | <span style="color: #999999; font-size: 10px;">Вы можете <a href="https://shop.lamaree.ru/disable_email/index.php?e=' . $su_email . '&s=' . $su_id . '" rel="noopener" style="text-decoration: underline; color: #0068A5;" target="_blank" title="отписаться">отписаться</a> от рассылки</span> | отписка от рассылки | 120 | отписка от рассылки ламаре |
173 | <?$arText = explode('#MY_COMPONENT#',$arResult['DETAIL_TEXT']); for($i=0;$i<count($arText);$i++) { echo $arText[$i]; if ($i>0) $APPLICATION->IncludeComponent('my:my_component',''); }?> | код в статью битрикс | 435 | Вставка кода в статью Битрикс |
174 | function find_closed() { //clearTimeout(typingTimer); //typingTimer = setTimeout(doneTyping, doneTypingInterval); var found; var tr = jQuery('.pricing tr'); var pos = jQuery('body, html').scrollTop(); var s = jQuery('#searchfield').val(); //var add = jQuery('.prices').first().position().top; var old, i, cont; if(s.length > 2) { old = jQuery('.found_color').parents('td'); jQuery.each(old, function(){ cont = jQuery(this).text(); old.text(cont); }); jQuery('tr').removeClass('found'); for (i = 0; i < tr.length; i++) { if (tr.eq(i).text().toLowerCase().indexOf(s.toLowerCase()) > -1) { tr.eq(i).addClass('opened found'); var text = tr.eq(i).children('td:first-child').text().replace(s, '<span class=found_color>' + s + '</span>'); //console.log(text); tr.eq(i).children('td:first-child').html(text); found = 1; }else{ //tr.eq(i).remove(); tr.eq(i).removeClass('opened'); tr.eq(i).removeClass('found'); } } if(jQuery('.found').length){ var E = setTimeout(function(){ pos += jQuery('.found').first().parents('table').position().top; jQuery('body, html').animate({scrollTop: pos}, 300, 'swing'); console.log(pos); },300); } if (found < 1) { jQuery('.not-found').text('Не найдено на этой странице. Поищите через общий поиск') } } } | найти в скрытом аккордионе | 12300 | find_closed с подстветкой |
175 | <script> document.addEventListener('touchstart', this.callPassedFuntion, {passive: false}); </script> | passive, false | 120 | Про passive false |
176 | В htaccess добавить <IfModule mod_headers.c> <FilesMatch ".(ttf|ttc|otf|eot|woff|woff2|font.css|css|js)$"> Header set Access-Control-Allow-Origin "*" </FilesMatch> </IfModule> | cors, allow origin | 100600 | No Access-Control-Allow-Origin header при подключении шрифтов |
177 | <script type="text/javascript">$(document).ready(function () { var div = $("#rec241218811").find(".t-video-lazyload"); var iframe = div.find('iframe'); var height = div.width() * 0.5625; div.height(height); iframe.height(height); $('.t223').bind('displayChanged', function () { height = div.width() * 0.5625; div.height(height); iframe.height(height); }); $(window).bind('scroll', t_throttle(function () { height = div.width() * 0.5625; div.height(height); iframe.height(height); }, 200)); });</script> | lazyload, youtube | 90890 | Лэйзилоуд для ютьюб роликов на страницу |
178 | [checkbox* checkbox-41 id:agree-2 class:agree label_first use_label_element "Да"] | согласие, чекбокс | 34090 | Чекбокс согласия в contact forms 7 |
179 | $connection = BitrixMainApplication::getConnection(); $sqlHelper = $connection->getSqlHelper(); $recordset = $connection->query("SELECT * FROM dbname"); while ($record = $recordset->fetch()){ ... } | d7 активация, битрикс | 1300 | Активировать в7 на конкретной странице |
180 | https://marketplace.1c-bitrix.ru/solutions/bitrix.liveapi/ | модуль, битрикс, API | 100 | Ссылка на Живое описание API Битрикс. Механизм сканирует все модули Битрикс и выводит все методы этих модулей. Можно посмотреть, какие возможности у каждого модуля! |
181 | SELECT * FROM shoutbox WHERE CONCAT(name, foo, bar, baz) LIKE '%$search%' | поиск, mysql, по колонкам | 340900 | Поиск по нескольким колонкам |
182 | <? $today = new DateTime(); $begin = new DateTime('January 01'); $ny1 = new DateTime('December 20'); $ny2 = new DateTime('January 8'); $spring = new DateTime('March 01'); $summer = new DateTime('June 01'); $fall = new DateTime('September 01'); $winter = new DateTime('December 01'); switch (true) { case $today >= $ny1 || $today < $ny2: echo 'Новогоднее настроение'; break; case ($today >= $winter || $today >= $begin) && $today < $spring: echo 'Зимнее настроение'; break; case $today >= $spring && $today < $summer: echo 'Весеннее настроение'; break; case $today >= $summer && $today < $fall: echo 'Летнее настроение'; break; case $today >= $fall && $today < $winter: echo 'Осеннее настроение'; break; default: break; } ?> | зимнее, весеннее | 100 | зимнее или весеннее |
183 | if (mob_detect()) { $APPLICATION->AddHeadString("<style>.wrap center img {margin-bottom: 2em;}</style>"); } | битрикс, header, строка | 9800 | Добавить произвольную строку в заголовок Битрикс |
184 | <span class="mc-stars" style="display:none"> <span class="mc-star" data-origin="star_o" data-color="#ffaf02" data-star="1" data-hover=""> <svg width="24" height="24" viewBox="0 0 1792 1792"><path d="M1201 1004l306-297-422-62-189-382-189 382-422 62 306 297-73 421 378-199 377 199zm527-357q0 22-26 48l-363 354 86 500q1 7 1 20 0 50-41 50-19 0-40-12l-449-236-449 236q-22 12-40 12-21 0-31.5-14.5t-10.5-35.5q0-6 2-20l86-500-364-354q-25-27-25-48 0-37 56-46l502-73 225-455q19-41 49-41t49 41l225 455 502 73q56 9 56 46z" fill="#ffaf02"></path></svg></span><span class="mc-star" data-origin="star_o" data-color="#ffaf02" data-star="2" data-hover=""> <svg width="24" height="24" viewBox="0 0 1792 1792"><path d="M1201 1004l306-297-422-62-189-382-189 382-422 62 306 297-73 421 378-199 377 199zm527-357q0 22-26 48l-363 354 86 500q1 7 1 20 0 50-41 50-19 0-40-12l-449-236-449 236q-22 12-40 12-21 0-31.5-14.5t-10.5-35.5q0-6 2-20l86-500-364-354q-25-27-25-48 0-37 56-46l502-73 225-455q19-41 49-41t49 41l225 455 502 73q56 9 56 46z" fill="#ffaf02"></path></svg></span><span class="mc-star" data-origin="star_o" data-color="#ffaf02" data-star="3" data-hover=""> <svg width="24" height="24" viewBox="0 0 1792 1792"><path d="M1201 1004l306-297-422-62-189-382-189 382-422 62 306 297-73 421 378-199 377 199zm527-357q0 22-26 48l-363 354 86 500q1 7 1 20 0 50-41 50-19 0-40-12l-449-236-449 236q-22 12-40 12-21 0-31.5-14.5t-10.5-35.5q0-6 2-20l86-500-364-354q-25-27-25-48 0-37 56-46l502-73 225-455q19-41 49-41t49 41l225 455 502 73q56 9 56 46z" fill="#ffaf02"></path></svg></span><span class="mc-star" data-origin="star_o" data-color="#ffaf02" data-star="4" data-hover=""> <svg width="24" height="24" viewBox="0 0 1792 1792"><path d="M1201 1004l306-297-422-62-189-382-189 382-422 62 306 297-73 421 378-199 377 199zm527-357q0 22-26 48l-363 354 86 500q1 7 1 20 0 50-41 50-19 0-40-12l-449-236-449 236q-22 12-40 12-21 0-31.5-14.5t-10.5-35.5q0-6 2-20l86-500-364-354q-25-27-25-48 0-37 56-46l502-73 225-455q19-41 49-41t49 41l225 455 502 73q56 9 56 46z" fill="#ffaf02"></path></svg></span><span class="mc-star" data-origin="star_o" data-color="#ffaf02" data-star="5" data-hover=""> <svg width="24" height="24" viewBox="0 0 1792 1792"><path d="M1201 1004l306-297-422-62-189-382-189 382-422 62 306 297-73 421 378-199 377 199zm527-357q0 22-26 48l-363 354 86 500q1 7 1 20 0 50-41 50-19 0-40-12l-449-236-449 236q-22 12-40 12-21 0-31.5-14.5t-10.5-35.5q0-6 2-20l86-500-364-354q-25-27-25-48 0-37 56-46l502-73 225-455q19-41 49-41t49 41l225 455 502 73q56 9 56 46z" fill="#ffaf02"></path></svg></span></span> | рейтинг, 5 звезд | 130900 | рейтинг в 5 пустых звезд |
185 | net user User_name * | пароль, сменить, cmd | 120 | Чтобы сменить пароль юзера в винде надо 5 раз нажать Shift, вызвать перезагрузку, открыть любую прогу дать sethc.exe другое имя и переименовать cmd.exe в sethc.exe. Перезагрузиться и 5 Shift вызвать cmd. Там задать эту команду, чтобы сбросить пароль Юзера |
186 | if((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443){ $protocol = 'https://'; }else{ $protocol = 'http://'; } $url = $protocol.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; $urlend = strrpos($url, '?', -1); // Находим и удаляем все параметры (номер страницы, параметры фильтра и тд.) if($urlend != false){ $url = substr($url, 0, $urlend); } if(mb_substr($url, -1) == '/'){ // Тут оставляем, если ссылки на сайте не заканчиваются на /, либо удаляем, если заканчиваются на /. $url = substr($url, 0, -1); } echo '<link rel="canonical" href="'.$url.'"/>'; | php, canonical | 32090 | php link rel canonical |
187 | <script src="<?=$scheme?>://api-maps.yandex.ru/2.1.50/?load=package.full&lang=<?=$locale?>"></script> | Яндекс карта, битрикс | 120 | Яндекс-карты адрес из Битрикса |
188 | var hr = $('body').find('.popup_image') hr.each(function(){ console.log($(this).attr('href') + ' ' + $(this).attr('title')); }) | парсинг js | 100 | Парсинг ссылок яваскриптом |
189 | "SHOW_ALL_WO_SECTION" => "Y" | ссылки, каталог, битрикс | 120 | При включении параметра "SHOW_ALL_WO_SECTION" ситуация меняется. Ссылки начинают формироваться в соответствии с ID группы, заданной для элемента в таблице `b_iblock_element`. В каталоге в секции все хорошо, а в каталоге-корне – ссылка на товар ведет не на товар, а на 404 без секции. |
190 | <script> $(document).ready(function(){ function getRemanningDays() { var date = new Date(); var time = new Date(date.getTime()); time.setMonth(date.getMonth() + 1); time.setDate(0); var days = time.getDate() > date.getDate() ? time.getDate() - date.getDate() : 0; return days; } setInterval(function(){ let dateNow = new Date(); let lastDate = new Date(new Date().getFullYear(), new Date().getMonth() + 2, 0).getDate(); let mon = dateNow.getMonth(); let monthNames = [ "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря" ]; if($('[field="tn_text_1620984661425"]').length){ let text = $('[field="tn_text_1620984661425"]').text(); let part = text.substr(18); let now = new Date(); let new_text = 'Акция действует до '; if(getRemanningDays() < 15){ new_text = new_text + lastDate + " " + monthNames[dateNow.getMonth() + 1]; $('[field="tn_text_1620984661425"]').text(new_text); } } }, 1000); }) </script> | до конча месяца, изменить дату, js | 200 | Акция если до конца месяца менее 10 дней, то акция продляется до конца следующего месяца |
191 | /** обратотка вставки функции автора статьи AddEventHandler("main", "OnEndBufferContent", "ShowVideoInsideNews"); function ShowVideoInsideNews(&$content) { if (CModule::IncludeModule("iblock")) { if (strpos($content, '#VIDEO_INS#') !== false) { $content = str_replace('#VIDEO_INS#', video_ins(), $youtube_id); } } } */ | статья, сниппет, Битрикс | 120 | обратотка вставки функции автора статьи в статью Битрикс |
192 | <meta itemprop="uploadDate" content="'.date("Y-m-d H:i:s", filemtime(__FILE__)).'"/> | meta, uploadDate | 500 | Правильное указание uploadDate для мета видео |
193 | RedirectMatch 301 /(.*)/$ /$1.html | редирект, html | 560 | Редирект с папки на файл .html |
194 | <url>(.*)([^/]+)</loc>(.*)</url> | regexp | 19010 | Заменить строки, где loc оканчивается без слэша в файле sitemap.xml |
195 | include_once($root . 'getID3/getid3/getid3.php'); $getID3 = new getID3; $file = $getID3->analyze($root . $file_src); #echo("Duration: ".$file['playtime_string']. #" / Dimensions: ".$file['video']['resolution_x']." wide by ".$file['video']['resolution_y']." tall". #" / Filesize: ".$file['filesize']." bytes<br />"); | gd3, анализ видео | 12010 | Анализ длительности, ширины, высоты видео |
196 | SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dlmlru_betashop' AND TABLE_NAME = 'sb_plugins_2' | autoincrement, автоинкремент | 120 | Получить авоинкремент из таблицы базы данных |
197 | let d = new Date(); let m = String(d.getMonth() + 1).padStart(2, '0'); | js,javascript,month with 0,month with zero | 340 | В яваскрипте получить месяц номер с ведущим нулём |
198 | function setCookie(name,value,days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'; } | куки, cookie | 120 | Постановка, уаделние кук Яваскрипт |
199 | function maskPhone(selector, masked = '+7 (___) ___-__-__') { const elems = document.querySelectorAll(selector); function mask(event) { const keyCode = event.keyCode; const template = masked, def = template.replace(/D/g, ""), val = this.value.replace(/D/g, ""); let i = 0, newValue = template.replace(/[_d]/g, function (a) { return i < val.length ? val.charAt(i++) || def.charAt(i) : a; }); i = newValue.indexOf("_"); if (i !== -1) { newValue = newValue.slice(0, i); } let reg = template.substr(0, this.value.length).replace(/_+/g, function (a) { return "\d{1," + a.length + "}"; }).replace(/[+()]/g, "\$&"); reg = new RegExp("^" + reg + "$"); if (!reg.test(this.value) || this.value.length < 5 || keyCode > 47 && keyCode < 58) { this.value = newValue; } if (event.type === "blur" && this.value.length < 5) { this.value = ""; } } for (const elem of elems) { elem.addEventListener("input", mask); elem.addEventListener("focus", mask); elem.addEventListener("blur", mask); } } maskPhone('input[type=tel]'); | маска телефона | 12009 | Скрипт JS маски телефона |
200 | "CUSTOM_FILTER" => "{"CLASS_ID":"CondGroup","DATA":{"All":"AND","True":"True"},"CHILDREN":[{"CLASS_ID":"CondIBSection","DATA":{"logic":"Equal","value":995}}]}", | custom filter, bitrix | 100 | Пример заполнения custom_filter в Битрикс |
201 | function send(onError, onSuccess, url, method = 'GET', data = null, headers = [], timeout = 60000) { let xhr; if (window.XMLHttpRequest) { // Chrome, Mozilla, Opera, Safari xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Internet Explorer xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open(method, url, true); headers.forEach((header) => { xhr.setRequestHeader(header.key, header.value); }) xhr.timeout = timeout; xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if(xhr.status >= 400) { onError(xhr.statusText) } else { onSuccess(xhr.responseText) } } } xhr.send(data); } | xhr, request, XMLHttpRequest, JS | 12090 | XMLHttpRequest обернутый в функцию |
202 | /^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?$/ | regexp, url, JS | 1300 | Регулярное выражение для проверки URL |
203 | /^([a-z0-9_.-]+)@([a-z0-9_.-]+).([a-z.]{2,6})$/ | regexp, email. JS | 14800 | Регулярное выражение для проверки email |
204 | var p1 = Promise.resolve(3); var p2 = 1337; var p3 = new Promise((resolve, reject) => { setTimeout(resolve, 100, "foo"); }); Promise.all([p1, p2, p3]).then(values => { console.log(values); }); | Promise, JS | 10900 | Промис яваскрипт |
205 | function flog($fname, $ftext, $write_a_w_state = null){ if(!$write_a_w_state) $write_a_w_state = "a+"; $fp = fopen("/home/d/dlmlru/posuda/public_html/log/" . $fname, $write_a_w_state); fwrite($fp, date("Y-m-d H:i:s ") . $ftext . " "); fclose($fp); } | flog | 12090 | функция логирования php |
206 | const add = (a) => (b) => a + b; console.log (add(3)(2)) | js, двойная функция | 100 | Пример двойной функции в Яваскрипт |
207 | $posts = get_posts ("category=11&orderby=date&numberposts=5"); if ($posts) : $i=1; foreach ($posts as $post) : setup_postdata ($post); $i++; endforeach; endif; | get_posts, wp | 1290 | Получить посты по запросу из Вордпресс |
208 | https://view.officeapps.live.com/op/view.aspx?src=https://site.com/price/price.xlsx | просмотр эксель, excel в браузере | 100 | Ссылка на просмотр файла эксель в браузере на сайте Майкрософт https://view.officeapps.live.com |
209 | const generateMinsRange = (min, max) => { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }; | интервал, минуты | 1000043 | сгенерить произвольно несколько минут или секунд в пределах от и до |
210 | return ($month === 12 && $day >= 15) || ($month === 1 && $day < 10); | новый год, php | 20090 | Вернёт true если новогодние праздники близко |
211 | let worker = { slow(min, max) { alert(`Called with ${min},${max}`); return min + max; } }; function cachingDecorator(func, hash) { let cache = new Map(); return function() { let key = hash(arguments); // (*) if (cache.has(key)) { return cache.get(key); } let result = func.call(this, ...arguments); // (**) cache.set(key, result); return result; }; } function hash(args) { return args[0] + ',' + args[1]; } worker.slow = cachingDecorator(worker.slow, hash); alert( worker.slow(3, 5) ); // работает alert( "Again " + worker.slow(3, 5) ); // аналогично (из кеша) | caching decorator, js | 24600 | Кеширующая js функция |
212 | $(document).ready(function(){ let tilDate = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 5); let tilDay = new Date(tilDate).getDate(); let monthNames = [ "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря" ]; if($('[field="tn_text_1655377664248"]').length){ new_text = tilDay + " " + monthNames[tilDate.getMonth()]; $('[field="tn_text_1655377664248"] span').text(new_text); } }); | 5 дней, JS | 20010 | Добавит 5 дней |
213 | $monthNames = [ "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря" ]; $tilDate = date("j", strtotime('last day of this month')); $tilMonth = date("n", strtotime('last day of this month')); $til = $tilDate . " " . $monthNames[$tilMonth - 1]; | последний день месяца, php | 21090 | Последний день месяца PHP (напр. 31 мая) |
214 | [display-posts category="apartamenty" image_size="medium" include_excerpt="true" orderby="date" order="ASC" include_excerpt_dash="false"] | список записей, WP | 11090 | Плагин WP – Display Posts для вывода списка записей по критериям |
215 | function custom_rate($num, $id) { $line = "<div class='item_rating' data-for='" . $id . "' data-rate='" . $num[0] . "'>"; for ($i = 1; $i < 6; $i++) { if ($i <= $num[0]) { $line .= "<img src="/wp-content/uploads/2022/07/Orange_star.svg" width=24 height=24 alt="Рейтинг не менее " . $i . ""/>"; } else { $line .= "<img src="/wp-content/uploads/2022/07/Orange_star_empty.svg" width=24 height=24 alt="Рейтинг менее " . $i . ""/>"; } } return $line . "</div>"; } | stars, rating, WP, рейтинг, звездочки | 120 | Функция для Вордпресс рейтинг звездочек |
216 | /** * @param $limit * @return string|string[] * обрезает контент до числа слов */ function content($limit, $pid = null) { $content = explode(' ', get_the_content($pid), $limit); if (count($content)>=$limit) { array_pop($content); $content = implode(" ",$content).'...'; } else { $content = implode(" ",$content); } $content = preg_replace('/[.+]/','', $content); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); return $content; } | контент, образает, WP | 1001 | обрезает контент до числа слов |
217 | $len = 10; // total number of numbers $min = 100; // minimum $max = 999; // maximum $range = []; // initialize array foreach (range(0, $len - 1) as $i) { while(in_array($num = mt_rand($min, $max), $range)); $range[] = $num; } print_r($range); | exclusive random, эксклюзивный | 2040 | Эксклюзивный выбор рандомных чисел |
218 | function loadScript(url, callback) { const element = document.createElement("script"); element.type = "text/javascript"; element.src = url; element.onload = callback; document.body.appendChild(element); } loadScript("js/common.js", () => { loadScript("<https://cdn.jsdelivr.net/npm/luxon@1.25.0/build/global/luxon.min.js>", () => { console.log("timer.js ") }) }) | loadscript, js | 1200 | Скрипт чтоб загрузить другой скрипт |
219 | /** * year start count from * input @string ('1987') * return years since @string */ function year_skils($Y) { $years = date("Y") - date("Y", strtotime($Y)); $year_text = ($years%2==0|$years%3==0|$years%4==0)?"года":(($years%10==1&&$years!=11)?"год":"лет"); return $years . " " . $year_text; } | php, years, year, лет по-русски | 23090 | php сколько лет с тех пор по-русски |
220 | // Перенаправляем пользователя на страницу оплаты Header("Location: http://auth.robokassa.ru/Merchant/Index.aspx?MrchLogin=$mrh_login&OutSum=$out_summ&InvId=$inv_id". "&InvDesc=$inv_desc&SignatureValue=$crc". "&Culture=$culture&Encoding=$encoding&Email=$email"); | header, location, php | 120 | Перенаправляем пользователя на страницу оплаты Header |
221 | User-agent: * Disallow: / User-agent: Googlebot User-agent: AdsBot-Google Disallow: / | disallow all, robots | 130 | Запретить индексайцию всем роботам и рекламным ботам |
222 | echo <<<EOH ---------- ----------- -- ---------- результат значение оп тест ---------- ----------- -- ---------- EOH; | eoh, php print formated | 12090 | Форматированная строка в PHP |
223 | public function convertImage(&$content) { if (defined('ADMIN_SECTION') || defined('WIZARD_SITE_ID')) { return; } preg_match_all('/"(/upload/[^"]*.(jpg|jpeg|png))"/i', $content, $matches1); self::convertImageToWebp($content, $matches1); preg_match_all("/'(/upload/[^']*.(jpg|jpeg|png))'/i", $content, $matches2); self::convertImageToWebp($content, $matches2); } private static function convertImageToWebp(&$content, $matches) { if (!empty($matches[1])) { foreach ($matches[1] as $i => $imageUrl) { $root = $_SERVER['DOCUMENT_ROOT']; $type = $matches[2][$i]; $newName = str_replace($type, 'webp', $imageUrl); if (file_exists($root . $newName)) { $content = str_replace($imageUrl, $newName, $content); continue; } if (!file_exists($root . $imageUrl)) { continue; } $type = strtolower($type); switch ($type) { case 'jpeg': case 'jpg': $img = imagecreatefromjpeg($root . $imageUrl); break; case 'png': $img = imagecreatefrompng($root . $imageUrl); imagepalettetotruecolor($img); imagealphablending($img, true); imagesavealpha($img, true); break; } if (isset($img)) { $result = imagewebp($img, $root . $newName, 75); if (!$result) { continue; } $content = str_replace($imageUrl, $newName, $content); imagedestroy($img); unset($img); } } } } | bitrix, webp, convert | 20030 | convert image to webp bitrix |
224 | ₽ | рубль, html | 100500 | символ рубля в html |
225 | <a href="https://api.whatsapp.com/send?phone=79269946796" target="_blank" class="header__social-link" data-menu-exit> | wa, whatsapp | 200 | |
226 | var player = {score: 1, name: 'Jeff'}; var newPlayer = Object.assign({}, player, {score: 2}); // or var newPlayer = {...player, score: 2}; | create new object, js | 100300 | Создать новый объект из старого в Javascript |
227 | const numbers = [1, 2, 3]; const doubled = numbers.map(x => x * 2); // [2, 4, 6] | map, js | 19800 | Метод map в javascript |
228 | new Date().toLocaleString('en-CA').substr(0,10) | дата, JS, date | 100 | Дата в Javascript ГГГГ-ММ-ДД |
229 | define('BX_COMP_MANAGED_CACHE', true); | кэш, битрикс, сбросить | 1390 | Учет кэширования в Битрикс и моментальные изменения после исправлений. Добавить в dbconn |
230 | grep двух слов в строке grep '77.50.63.90' lamaree.ru.access.log | grep '.default/ajax.php' | grep, 2 words | 10080 | Поиск двух слов в строке через grep linux |
231 | $scheme = CMain::IsHTTPS() ? "https" : "http"; | https, bitrix | 9090 | Определить https в Битрикс |
232 | if(preg_match('/[A-Z]/', $_SERVER['REQUEST_URI'])){ LocalRedirect(strtolower($_SERVER['REQUEST_URI']), 0, "301 Moved permanently"); } | bitrix, редирект, localredirect | 9000 | Битрикс редирект в обход htaccess с заглавных букв в УРЛ на маленькие |
233 | function validatePassword(password) { // Проверяем, что длина пароля не меньше 8 символов if (password.length < 8) { return false; } // Проверяем, что пароль содержит хотя бы одну цифру, одну маленькую букву, одну большую букву и один спецсимвол const regex = /^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+-=[]{};':"\|,.<>/?]).*$/; return regex.test(password); } Пример const password = "myP@ssw0rd"; if (validatePassword(password)) { console.log("Пароль верный"); } else { console.log("Пароль неверный"); } | валидация, пароль, яваскрипт, javascript | 110 | Код валидации пароля на Javascript чтобы пароль был не короче 8 символов и содержал обязательно буквы маленькие, большие, цифры и спецсимволы |
234 | pip install Flask set FLASK_APP=main.py flask --app main.py run | flask, запустить | 20090 | Запустить приложение python flask |
235 | $to = 'email@site.ru'; $subject = 'Сообщение с сайта' . $_SERVER['HTTP_HOST']; $message = 'Заправлены в планшеты космические карты'; $headers = 'MIME-Version: 1.0' . " "; $headers .= 'Content-type: text/html; charset=utf-8' . " "; $headers .= 'To: Admin <' . $to . '>' . " "; $headers .= 'From: Site <' . $to . '>' . " "; mail( $to, $subject, $message, $headers ); | mail, php | 30098 | Отправить письмо php |
236 | //ADD SECTION CANONICAL URL $canonicalScheme = CMain::IsHTTPS() ? "https" : "http"; $APPLICATION->AddHeadString('<link rel="canonical" href="' . $canonicalScheme . '://' . SITE_SERVER_NAME . $arCurSection["PATH"][$arCurSection["ID"]]["SECTION_PAGE_URL"] . '" />', true); | bitrix, section | 9008 | ADD SECTION CANONICAL URL |
237 | <? #$APPLICATION->AddHeadScript(PROTOCOL.$_SERVER['SERVER_NAME']."/js/2gis.js") ?> <? #$APPLICATION->AddHeadScript("https://maps.api.2gis.ru/2.0/loader.js?pkg=full") ?> <? #$APPLICATION->AddHeadScript(SITE_TEMPLATE_PATH."/js/gis-init.js") ?> | 2gis | 200900 | Установка 2gis |
238 | "SECTION_URL" => $arResult["FOLDER"].$arResult["URL_TEMPLATES"]["section"], | bitrix, catalog.section.list | 500 | Путь секции для catalog.section.list |
239 | $category["name"] = "Мимоза"; $category["id"] = 123456; $arParamsTrans = array("replace_space"=>"-","replace_other"=>"-"); $arCatalogSectionFields = array( "ACTIVE" => 'Y', "IBLOCK_ID" => $bitrixCatalogBlockId, "NAME" => $category["name"], "XML_ID" => $category["id"], "IBLOCK_SECTION_ID" => $bitrixSectionId, ); $arCatalogSectionFields["CODE"] = $trans = Cutil::translit($category["name"],"ru",$arParamsTrans); print_r($arCatalogSectionFields); | битрикс, транслит | 300 | Битрикс транслит |
240 | document.addEventListener("DOMContentLoaded", function (event) { setTimeout(function() { let container = document.createElement("div"); container.classList.add('g-recaptcha'); container.setAttribute('id', 'g-recaptcha'); container.dataset.sitekey = '6Lc-rR0nAAAAAApbMeAGotqehDQZrx7IeUrAajI2'; let prev = document.querySelector('[name="form_hidden_45"]'); prev.after(container); },0); }); | JS, javascript, captcha | 120 | Добавить блок Капча после поля формы Яваскрипт |
241 | let dano = $('[name=ORDER_PROP_20]').val(); // 19.03.2023 let dateEn = new Date(dano.substr(6,4), dano.substr(4,2) - 1, dano.substr(0,2), 0, 0, 0).toLocaleDateString('en-CA'); // 2023-03-19 | date, JS, convert | 200 | Конвертация импортной даты в русскую |
242 | use BitrixMainPageAsset; use BitrixMainPageAssetLocation; Asset::getInstance()->addString("<script>***</script>", true, AssetLocation::AFTER_JS); // AssetLocation::BEFORE_CSS; // AssetLocation::AFTER_CSS; // AssetLocation::AFTER_JS_KERNEL // AssetLocation::AFTER_JS | head, js, css, d7 | 10980 | Вставка ссылок в head Битрикс |
243 | BitrixMainLoader::includeModule('iblock'); CIBlockSection::ReSort(30); | переиндексация разделов битрикс | 100 | Переиндексация LEFT_MARGIN и RIGHT_MARGIN разделов Битрикс |
244 | CREATE TABLE email_services(domain CHAR(24) NOT NULL,name CHAR(32) NOT NULL,url CHAR(64) NOT NULL); LOAD DATA LOCAL INFILE '/home/user/services.csv' INTO TABLE email_services FIELDS TERMINATED BY ',' ENCLOSED BY '"'; | mysql, csv, insert, create | 290 | Создать таблицу SQL из локального csv файла |
245 | https://drive.google.com/uc?export=download&id=1Nzl05CwW6NOwqTZsj1uOhmj52zLTk4Vv | видео, загрузить, гугл диск | 1290 | Ссылка для воспроизведения видео с гугл-диска. Загрузить файл на Диск, предоставить доступ по ссылке, из ссылки взять id и здесь заменить |
246 | JSON_UNESCAPED_UNICODE => 256 | unicode, json, php | 240 | Числовое представление константы JSON_UNESCAPED_UNICODE |
247 | function loadImages(block) { Array.from(block.querySelectorAll('img[data-src]')).forEach(function (img, i) { let _img = new Image, _src = img.getAttribute('data-src'); let wrap = img.closest('.is-loader'); _img.onload = function () { img.src = _src; img.classList.add('is-loaded'); if (wrap.length > 0) wrap.classList.remove('is-loader'); } if (img.src !== _src) _img.src = _src; }); } | изображения, загрузка, load, js | 3000 | Загрузка картинок с атрибутом data-src |
248 | <?php $haystack = 'abcde'; $needle = 'f'; strpos($haystack,$needle) !== FALSE OR print "$needle not in $haystack"; | php, print | 100 | Как использовать возвращаемое print значение (1) |
249 | RedirectMatch 301 ^/my_redirected_folder/ http://www.new-website.com/ | redirect, редирект | 220 | В корневом htaccess редирект с папки на другой сайт |
250 | <?php $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array( PDO::ATTR_PERSISTENT => true )); ?> | pdo, php, mysql, постоянное соединение | 2200 | Настройка постоянного соединения с MySQL |
251 | <meta name="format-detection" content="telephone=no"> <meta name="format-detection" content="address=no"> | meta | 110 | Мета скрыть телефон и адрес |
252 | !CSite::InDir("/shop/") | папка, Битрикс | 190080 | Проверка текущей папки в Битрикс |
253 | $iterator = CIBlockElement::GetList( array("ID"=>"DESC"), array('IBLOCK_ID' => 26, '=ACTIVE' => 'Y', 'IBLOCK_SECTION_ID', ['LOGIC' => 'OR', 'PREVIEW_TEXT' => false, 'DETAIL_TEXT' => false]), false, false, array('ID', 'NAME', 'CODE', 'IBLOCK_SECTION_ID') ); while($item = $iterator->Fetch()) { $was_id = 0; $nav = CIBlockSection::GetNavChain(false, $item['IBLOCK_SECTION_ID'], array(), false); $url = ""; while($nav->Fetch()){ if($was_id != $item['ID']){ $url_length = count($nav->arResult); $url .= $nav->arResult[$url_length - 1]['CODE'] . "/"; echo $item['ID'] . ';"' . $item['NAME'] . '";"https://lamaree.ru/catalog/' . $url . $item['CODE'] . '/"' . " "; $was_id = $item['ID']; } } } | url, bitrix, catalog | 980 | Выбрать из каталога Битрикс товары без описаний с URL |
254 | document.addEventListener("DOMContentLoaded", ()=>{ document.querySelector("#get_data_by_inn").addEventListener("click", ()=> { (async function get_jur_data() { let url = "https://' . $_SERVER['HTTP_HOST'] .'/test/inn.json"; fetch(url, { headers: { Authentication: "secret" }}) .then((response) => { return response.json(); }) .then((data) => { console.log(data); }); })() }); }); | json, fetch, js | 670 | Запрос json через javascript |
255 | class Foo extends \stdClass // to fix Deprecated: Creation of dynamic property | php, deprecation, dynamic | 650 | Исправление ошибки создания динамически свойства в php8.2 |
256 | <IfModule mod_rewrite.c> RewriteEngine on RewriteBase / RewriteRule ^$ public/ [L] RewriteRule (.*) public/$1 [L] </IfModule> | redirect, public | 190 | htaccess редирект из корня в папку public в корне |
257 | <script> $(document).ready(function(){ $('<script/>',{type:'text/javascript', src:'https://w561931.yclients.com/widgetJS'}).appendTo('head'); }); </script> | js, document.ready, load script | 450 | Загрузить js скрипт после загрузки страницы |
258 | SELECT COUNT(SUM_PAID), CASE WHEN SUM_PAID > 10000 THEN 'more10' WHEN SUM_PAID BETWEEN 5000 AND 10000 THEN '5to10' ELSE 'less5' END AS SaleLevel FROM b_sale_order GROUP BY SaleLevel; | sql, case | 140 | Запрос с условием SQL CASE |
259 | function readFileLineByLine($filename) { $file = fopen($filename, 'r'); while (!feof($file)) { yield fgets($file); } fclose($file); } foreach (readFileLineByLine('large_file.txt') as $line) { echo $line . "<br>"; } | генератор, php | 40010 | Генераторы особенно полезны в сценариях обработки больших файлов или потоков данных, например при построчном считывании большого файла |
260 | Рейтинг рассчитывается по формуле Экслера: рейтинг = (сумма всех оценок + 31,25) / (число проголосовавших + 10) | рейтинг | 43590 | Как считать рейтинг |
261 | function flog($fname, $ftext, $write_a_w_state = null){ if($write_a_w_state) $write_a_w_state = 8; // FILE_APPEND else $write_a_w_state = 0; // FILE_APP $fp = "/home/virtwww/w_2315art-ru_25432bcf/http/log/" . substr($fname, 0, strpos($fname, ".")) . "_" . date('m') . "_" . date('Y') . substr($fname, strpos($fname, ".")); file_put_contents($fp, date("Y-m-d H:i:s ") . $ftext . " ", $write_a_w_state); } | log, php, func | 110 | flog new |
262 | document.querySelectorAll('[name="CallForm[email]"]').forEach(i => { if(i.value != '') { return name = i.value; } }); | js, form | 340 | Если много форм на сайте с одинаковыми названиями полей, выбрать непустое |
263 | https://api.wordpress.org/secret-key/1.1/salt/ | ключи, WP | 985 | Сгенерировать ключи Вордпресс |
264 | <script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui@5.0/dist/fancybox/fancybox.umd.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui@5.0/dist/fancybox/fancybox.css" /> <script type="text/javascript"> Fancybox.bind("a.fancybox", { // Your custom options }); </script> | fancybox | 0 | New fancybox 5 |
265 | https://demo.flyimg.io/upload/w_1600,h_1067,c_1,o_jpg/https://modernfotostudio.ru/images/img1-home-top.jpg | afif, url, convert | 510 | Конвертер в афиф формал, но сохраняет в жпег формате. Много легче оригинала |
266 | /** * Clean Head */ remove_action('wp_head', 'wp_generator'); remove_action('wp_head', 'wp_shortlink_wp_head'); remove_action('wp_head', 'adjacent_posts_rel_link_wp_head'); remove_action('wp_head', 'rest_output_link_wp_head', 10); remove_action('wp_head', 'wp_oembed_add_discovery_links', 10); remove_action('wp_head', 'wp_resource_hints', 2); remove_action('template_redirect', 'rest_output_link_header', 11, 0); add_filter('the_generator', '__return_empty_string'); // Убираем версию WordPress remove_action('wp_head', 'index_rel_link'); remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0); // Короткая ссылка, ссылка без ЧПУ <link rel='shortlink' | wp, clean head | 10090 | WP clean header |
267 | AddEventHandler("sale", "onSaleDeliveryServiceCalculate", "onSaleDeliveryServiceCalculate"); function onSaleDeliveryServiceCalculate($result, $shipment, $deliveryID){ // Проверка id службы доставки //17 - Почта России //20 - Доставка курьером //21 - Пункт выдачи СДЭК //24 - Пункт выдачи Boxberry //33 - EMS Почта России if($deliveryID == 20 ){ if(isset($_SESSION['ORDER_BASKET_PRICE']) ) { $basketPrice = $_SESSION['ORDER_BASKET_PRICE']; if($basketPrice > 1000){ // Записываем новое значение цены на доставку $shipment->setBasePriceDelivery(0, true); } } } if($deliveryID == 31 || $deliveryID == 33){ $shipment->setBasePriceDelivery(2500, true); } } | битрикс, доставка | 150 | Бесплатная доставка, если сумма в корзине больше определенной |
268 | $pdf = new CSalePdf('P', 'pt', 'A4'); print_r( $pdf ); | pdf, bitrix | 170 | В Битрикс сделать ПДФ pdf |
269 | if ($handle = opendir('.')) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { echo "$entry "; } } closedir($handle); } | readdir, php | 290 | Прочесть файлы в папке |
270 | #order:Название товара =1000:::image=URL | order, tilda | 290 | Ссылка на покупку в Тильде с картинкой |
271 | // Simulate an HTTP redirect: window.location.replace("http://www.w3schools.com"); | js, redirect | 155 | js редирект |
272 | #order:Product name =1000:::image=URL | тильда, товар | 340 | Тильда добавить товар с картинкой |
273 | function webpImage($source, $quality = 100, $removeOld = false) { if(strpos('http', $source) !== false) { //define scheme $scheme = CMain::IsHTTPS() ? "https" : "http"; // http //replace http://server with nothing $source = str_replace([$scheme . '://'. $_SERVER['HTTP_HOST']], [""], $source); } if(strpos('http', $source) === false) { $source = '/home/bitrix/www' . $source; } $dir = pathinfo($source, PATHINFO_DIRNAME); $name = pathinfo($source, PATHINFO_FILENAME); $destination = $dir . DIRECTORY_SEPARATOR . $name . '.webp'; $info = getimagesize($source); $isAlpha = false; echo $info['mime']; if ($info['mime'] == 'image/jpeg'){ $image = imagecreatefromjpeg($source); echo $source; var_dump($image); } elseif ($isAlpha = $info['mime'] == 'image/gif') { $image = imagecreatefromgif($source); } elseif ($isAlpha = $info['mime'] == 'image/png') { $image = imagecreatefrompng($source); } else { return $source; } if ($isAlpha) { imagepalettetotruecolor($image); imagealphablending($image, true); imagesavealpha($image, true); } imagewebp($image, $destination, $quality); imagedestroy($image); if ($removeOld) unlink($source); return $destination; } | webp, convert image, bitrix | 10900 | Функция для Битрикс конвертации картинок в webp |
274 | if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die(); use BitrixMainDataCache; $elems = []; $cash_key = md5("hdgbchdch383787lkokcodcjj8773asas_"); $cache = Cache::createInstance(); // получаем экземпляр класса if ($cache->initCache(360000, $cash_key)) { // проверяем кеш и задаём настройки $elems = $cache->getVars(); // достаем переменные из кеша } elseif ($cache->startDataCache()) { ...вычисления $cache->endDataCache($elems); // записываем в кеш } | cache, bitrix, кеширование | 23600 | Кеширование блоков в битрикс |
275 | /битрix/modules/main/lib/лисенз.php getExpireDate():?Date{ $_261120490= (int)($GLOBALS[___1048290049(33)] ??(1100/2-550)); if($_261120490>(1200/2-600)){ return Date::createFromTimestamp(/*$_261120490*/1782990400);} return null;} | битрix | 10900 | Нет комментария. Произвольный набор символов |
276 | preg_replace('~D~', '', $phone); | regex, php, phone, телефон регекс | 20530 | Оставить только цифры в номере телефона |
277 | <picture> <source media="(max-width: 799px)" srcset="elva-480w-close-portrait.jpg" /> <source media="(min-width: 800px)" srcset="elva-800w.jpg" /> <img src="elva-800w.jpg" alt="Chris standing up holding his daughter Elva" /> </picture> | picture, source, size | 21200 | picture source с размерами |
278 | <?BitrixMainUIExtension::load("ui.buttons"); ?> <!-- .ui-btn.ui-btn-clock--> <button class="ui-btn ui-btn-clock">Кнопарь</button> <!-- .ui-btn-split.ui-btn-clock--> <div class="ui-btn-split ui-btn-clock"> <button class="ui-btn-main">Кнопарь</button> <button class="ui-btn-menu"></button> </div> | кнопка, битрикс | 10087 | Кнопка Битрикс со стилями |
279 | <script> document.addEventListener("DOMContentLoaded", function(){ let tilDate = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 14); let tilDay = new Date(tilDate).getDate(); let monthNames = [ "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря" ]; if(document.querySelector('[field="tn_text_1721979743635"]') !== null){ new_text = "Акция до " + tilDay + " " + monthNames[tilDate.getMonth()]; document.querySelector('[field="tn_text_1721979743635"] strong').textContent = new_text; } }); </script> | js, 14 дней, Тильда | 12000 | Добавит 14 дней в Тильде в блоке |
280 | <script type="application/ld+json"> { "@type" : "Offer", "hasMerchantReturnPolicy": { "@type": "MerchantReturnPolicy", "applicableCountry": "RU", "returnPolicyCategory": "https://schema.org/MerchantReturnFiniteReturnWindow", "merchantReturnDays": 10, "returnMethod": "https://schema.org/ReturnInStore", "returnFees": "https://schema.org/FreeReturn" }, "shippingDetails": { "@type": "OfferShippingDetails", "shippingRate": { "@type": "MonetaryAmount", "value": <?=DELIVERY?>, "currency": "RUB" }, "shippingDestination": { "@type": "DefinedRegion", "addressCountry": "RU" }, "deliveryTime": { "@type": "ShippingDeliveryTime", "handlingTime": { "@type": "QuantitativeValue", "minValue": 1, "maxValue": 1, "unitCode": "DAY" }, "transitTime": { "@type": "QuantitativeValue", "minValue": 1, "maxValue": 14, "unitCode": "DAY" } } }, "priceCurrency": "RUB", "price": "<?=$price['PRICE']?>", "itemCondition" : "http://schema.org/NewCondition", "availability" : "http://schema.org/<?=($offer['CAN_BUY'] ? 'InStock' : 'OutOfStock')?>", "url" : "https://<?=$_SERVER['HTTP_HOST']?><?=$_SERVER['REQUEST_URI']?>", "image": "https://<?=$_SERVER['HTTP_HOST']?><?=$actualItem["MORE_PHOTO"][0]['SRC']?>", "name" : "<?=$item['NAME']?>", "sku": "<?=str_replace(" ", "_", $item['PROPERTIES']['ARTNUMBER']['VALUE'])?>", "description" : "<?=get_schema_product_description($item, "PREVIEW")?>" } </script> | schema,markup,offer | 39008 | Offer ld+json markup |
281 | <script src="https://forma.tinkoff.ru/static/onlineScriptTilda.js"></script> | tinkoff, код рассрочки, тинькоф | 9080 | Сорс кода рассрочки тинькоф |
282 | 18 => array ( 'CONDITION' => '#^/robots.txt(.*)#', 'RULE' => '', 'ID' => '', 'PATH' => '/robots.txt.php', 'SORT' => 100, ), | urlrewrite, Переадресация, robots | 45900 | Переадресация Битрикс в urlrewrite для robots.txt |
283 | CJSCore::Init(['masked_input']); | maskedinput, bitrix, Битрикс, маска | 1290 | Аналог maskedinput в Битрикс |
284 | Например, запретить доступ конкретным адресам, разрешить всем остальным: <RequireAll> Require not ip 1.1.1.1 # ipv4 Require not ip 1:2:3:4:5:6:7:8 # ipv6 Require all granted </RequireAll> | IP, доступ, htaccess | 10032 | Запретить доступ по IP через htaccess |
285 | RewriteEngine On RewriteBase / RewriteCond %{THE_REQUEST} /public/([^s?]*) [NC] RewriteRule ^ %1 [L,NE,R=302] RewriteRule ^((?!public/).*)$ public/$1 [L,NC] | htaccess, rewrite, public | 9080 | htaccess rewrite root to public |
286 | $url = 'https://rutube.ru/api/video/' . $id; $preview_src = 'https://rutube.ru/play/embed/' . $id . '/thumbnail/?redirect=1'; | rutube, preview | 9000 | Ссылка на видео rutube.ru и ссылка на превью |
287 | {"id": "078c5c33e05817d77b43714cdb53240e", "title": "u0422u0438u0431u0435u0442u0441u043au0438u0439 u043cu0430u0441u0441u0430u0436 u041au0443u041du044cu0435. u0422u043eu0447u0435u0447u043du044bu0439 u044du043du0435u0440u0433u0435u0442u0438u0447u0435u0441u043au0438u0439 u043cu0430u0441u043bu044fu043du044bu0439 u043cu0430u0441u0441u0430u0436.", "description": "u041cu0430u0441u0441u0430u0436 u041au0443u043du044cu0435 - u0440u0430u0437u043du043eu0432u0438u0434u043du043eu0441u0442u044c u043cu0430u0441u043bu044fu043du043eu0433u043e u043cu0430u0441u0441u0430u0436u0430, u043au043eu0442u043eu0440u044bu0439 u043fu0440u0430u043au0442u0438u043au0443u0435u0442u0441u044f u0432 u0441u0438u0441u0442u0435u043cu0435 u0442u0440u0430u0434u0438u0446u0438u043eu043du043du043eu0439 u0442u0438u0431u0435u0442u0441u043au043eu0439 u043cu0435u0434u0438u0446u0438u043du044b. u041eu043d u044du0444u0444u0435u043au0442u0438u0432u0435u043d u043fu0440u0438 u043fu0440u043eu0431u043bu0435u043cu0430u0445 u043eu043fu043eu0440u043du043e- u0434u0432u0438u0433u0430u0442u0435u043bu044cu043du043eu0433u043e u0430u043fu043fu0430u0440u0430u0442u0430, u0437u0430u0441u0442u043eu044f u043bu0438u043cu0444u044b u0438 u043au0440u043eu0432u0438, u0431u043eu043bu044fu0445 u0432 u0441u043fu0438u043du0435 u0438 u043fu043bu0435u0447u0430u0445, u0441u043du0438u043cu0430u0435u0442 u043cu044bu0448u0435u0447u043du044bu0439 u0441u043fu0430u0437u043c, u0440u0430u0441u0441u043bu0430u0431u043bu044fu0435u0442 u043du0430u043fu0440u044fu0436u0435u043du043du044bu0435 u043cu044bu0448u0446u044b, u0431u0430u043bu0430u043du0441u0438u0440u0443u0435u0442 u0432u0441u0435 u044du043du0435u0440u0433u0438u0438 u0442u0435u043bu0430, u0440u0430u0432u043du043eu0432u0435u0441u0438u0435 u043au043eu0442u043eu0440u044bu0445 u0430u0432u0442u043eu043cu0430u0442u0438u0447u0435u0441u043au0438 u043eu0431u0435u0441u043fu0435u0447u0438u0432u0430u0435u0442 u0445u043eu0440u043eu0448u0435u0435 u0437u0434u043eu0440u043eu0432u044cu0435 u0438 u0433u0430u0440u043cu043eu043du0438u044e. u041cu0430u0441u0441u0430u0436 u043fu0440u043eu0432u043eu0434u0438u0442 u041eu0440u043bu043eu0432 u0418.u0410. https://sagandali.com/specialisti/orlov-ivan-aleksandrovich.html u0421u0430u0439u0442 u043au043bu0438u043du0438u043au0438 u0421u0430u0433u0430u043d u0414u0430u043bu0438 https://sagandali.com/ u0418u043du0441u0442u0430u0433u0440u0430u043c https://www.instagram.com/sagan_dali/ u0413u0440u0443u043fu043fu0430 u0412u041a https://vk.com/vostochnaya_medicina_moskva u0413u0440u0443u043fu043fu0430 FB https://www.facebook.com/sagandalimed/ u0413u0440u0443u043fu043fu0430 u041eu0434u043du043eu043au043bu0430u0441u0441u043du0438u043au0438 https://www.ok.ru/profile/587980932899 #u043au0443u043du044cu0435 #u0442u043eu0447u0435u0447u043du044bu0439 #u043cu0430u0441u0441u0430u0436 #u044du043du0435u0440u0433u0435u0442u0438u0447u0435u0441u043au0438u0439 #massage", "thumbnail_url": "https://pic.rutubelist.ru/video/85/87/85870d3ed1d0ed0968d95d7ef5162c72.jpg", "is_audio": false, "created_ts": "2024-05-22T18:26:45", "video_url": "https://rutube.ru/video/078c5c33e05817d77b43714cdb53240e/", "track_id": 214925787, "hits": 27, "duration": 60, "is_livestream": false, "last_update_ts": "2024-05-22T18:28:36", "stream_type": null, "origin_type": "rtb", "picture_url": "", "preview_url": "https://preview.rutube.ru/preview/078c5c33e05817d77b43714cdb53240e.webp?exp=1725884596&s=hcdN0xCCAh1rtIosyMTW6A", "author": {"id": 36961394, "name": "channel_sagandali", "avatar_url": "https://pic.rutubelist.ru/user/71/ab/71abefcb1a4d25c44cad9cbcac1cf145.jpg", "site_url": "https://rutube.ru/video/person/36961394/", "is_allowed_offline": true}, "is_adult": false, "pg_rating": {"age": 12, "logo": "https://pic.rutubelist.ru/agerestriction/99/0e/990e87f25d8689833de24c0eb7eaec81.png"}, "publication_ts": "2024-05-22T18:27:56", "extra_params": {}, "future_publication": null, "is_club": false, "is_classic": true, "is_paid": false, "product_id": null, "category": {"id": 13, "category_url": "https://rutube.ru/video/category/13/", "name": "u0420u0430u0437u043du043eu0435"}, "is_official": false, "is_licensed": false, "action_reason": {"id": 0, "name": ""}, "embed_url": "https://rutube.ru/play/embed/078c5c33e05817d77b43714cdb53240e", "html": "<iframe width="720" height="405" src="https://rutube.ru/play/embed/078c5c33e05817d77b43714cdb53240e" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowfullscreen allow="encrypted-media"></iframe>", "is_hidden": false, "has_high_quality": false, "is_deleted": false, "source_url": "https://rutube.ru/video/078c5c33e05817d77b43714cdb53240e/", "rutube_poster": null, "pepper": null, "show": null, "persons": "https://rutube.ru/api/metainfo/video/078c5c33e05817d77b43714cdb53240e/videoperson", "genres": "https://rutube.ru/api/metainfo/video/078c5c33e05817d77b43714cdb53240e/videogenre", "music": null, "hashtags": ["massage", "u043au0443u043du044cu0435", "u043cu0430u0441u0441u0430u0436", "u0442u043eu0447u0435u0447u043du044bu0439", "u044du043du0435u0440u0433u0435u0442u0438u0447u0435u0441u043au0438u0439"], "all_tags": [], "restrictions": {"country": {"allowed": ["-", "AB", "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "OS", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "ZA", "ZM", "ZW"], "restricted": []}}, "feed_url": "https://rutube.ru/video/person/36961394/", "feed_name": "channel_sagandali", "feed_subscription_url": "https://rutube.ru/api/subscription/card/userchannel/36961394", "feed_subscribers_count": 0, "episode": null, "season": null, "is_serial": false, "ext_id": null, "tv_show_id": null, "club_params": "", "premier_url": null, "hide_comments": false, "hide_chat": false, "hide_likes": false, "hide_dislikes": false, "stream_end_ts": null, "is_original_content": false, "kind_sign_for_user": false, "is_reborn_channel": false, "topics": [], "properties": {"hide_comments": false, "is_donate_allowed": false}} | rutube json | 9020 | rutube json on request |
288 | $(document).ready(function(){ let coordinates = [ [ 55.621120, 37.745894, 'Ship' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Ship*/ [ 55.623054, 37.705296, 'Oreh' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Oreh*/ [ 55.726735, 37.747923, 'Stahan' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Stahan*/ [ 55.605079, 37.721539, 'Domod' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Domod*/ [ 55.653061, 37.763539, 'Brat' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Brat*/ [ 55.541874, 37.722733, 'Vidnoye' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Vidnoye*/ [ 55.676545, 37.633802, 'Nagat' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Nagat*/ [ 55.726487, 37.747693, 'Nizhegorodskaya' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Nizhegorodskaya Perovo*/ [ 55.660531, 37.730895, 'Mar' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Mar*/ [ 55.532594, 37.717052, 'Sapronovo' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Sapronovo*/ [ 55.647433, 37.386310, 'Solntsevo' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Solntsevo*/ [ 55.642138, 37.601421, 'Chertanovskaya' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Chertanovskaya*/ [ 55.553900, 37.553990, 'Skobelevskaya' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Skobelevskaya*/ [ 54.991149, 82.968570, 'Novosib' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Novosib*/ [ 59.910402, 30.518133, 'Kudrovo' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Kudrovo*/ [ 55.555969, 37.809973, 'Misailovo' , '' , 'https://static.tildacdn.com/tild6432-3466-4133-a163-383538333433/44605057_1.png' ], /*Misailovo*/ ]; let classNames = [ 'Solntsevo', 'Brat', 'Ship', 'Domod', 'Mar', 'Oreh', 'Stahan', 'Nagat', 'Chertanovskaya', 'Skobelevskaya', 'Novosib', 'Kudrovo', 'Sapronovo', 'Prokshino', 'Kolomenskaya', 'Misailovo', ]; ymaps.ready(function () { let myMap = new ymaps.Map('map', { center: [ coordinates[0][0] , coordinates[0][1] ], //Координаты центра при запуске карты zoom: 10 //Увеличение карты при запуске }, {searchControlProvider: 'yandex#search' }), MyIconContentLayout = ymaps.templateLayoutFactory.createClass( '<div style="color: #FFFFFF; font-weight: bold;">$[properties.iconContent]</div>' ); for (i = 0; i < coordinates.length; i++) { myMap.geoObjects .add(new ymaps.Placemark([ coordinates[i][0] , coordinates[i][1] ], { hintContent: coordinates[i][3], // специально 3 вместо 2, чтоб не было подсказок balloonContent: coordinates[i][3], }, { iconLayout: 'default#imageWithContent', iconImageHref: coordinates[i][4], iconImageSize: [25, 32], // Размеры метки. iconImageOffset: [-16, -33], // Смещение левого верхнего угла иконки относительно iconContentOffset: [0, 0], // Смещение слоя с содержимым относительно слоя с картинкой iconContentLayout: MyIconContentLayout })); let className = coordinates[i][2]; let latHere = coordinates[i][0]; let lonHere = coordinates[i][1]; $(`.${className}`).click(()=>{ console.log('click'); classNames.forEach((elt, index)=>{ if(className === elt){ myMap.setCenter([latHere, lonHere]); myMap.setZoom( 16 ); } }); }); }; }); }); | yandex, maps, яндекс, карты | 100 | По клику на кнопке перейти на свою карту Яндекс карты |
289 | (function() { // Load the script const script = document.createElement("script"); script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js'; script.type = 'text/javascript'; script.addEventListener('load', () => { console.log(`jQuery ${$.fn.jquery} has been loaded successfully!`); // use jQuery below }); document.head.appendChild(script); })(); | jquery | 200 | загрузить скриптом jQuery |
290 | function dataLayerYandexPush (id, naming, price, quant, brand, category, variant) { dataLayer?.push({ "ecommerce": { "currencyCode": "RUB", "add" : { "products": [ { "id": id, "name": naming, "price": price, "quantity": quant, "brand": brand, "category": category, "variant": variant } ] } } }); } | dataLayer,push,Yandex | 8001 | dataLayer push Yandex |
291 | В адресной строке браузера добавьте к адресу страницы параметр _ym_debug=2 и загрузите страницу. http://example.com/?_ym_debug=2 | проверка метрики, метрика | 19700 | Как проверить работу счетчика Я Метрики |
292 | SELECT p.PRODUCT_ID, p.CNT FROM b_sale_order_product_stat p JOIN b_iblock_element e ON p.PRODUCT_ID = e.ID WHERE e.IBLOCK_ID = 55 GROUP BY p.PRODUCT_ID ORDER BY p.CNT DESC LIMIT 9 | рекомендуемые, битрикс | 5690 | Выбрать из БД Битрикс которые чаще заказывают с другими |
293 | echo $MESS['MONTH_'.date('n')]; // Июнь echo $MESS['MONTH_'.date('n').'_S']; // Июня | месяц, битрикс, родительный падеж | 6700 | Битрикс получить месяц в родительном падеже |
294 | $arSelect = Array("ID", "NAME"); $arFilter = Array("IBLOCK_ID"=>2, "ACTIVE"=>"Y"); $res = CIBlockElement::GetList(Array("NAME" => "ASC"), $arFilter, false, Array("nPageSize" => 1005), $arSelect); $i = 1; $name = []; while($ob = $res->GetNextElement()) { $arFields = $ob->GetFields(); $sel = $DB->Query("SELECT NAME FROM b_sale_order_props_variant WHERE NAME LIKE '%" . $arFields['NAME'] . "%'"); while($res_name = $sel->Fetch()) { $name[] = $res_name['NAME']; } //echo $name; if(!in_array($arFields['NAME'], $name)) { $query = "INSERT INTO b_sale_order_props_variant VALUES ('', 26, '" . $arFields['NAME'] . "', '" . Cutil::translit($arFields['NAME'], "ru", array("replace_space"=>"-","replace_other"=>"-")) . "', " . $i*100 . ", '', 'bx_" . hash("crc32", $arFields['NAME']) . "')"; echo $query . " "; $DB->Query($query); } else { $query = "UPDATE b_sale_order_props_variant SET SORT = " . $i*100 . " WHERE NAME = '" . $arFields['NAME'] . "'"; echo $query . " "; $DB->Query($query); } $i++; } | свойства заказа | 10090 | Добавить свойство Пункт самовывоза в список свойств Заказа в Битрикс |
295 | new Date($('[type="datetime-local"]').val()).toLocaleString('ru-RU').split(", ").join(" ").substr(0, 16) | дата, js | 9000 | Выведет 14.11.2024 10:31 |
296 | private function processPhone($phone) { $hasPlus = $phone[0] == '+'; $phone = preg_replace('/D+/', '', $phone); if($phone[0] == '8') { $phone = '7' . substr($phone, 1); } return trim($phone); } | php, phone, телефон проверка | 4000 | Проверка телефона php |
297 | grep -rl "javascript;base64,CiAg" . | xargs sed -i "s@javascript;base64,CiAg@ @g" | замена, grep, bash script | 350 | На сервере заменить все вхождения во всех файлах рекурсивно с строки на пробел |
298 | $arPrice["PRICE"] * $item["PRODUCT"]["VAT_RATE"] / (100 + $item["PRODUCT"]["VAT_RATE"]) | НДС | 30090 | Посчитать НДС из цены с НДС |
299 | https://metrica.yandex.com/counter-transfer/?period=yesterday&group=dekaminute | метрика, яндекс | 1245 | Ссылка на перенос счетчика метрики к себе на аккаунт |
300 | $today = new DateTime(); $ny1 = new DateTime('December 25'); $ny2 = new DateTime('January 9'); if ($today < $ny2 && $today > $ny1) { ... } | php, ny, новый год | 45800 | Автоматический показ объявления о новогодних праздниках php |
301 | #убрать множественные слеши в конце адреса RewriteCond %{THE_REQUEST} s[^?]*// RewriteRule ^.*$ /$0 [R=302,L,NE] | htaccess, slash | 9086 | убрать множественные слеши в конце адреса |
302 | if (strlen($youtube_id) > 11) { // rutube $result = file_get_contents('https://rutube.ru/api/video/' . $youtube_id . '/thumbnail/'); // Will dump a beauty json :3 $preview_url = json_decode($result, true); $preview_url_url = $preview_url['url']; echo '<div class="youtube" itemscope itemtype="http://schema.org/VideoObject" data-src="https://rutube.ru/play/embed/' . $youtube_id . '" id="' . $youtube_id . '" style="background-image: url(//i.ytimg.com/vi/' . $youtube_id . '/0.jpg);"> <meta itemprop="name" content="' . $name . '"/> <meta itemprop="description" content="' . $descr . '"/> <meta itemprop="duration" content="PT' . $t[0] . 'M' . $t[1] . 'S"> <meta itemprop="isFamilyFriendly" content="true"> <meta itemprop="uploadDate" content="' . date("Y-m-d H:i:s", filemtime(__FILE__)) . '"/> <span itemprop="thumbnail" itemscope itemtype="http://schema.org/ImageObject"> <img itemprop="contentUrl" src="' . $preview_url_url . '" style="width:580px;height:324px;" alt="' . $name . '"/> <meta itemprop="thumbnailUrl" content="' . $preview_url_url . '"> <meta itemprop="width" content="580"> <meta itemprop="height" content="324"> </span> <div class="play"><a itemprop="url" href="https://rutube.ru/play/embed/' . $youtube_id . '"></a></div></div>'; } | php, preview | 130 | Функция php для вставки видео Рутуб по кнопке с превью картинкой |
303 | <? $line = ''; $files = scan_dir(__DIR__ . "/im/", [".", ".."]); // функция scan_dir в init.php foreach($files as $i=>$f){ $dir = $f; $line .= '<a class="slider-doc" href="/clinic/diploma/im/'.$f.'"><img class="lazyload" data-src="/clinic/diploma/im/'.$f.'" style="width:200px; height:320px; object-fit:cover"/></a>'; } echo $line; ?> | scan_dir, php | 1900 | Сканировать папку и вывести только изображения |
304 | $assetManager->addJs( "https://cdn.ampproject.org/v0.js"); | amp, bitrix | 30090 | Скрипт загрузки АМП |
305 | Внутрь хед ставим <script src="https://www.google.com/recaptcha/enterprise.js?render=6LfM-tUqAAAAAAK871StVSv4ssTIyIeOk7I7&hl=ru&badge=bottomleft"></script> и <script> function onClick(e) { e.preventDefault(); grecaptcha.enterprise.ready(async () => { const token = await grecaptcha.enterprise.execute('6LfM-tUqAAAAAAK871StVSv4ssTsjweIyIeOk7I7', {action: 'SUBMIT'}); // IMPORTANT: The 'token' that results from execute is an encrypted response sent by // reCAPTCHA to the end user's browser. // This token must be validated by creating an assessment. // See https://cloud.google.com/recaptcha/docs/create-assessment }); } </script> После отправки формы в консоли Нетворк перейти по ссылке сгенерированного хеша | рекапча3, recaptcha v3 | 340070 | Рекапча версия 3 установка |
306 | <div><?=(new CBXSanitizer)->sanitizeHtml($foo);?></div> $login = $DB->ForSql($_REQUEST['login']); $res = $DB->Query("SELECT * FROM b_user WHERE LOGIN='$login'"); $arInsert = $DB->PrepareInsert("b_user", ["LOGIN" => $_REQUEST["login"]]); $sql = "INSERT INTO b_user (".$arInsert[0].") VALUES (".$arInsert[1].")"; $res = $DB->Query($sql); | sanitize, bitrix | 100 | Обработать переменную в Битрикс |
307 | <meta http-equiv="refresh" content="0;url=https://spa-cavefish.ru/odintsovo"> | meta, redirect, редирект html | 200 | Редирект 301 средствами html |
308 | system('tail -n 100 /home/bitrix/.msmtprc') | почта, bitrixvm, log mail | 300 | Посмотреть в php строке Битрикс лог почты |
309 | docker-compose up -d | docker, start | 50 | Имея файл docker-compose.yml стартовать докер приложение |
310 | CFile::ShowImage($img, $width, $height); | bitrix, img, image, битрикс, изображение | 460 | Как вывести в Битрикс картинку по размерам. $img - ID картинки или путь к файлу |
311 | Знак рубля ₽ | рубль | 9900 | Знак рубля |
312 | <?=(date('W') + 5) % 5 + 1?> | php, чередование | 39080 | Раз в неделю из пяти: первую - одно, вторую - второе. PHP |
313 | // определим константу LOG_FILENAME, в которой зададим путь к лог-файлу define("LOG_FILENAME", $_SERVER["DOCUMENT_ROOT"]."/mylog-6665444.txt"); //дебаг почты function custom_mail($to, $subject, $message, $additional_headers='', $additional_parameters='') { AddMessage2Log( 'To: '.$to.PHP_EOL. 'Subject: '.$subject.PHP_EOL. 'Message: '.$message.PHP_EOL. 'Headers: '.$additional_headers.PHP_EOL. 'Params: '.$additional_parameters.PHP_EOL ); if ($additional_parameters!='') { return @mail($to, $subject, $message, $additional_headers, $additional_parameters); } else { return @mail($to, $subject, $message, $additional_headers); } } | mail, php, log, bitrix | 19005 | mail log bitrix |
314 | $ipropValues = new BitrixIblockInheritedPropertyElementValues( $arParams['IBLOCK_ID'], $arResult["ID"] ); $arResult["IPROPERTY_VALUES"] = $ipropValues->getValues(); | meta values, bitrix | 28005 | Получить в Битрикс метаданные элемента |
315 | Модуль конвертации картинок для Битрикс https://marketplace.1c-bitrix.ru/solutions/dev2fun.imagecompress/ | битрикс, изображения | 100 | Модуль конвертации картинок для Битрикс |
316 | 'cache' => array( 'value' => array ( 'type' => 'memcache', 'memcache' => array( 'host' => 'localhost', 'port' => '11211' ), 'sid' => $_SERVER["DOCUMENT_ROOT"]."#01" ), ), | memcached, bitrix | 300 | настройка memcached в bitrix в файле .settings.php |
317 | $info = pathinfo($file); $file_name = basename($file,'.'.$info['extension']); | php, filename | 700 | php имя файла без расширения по УРЛ файла |
318 | последний день месяца $d = new DateTime('now'); $priceValidUntil = $d->format('Y-m-t'); | php, date | 890 | последний день месяца на php |
319 | # Удаляем index.php из адреса RewriteCond %{THE_REQUEST} ^GET.*index.php [NC] # Не применяем к админке, иначе перестает работать страница Highload-блоки RewriteCond %{REQUEST_URI} !/bitrix/admin/.* [NC] RewriteCond %{REQUEST_URI} !^/bitrix/tools/ [NC] RewriteRule (.*?)index.php/*(.*) https://%{HTTP_HOST}/$1$2 [R=301,NE,L] | htaccess, rewrite, bitrix | 395 | Удалить index.php из УРЛ редиректом, кроме админки Битрикс |
320 | async function getRutubePreview(id) { let url = `https://rutube.ru/api/video/${id}/thumbnail/`; let response = await fetch(url); if (response.ok) { let json = await response.json(); console.log(json.url); return json.url; } else { return `{"error": "Ошибка HTTP: ${response.status}")`; } } getRutubePreview('86da488c8e7f1427049c2f2fea207989'); | js, rutube thumbnail url | 100 | Получить превью Рутуб с помощью Яваскрипт |
321 | function log_error($message) { file_put_contents('php_errors.log', date('Y-m-d H:i:s')." - ".$message.PHP_EOL); } | php, log to file | 200 | Лог в файл php |