Настройки анимации по умолчанию для всего документа:
DIV, SPAN, UL, LI, A, IMG, INPUT, BUTTON { -webkit-transition: ease 0s, background 0.2s ease 0s, height 0.3s ease 0s, filter 0.3s ease 0s, box-shadow 0.3s ease 0s, opacity 0.3s, linear-gradient 0.3s ease 0s, border 0.3s ease 0s, color 0.3s ease 0s, margin 0.3s ease 0s; -moz-transition: ease 0s, background 0.2s ease 0s, height 0.3s ease 0s, filter 0.3s ease 0s, box-shadow 0.3s ease 0s, opacity 0.3s, linear-gradient 0.3s ease 0s, border 0.3s ease 0s, color 0.3s ease 0s, margin 0.3s ease 0s; -o-transition: ease 0s, background 0.2s ease 0s, height 0.3s ease 0s, filter 0.3s ease 0s, box-shadow 0.3s ease 0s, opacity 0.3s, linear-gradient 0.3s ease 0s, border 0.3s ease 0s, color 0.3s ease 0s, margin 0.3s ease 0s; transition: ease 0s, background 0.2s ease 0s, height 0.3s ease 0s, filter 0.3s ease 0s, box-shadow 0.3s ease 0s, opacity 0.3s, linear-gradient 0.3s ease 0s, border 0.3s ease 0s, color 0.3s ease 0s, margin 0.3s ease 0s; }
@font-face{ font-family: RobotoBold; src: url("../fonts/Roboto-Bold.ttf"); } @font-face{ font-family: RobotoLight; src: url("../fonts/Roboto-Light.ttf"); } @font-face{ font-family: RobotoMedium; src: url("../fonts/Roboto-Medium.ttf"); } @font-face{ font-family: RobotoRegular; src: url("../fonts/Roboto-Regular.ttf"); }
Оптимальная сетка деления медиа запросов под Framework Bootstrap
//---------------------- // MEDIA //---------------------- // FULL SCREAN @media screen and (max-width: 5000px) { } // COL-XL @media screen and (max-width: 1920px) { } // COL-LG @media screen and (max-width: 1200px) { } // COL-MD @media screen and (max-width: 992px) { } // COL-SM @media screen and (max-width: 768px) { } // COL-XS @media screen and (max-width: 575px) { } // MICRO COL-XS @media screen and (max-width: 480px) { }
Для определенного количества колонок
.text_demoBlock { padding-bottom:20px; /*отступ снизу*/ width:100%; /*указываем общую ширину блока с колонками*/ text-align:justify; /*выравнивание текста внутри колонок*/ column-count: 3; /*количество колонок, на которое хотим разбить текст*/ -moz-column-count: 3; /*для мозилы*/ -webkit-column-count: 3; /*для webkit браузеров*/ column-gap: 40px; /*отступ между колонками*/ -moz-column-gap: 40px; -webkit-column-gap: 40px; column-rule: 1px solid #000; /*если требуется по дизайну, разделяем колонки линией*/ -moz-column-rule: 1px solid #000; -webkit-column-rule: 1px solid #000; }
Для элементов разбивки - для правильного переноса
page-break-inside: avoid; break-inside: avoid;
При задании определенной ширины
.text_demoBlock { padding-bottom:20px; /*отступ снизу*/ width:100%; /*указываем общую ширину блока с колонками*/ text-align:justify; /*выравнивание текста внутри колонок*/ column-width: 200px; /*указываем ширину колонок*/ -moz-column-width: 200px; -webkit-column-width: 200px; column-gap: 40px; /*отступ между колонками*/ -moz-column-gap: 40px; -webkit-column-gap: 40px; column-rule: 1px solid #000; /*если требуется по дизайну, разделяем колонки линией*/ -moz-column-rule: 1px solid #000; -webkit-column-rule: 1px solid #000; }
Не касающийся разбивки, но обожаемый IE...
<head> <!--[if IE]> <script type="text/javascript" src="/папка со скриптами/css3-multi-column.js"></script> <![endif]--> </head>
Более подробно тут
php_value display_errors 1 php_value display_startup_errors 1 php_value error_reporting E_ALL
php_value memory_limit 30M php_value post_max_size 100M php_value upload_max_filesize 30M AddDefaultCharset utf-8 php_flag magic_quotes_gpc Off
Редирект с / на www
RewriteCond %{HTTP_HOST} ^domain\.ru RewriteRule ^(.*)$ http://www.domain.ru/$1 [R=permanent,L] . Header set Cache-Control "max-age=2592000"
Редирект с / на https
RewriteCond %{HTTPS} =off [OR]
RewriteCond %{SERVER_PORT} !^443$ RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L]
Редирект общий
RewriteCond %{HTTPS} off RewriteCond %{HTTP:X-Forwarded-Proto} !http RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [QSA,L] RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [R=permanent,L] . Header set Cache-Control "max-age=2592000"
RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?getwork.ru.*$ [NC] RewriteRule \.(jpeg|bmp|gif|png|css|zip|pdf|txt|doc)$ - [NC,F,L] <IfModule mod_rewrite.c> RewriteEngine on RewriteRule !(js|ico|gif|jpg|png|css|swf|flv|libraries|maint|admin|login|logout|reg) index.php [QSA,L] </IfModule> <Files "*.conf"> deny from all </Files> <Files ~ "\.(inc|conf|cfg)$"> deny from all </Files>
"Думаю, что не только я, но и другие пользователи Chrome под Windows, на многих сайтах замечали проблемы c отображением нестандартных шрифтов. Читать текст на таких сайтах можно, но глазам больно. Я бы так все это и продолжал терпеть, но на одном из недавних собственных проектов этот вопрос встал буквально ребром. Решил разобраться во всем досконально." (текст cp habrahabr)
Такие проблемы возможны при полном указании ссылок на сайте, которые при переносе сложно найти и изменить, но так же не редки и cross-domain ошибки. Эти ошибки связанны со склейкой доменнов, т.е. редиректов с / на WWW
Вот одно из решений:
<ifModule mod_headers.c> <IfModule mod_headers.c> <FilesMatch "\.(eot|font.css|otf|ttc|ttf|woff)$"> Header set Access-Control-Allow-Origin "*" </FilesMatch> </IfModule> <IfModule mod_mime.c> # Web fonts AddType application/font-woff woff AddType application/vnd.ms-fontobject eot # Browsers usually ignore the font MIME types and sniff the content, # however, Chrome shows a warning if other MIME types are used for the # following fonts. AddType application/x-font-ttf ttc ttf AddType font/opentype otf # Make SVGZ fonts work on iPad: # https://twitter.com/FontSquirrel/status/14855840545 AddType image/svg+xml svg svgz AddEncoding gzip svgz </IfModule> # rewrite www.example.com → example.com <IfModule mod_rewrite.c> RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L] </IfModule>
Включение GZIP в файле .htaccess
Через mod_deflate:
<IfModule mod_deflate.c> # Compress HTML, CSS, JavaScript, Text, XML and fonts AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/vnd.ms-fontobject AddOutputFilterByType DEFLATE application/x-font AddOutputFilterByType DEFLATE application/x-font-opentype AddOutputFilterByType DEFLATE application/x-font-otf AddOutputFilterByType DEFLATE application/x-font-truetype AddOutputFilterByType DEFLATE application/x-font-ttf AddOutputFilterByType DEFLATE application/x-javascript AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE font/opentype AddOutputFilterByType DEFLATE font/otf AddOutputFilterByType DEFLATE font/ttf AddOutputFilterByType DEFLATE image/svg+xml AddOutputFilterByType DEFLATE image/x-icon AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/xml # Remove browser bugs (only needed for really old browsers) BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html Header append Vary User-Agent </IfModule>
Через mod_gzip:
<ifModule mod_gzip.c> mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$ mod_gzip_item_include mime ^application/x-javascript.* mod_gzip_item_include mime ^text/.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.* mod_gzip_item_exclude mime ^image/.* mod_gzip_item_include handler ^cgi-script$ </ifModule>
Задание определеного интервала для типов файлов
<ifModule mod_headers.c> # Все html и htm файлы будут храниться в кэше браузера один день <FilesMatch "\.(html|htm)$"> Header set Cache-Control "max-age=43200" </FilesMatch> # Все css, javascript и текстовые файлы будут храниться в кэше браузера одну неделю <FilesMatch "\.(js|css|txt)$"> Header set Cache-Control "max-age=604800" </FilesMatch> # Все флэш файлы и изображения будут храниться в кэше браузера один месяц <FilesMatch "\.(flv|swf|ico|gif|jpg|jpeg|png)$"> Header set Cache-Control "max-age=2592000" </FilesMatch> # Отключаем кеширование php и других служебных файлов <FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$"> Header unset Cache-Control </FilesMatch> </IfModule>
Через модуль mod_expires
- Apache HTTP Server Version 2.4+
Этот модуль контролирует настройку Expires HTTP заголовка и максимального возраста директивы заголовка Cache-Control HTTP в ответах сервера. Дату окончания срока действия можно установить относительно: либо времени исходного файла; либо ко времени доступа клиента.
Эти заголовки HTTP являются инструкциями клиенту о достоверности сохранения документа в кэше.
<ifModule mod_headers.c> ExpiresActive On ExpiresDefault "access plus 5 seconds" # Включаем кэширование изображений и флэш на месяц ExpiresByType image/x-icon "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType image/gif "access plus 1 month" ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds" # Включаем кэширование css, javascript и текстовых файлов на одну неделю ExpiresByType text/css "access plus 3600 seconds" ExpiresByType text/javascript "access plus 3600 seconds" ExpiresByType application/javascript "access plus 3600 seconds" ExpiresByType application/x-javascript "access plus 3600 seconds" # Включаем кэширование html и htm файлов на один день ExpiresByType text/html "access plus 43200 seconds" # Включаем кэширование xml файлов на десять минут ExpiresByType application/xhtml+xml "access plus 600 seconds" </IfModule>
<script type="text/javascript"> jQuery(document).ready(function(){ jQuery.when( jQuery.ajax({ type: "GET", url: "https://api-maps.yandex.ru/2.1/?lang=ru-RU", dataType: "script", async: true, cache: true }) .done(function(script, textStatus){ /* -- MAP WORKS -- */ }) .fail(function(jqxhr, settings, exception){}), ).done(function(){}); }); </script>
<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script> <script type="text/javascript"> ymaps.ready(init); var myMap, myPlacemark, centerMap; if(jQuery(document).width() < 500){ centerMap = [44.768411,37.704457]; } else { centerMap = [44.768411,37.704457]; } function init(){ myMap = new ymaps.Map("map", { center: centerMap, zoom: 17, controls: [], controls: ['smallMapDefaultSet'], //zoomControl: false, //scaleControl: false, //scrollwheel: false, behaviors: [] }); myMap.behaviors.enable('drag'); myPlacemark = new ymaps.Placemark([44.768411,37.704457], { hintContent: 'ул. ---, д 12', }); myMap.geoObjects.add(myPlacemark); } </script> <div id="map"></div>
<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script> <script type="text/javascript"> ymaps.ready(init); var myMap, myPlacemark; function init(){ myMap = new ymaps.Map("map", { center: [52.81400705, 55.39457876], zoom: 3, controls: [], controls: ['smallMapDefaultSet'], behaviors: [] }); myMap.behaviors.enable('drag'); var arrLocal = [ [ [55.75399400, 37.62209300], 'Москва' ], [ [54.72865424, 56.03041250], 'Уфа' ], [ [55.14733041, 59.69741200], 'Златоуст' ], [ [55.15336244, 61.39170200], 'Челябинск' ], [ [53.19113025, 63.60501600], 'Костанай' ], [ [51.15181486, 71.48300800], 'Астана' ], [ [50.40587702, 80.28271050], 'Семей' ], [ [56.78879801, 60.60339450], 'Екатеринбург' ], [ [60.92827028, 76.55570850], 'Нижневартовск' ], [ [57.13726821, 65.54499550], 'Тюмень' ] ], myCollection = new ymaps.GeoObjectCollection( {}, { iconLayout: 'default#image', iconImageHref: '/images/map-marker_all_1.png', iconImageSize: [21, 30], //iconImageOffset: [-30, -10] } ); // ОБЩИЕ метки jQuery.each(arrLocal, function(index, value){ //console.log(value); myCollection.add(new ymaps.Placemark(value[0], { hintContent: value[1], } )); }); // СВОЯ метка myCollection.add(new ymaps.Placemark([44.71029965, 37.77731181], { hintContent: 'Мы находимся здесь', },{ iconImageHref: '/images/map-marker.png' } )); // Добавляем коллекцию на карту. myMap.geoObjects.add(myCollection); // Устанавливаем карте центр и масштаб так, чтобы охватить коллекцию целиком. myMap.setBounds(myCollection.getBounds()); } </script>
<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script> <script type="text/javascript"> <script type="text/javascript"> ymaps.ready(init); var myMap, myPlacemark; function init(){ myMap = new ymaps.Map("mapObj", { center: [52.81400705, 55.39457876], zoom: 3, controls: [], controls: ['smallMapDefaultSet'], behaviors: [] }); myMap.behaviors.enable('drag'); var myCollection; var myCollection = new ymaps.GeoObjectCollection( {}, { iconLayout: 'default#image', iconImageSize: [28, 40], iconImageOffset: [-14, -40] } ); <?php foreach($arr_obj AS $value): ?> myCollection.add(new ymaps.Placemark([<?=$value->geo_point?>], { balloonContent: '<?=$value->baloon_block?>', hintContent: '<?=$value->hint?>', }, { iconImageHref: '<?=$value->mapIcon?>', // Отключаем кнопку закрытия балуна. balloonCloseButton: true, // Балун будем открывать и закрывать кликом по иконке метки. hideIconOnBalloonOpen: false } )); <?php endforeach; ?> // Добавляем коллекцию на карту. myMap.geoObjects.add(myCollection); // Устанавливаем карте центр и масштаб так, чтобы охватить коллекцию целиком. myMap.setBounds(myCollection.getBounds()); myMap.setZoom(parseFloat(myMap.getZoom()) - 1); //myMap.setZoom(myMap.getZoom()); } </script>
<?php CModule::IncludeModule("iblock"); $obj_place = CIBlockElement::GetList( Array('NAME' => 'ASC'), array( 'IBLOCK_ID' => 3, 'PROPERTY_PLACE_OTEL' => $id_hotel, ), false ); $result_items = array(); while($res_place = $obj_place->getNext()){ $obj_prop = CIBlockElement::GetProperty(3, $res_place['ID'], Array(), Array()); $tmpArr = array(); while($ar_prop = $obj_prop->getNext()){ $tmpArr[$ar_prop['CODE']] = $ar_prop; } $result_items[$res_place['ID']] = array( 'NAME' => $res_place['NAME'], 'PROP' => $tmpArr ); } ?> <div class="mapCatAll"> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <h2>Выберите объект на карте</h2> </div> </div> </div> <div id="mapCatAll"> </div> <div class="blockOneChildMap"></div> </div> <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script> <script type="text/javascript"> ymaps.ready(init); var myMap, myPlacemark; function setIcon(){ //myMap.IGeoObject.setIconContent('iconImageHref', '/img/icons/map_default.png'); } function init(){ myMap = new ymaps.Map("mapCatAll", { center: [52.81400705, 55.39457876], zoom: 3, controls: [], controls: ['smallMapDefaultSet'], behaviors: [] }); myMap.behaviors.enable('drag'); var myCollection = new ymaps.GeoObjectCollection( {}, { iconLayout: 'default#image', iconImageHref: '/img/icons/map_default.png', iconImageSize: [18, 24], iconImageOffset: [-9, -24] } ); <?php foreach($result_items AS $id_h => $values): ?> var yPl = new ymaps.Placemark([$values['PROP']['GEOLOCATION']['VALUE']?>], { //balloonContent: '<?=$values['PROP']['ADRES']['VALUE']?>', hintContent: '<?=$values['NAME']?>', }, { iconImageHref: '/img/icons/map_default.png', // Отключаем кнопку закрытия балуна. balloonCloseButton: false, // Балун будем открывать и закрывать кликом по иконке метки. hideIconOnBalloonOpen: true, classed: 'class', idobject: '<?=$id_h?>' } ); yPl.events .add('click', function (e) { myCollection.each(function(a){a.options.set('iconImageHref', '/img/icons/map_default.png')}); /* if(e.get('target').options.get('classed') == 'active'){ e.get('target').options.set('classed', 'class'); jQuery('.mapCatAll .blockOneChildMap').css('display', 'none'); e.get('target').options.set('iconImageHref', '/img/icons/map_default.png'); } else { */ e.get('target').options.set('classed', 'active'); post = {urlArr:'<?=$APPLICATION->GetCurPage()?>', post_dateFrom:'<?=$_SESSION['dateIn']?>', post_dateTo:'<?=$_SESSION['dateOut']?>', id_hotel:'<?=$id_h?>'}; jQuery.ajax({ url : "/page_inc/get_viewHotelOnMap.php", type : 'POST', data : {'post':JSON.stringify(post), 'func':'getObj'}, cache : false, success: function(data){ //console.log('success - '+data); } }) .done( function(data){ console.log(data); data = JSON.parse(data); //console.log(data); if( data.id ){ jQuery('.mapCatAll .blockOneChildMap').html(''); jQuery('.mapCatAll .blockOneChildMap').append(data.message); } else { jQuery('.mapCatAll .blockOneChildMap').html(''); jQuery('.mapCatAll .blockOneChildMap').append("<h3>ERROR</h3>"); } } ) .fail( function(){ alert('Error'); } ); jQuery('.mapCatAll .blockOneChildMap').css('display', 'block'); e.get('target').options.set('iconImageHref', '/img/icons/map_hover.png'); /*}*/ }) .add('mouseenter', function (e) { //e.get('target').options.set('iconImageHref', '/img/icons/map_hover.png'); }) .add('mouseleave', function (e) { //e.get('target').options.set('iconImageHref', '/img/icons/map_default.png'); }); myCollection.add(yPl); <?php endforeach; ?> // Добавляем коллекцию на карту. myMap.geoObjects.add(myCollection); // Устанавливаем карте центр и масштаб так, чтобы охватить коллекцию целиком. myMap.setBounds(myCollection.getBounds()); //myMap.setZoom(parseFloat(myMap.getZoom()) - 1); myMap.setZoom(myMap.getZoom()); } </script>
<!-- Yandex.Metrika counter --> <!-- <CODEMETRIK> - заменить на Ваш ID --> <script type="text/javascript"> (function (d, w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter<CODEMETRIK> = new Ya.Metrika({ id:<CODEMETRIK>, clickmap:true, trackLinks:true, accurateTrackBounce:true, webvisor:true, trackHash:true }); } catch(e) { } }); var n = d.getElementsByTagName("script")[0], s = d.createElement("script"), f = function () { n.parentNode.insertBefore(s, n); }; s.type = "text/javascript"; s.async = true; s.src = "https://mc.yandex.ru/metrika/watch.js"; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "yandex_metrika_callbacks"); </script> <noscript><div><img src="https://mc.yandex.ru/watch/<CODEMETRIK>" style="position:absolute; left:-9999px;" alt="" /></div></noscript> <!-- /Yandex.Metrika counter -->
Непосредственно в элементе
// <CODEMETRIK> - заменить на Ваш ID onClick="yaCounter<CODEMETRIK>.reachGoal('myCodeMetrics'); return true;" onSubmit="yaCounter<CODEMETRIK>.reachGoal('myCodeMetrics'); return true;"
в скрипте jQuery
jQuery('ELEMENT').on('event', function(){ yaCounter<CODEMETRIK>.reachGoal('myCodeMetrics'); return true; });
Для того что-бы получить список файлов необходимо использовать scandir
. Так же стоит отсечь полушеные ссылки на эту директорию и предыдущую.
Например метод получения списка файлов может выглядеть следующим образом:
public function getArrImage($directories = '/img', $fullPath = false) { $arr = array(); $arr = scandir( mb_convert_encoding($_SERVER['DOCUMENT_ROOT'] . $directories, "UTF-8", "Windows-1251") ); if( count($arr) > 3 ){ for ($i = 0; $i < count($arr); $i++) { if( $arr[$i] != 'index.php' && $arr[$i] != '.' && $arr[$i] != '..' ) { //$arrImg[] = mb_convert_encoding($arr[$i], "UTF-8", "Windows-1251"); $arrImg[] = $fullPath ? $directories . '/' . $arr[$i] : $arr[$i]; } } } return $arrImg; }
где:
$directories
- директория относительно папки WEB$fullPath
- возврат полного пути в масиве относительно папки WEBini_set('error_reporting', E_ALL); ini_set('display_errors', 1); ini_set('display_startup_errors', 1);
<?php private function getPhoneSms (string $phone) { $phoneSMSTo = $phone; $phoneSMSTo = trim($phoneSMSTo); $phoneSMSTo = preg_replace('/\(/', '', $phoneSMSTo); $phoneSMSTo = preg_replace('/\)/', '', $phoneSMSTo); $phoneSMSTo = preg_replace('/ /', '', $phoneSMSTo); $phoneSMSTo = preg_replace('/-/', '', $phoneSMSTo); $phoneSMSTo = preg_replace('/\+7/', '8', $phoneSMSTo); return $phoneSMSTo; }
Часто применяемый - гибко управляемый способ
<?php $param = array('foo'=>'bar', 'baz'=>'boom', 'cow'=>'milk', 'php'=>'hypertext processor' ); if(isset($param)){ foreach($param AS $key => $value){ if( !empty($value) ){ $postParams .= $key . '=' . $value . '&'; } } } else { $postParams = ''; }
итог:
foo=bar&baz=boom&cow=milk&php=hypertext%20processor
Использование функции php http_build_query()
<?php $param = array('foo'=>'bar', 'baz'=>'boom', 'cow'=>'milk', 'php'=>'hypertext processor' ); echo http_build_query($data) . "\n"; echo http_build_query($data, '', '&');
итог:
foo=bar&baz=boom&cow=milk&php=hypertext+processor foo=bar&baz=boom&cow=milk&php=hypertext+processor
<?php header("X-Frame-Options: Deny"); header("X-Frame-Options: Sameorigin");
<?php usort($arrResultAll, function($a, $b){ return (strnatcmp($a["product"], $b["product"])); });
<?php LoadFile "C:/SERVER/php726/php7ts.dll" LoadModule php7_module "C:/SERVER/php726/php7apache2_4.dll" PHPIniDir "C:/SERVER/php726" #AddType application/x-httpd-php .php AddType text/html .php AddHandler application/x-httpd-php .php
Этот код применяется злоумышлениками для перехвата трафика с вашего сайта, будьте внимательны если встретите этот код у себя в файлах
<script> var s = document.referrer; if (s.indexOf("google") > 0 || s.indexOf("bing") > 0 || s.indexOf("yahoo") > 0 || s.indexOf("aol") > 0) { self.location = 'http://yeezy350boost.fr/'; } </script >
Вешаем класс "onBlur
" на элемент вызывающий модальное окно, и все
<script> // blur effect jQuery('.onBlur').on('click', function(){ jQuery('BODY .container').css('filter','blur(2px)'); }); // fade effect blur jQuery('.onlineZayavka').on('hidden.bs.modal', function (e){ jQuery('BODY .container').css('filter','none'); }); </script >
Форма может быть любой
<form method="POST" action="#" name="uploadZakaz" data="modal" label="Пример, чего хочу" data-label="Пример, чего хочу" enctype="multipart/form-data"> <input class="form" name="name" type="text" value="" placeholder="Имя" required autocomplete="off"> <input class="form" name="phone" type="tel" value="" placeholder="+7 ( ) - -" required autocomplete="off"> <div class="imgPreview"> <input class="imgPreviewInput" name="UF_PHOTO" type="file" accept="image/*" value="" autocomplete="off"> </div> <button class="btn btn-success">Заказать</button> </form>
Скрипт обработки
<script> jQuery('FORM[name=uploadZakaz]').submit(function(){ var thisObj = jQuery(this), name = thisObj.find('INPUT[name=name]'), phone = thisObj.find('INPUT[name=phone]'), formDataPost = new FormData(thisObj[0]); if(name.val() == ''){ jQuery('#alertModal DIV.modal-body').html(''); jQuery('#alertModal DIV.modal-body').append("<h3>Не все поля заполненны</h3><p>Введите свое имя</p>"); jQuery('#alertModal').modal(); name.focus(); return false; } if(phone.val() == ''){ jQuery('#alertModal DIV.modal-body').html(''); jQuery('#alertModal DIV.modal-body').append("<h3>Не все поля заполненны</h3><p>Введите свой телефон</p>"); jQuery('#alertModal').modal(); phone.focus(); return false; } else { var r2 = /^\+7 \([0-9]{3}\) [0-9]{3}-[0-9]{2}-[0-9]{2}$/i; if(!r2.test(phone.val())){ jQuery('#alertModal DIV.modal-body').html(''); jQuery('#alertModal DIV.modal-body').append("<h3>Не все поля заполненны</h3><p>Введен не верный телефон</p>"); jQuery('#alertModal').modal(); phone.focus(); return false; } } // append extra fields formDataPost.append('func', 'sentLoaded'); jQuery.ajax({ url: '/phpscript.php', type: 'POST', data: formDataPost, cache: false, enctype: 'multipart/form-data', processData: false, contentType: false, success : function(){} }) .done( function(data){ data = JSON.parse(data); if( data.id ){ jQuery('#alertModal DIV.modal-body').html(''); jQuery('#alertModal DIV.modal-body').append('<h3>Спасибо за заявку!</br>Мы свяжемся с Вами в ближайшее время!</h3>'); jQuery('.onlineZayavka').modal('hide'); jQuery('#alertModal').modal(); jQuery('INPUT[name=name]').val(''); jQuery('INPUT[name=phone]').val(''); jQuery('INPUT[name=UF_PHOTO]').val(''); jQuery('.imgPreview').css('background-image', '/images/noImg.jpg');; } else { jQuery('#alertModal DIV.modal-body .blockText').html(''); jQuery('#alertModal DIV.modal-body .blockText').append("<h3>Не все поля заполненны</h3>"); jQuery('#alertModal').modal(); } }) .fail(function(data){ console.log(data); //alert('Error'); }); return false; }); </script>
Скрипт на стороне сервера
<?php /// пример if(!empty($_FILES['UF_PHOTO'])){ require_once($_SERVER['DOCUMENT_ROOT'] . '/includes/cropImage.php'); $cropImage = new \cropImage(); $dirRoot = '/images/uploads'; $dir = $_SERVER['DOCUMENT_ROOT'] . $dirRoot; if(!file_exists($dir)){ mkdir($dir, 0777, true); } $dirRootCache = '/cache/image-uploads'; $dirCache = $_SERVER['DOCUMENT_ROOT'] . $dirRootCache; if(!file_exists($dirCache)){ mkdir($dirCache, 0777, true); } $tmpName = rand(100,999) . rand(100,999) . '_' . $_FILES['UF_PHOTO']['name']; move_uploaded_file($_FILES['UF_PHOTO']['tmp_name'], $dirCache . '/' . $tmpName); $img = $dirCache . '/' . $tmpName; $createFile = !empty($_POST['name']) ? $_POST['name'] . '_' : ''; $createFile .= date('His') . '_' . $_FILES['UF_PHOTO']['name']; $cropImage->cropImages($img, $dir . '/' . $createFile, 3000, 500, 80); $img = $dirRoot . '/' . $createFile; } $subject = 'Заявка с сайта ' . $_SERVER['SERVER_NAME'] . ' с файлом'; $data = array( 'name' => !empty($_POST['name']) ? $_POST['name'] : '', 'phone' => !empty($_POST['phone']) ? $_POST['phone'] : '', 'file' => !empty($img) ? $img : '', 'label' => 'Заказ звонка с файлом', ); $mailSender = new mailTo($mailToAdres, $mailFromAdres, $subject, $data); $mailSender->sendMail(); echo json_encode( array( "id" => 1, "message" => "Ok", ));
Вся работа через командную строку
, переходим в нужную директорию (зависимость PHP > 7.1 + record on PATH).
Скачиваем файл в директорию
php -r "readfile('https://getcomposer.org/installer');" | php
В случае каких то работ - обновляем composer
php composer.phar self-update
В случае наличия файла composer.json можем произвести установку проекта согласно инструкциям
php composer.phar install
В случае прямой установки, запускаем установку (пример Symfony)
// в корень php composer.phar create-project symfony/website-skeleton // в директорию www php composer.phar create-project symfony/website-skeleton www
<?php /** * Created by PhpStorm. * User: Denis * Date: 21.08.2015 * Time: 12:47 */ namespace Framework\Libs; use Framework\Base\Classes\BaseLib; use Framework\Exceptions\CoreException; class Cacher extends BaseLib { private $_Data = null; private $_Time = null; private function __construct ($Data, $Time) { $this->_Data = $Data; $this->_Time = $Time; } static public function Cache ($file, $data, $time = 300) { if (!file_exists ("./App/Cache/" . $file . ".rch")) { $data = new self($data, time () + intval ($time)); $fp = fopen ("./App/Cache/" . $file . ".rch", "w"); flock ($fp, LOCK_EX); fputs ($fp, serialize ($data)); fflush ($fp); flock ($fp, LOCK_UN); fclose ($fp); return (bool) true; } else{ return (bool) false; } } static public function RemoveCache ($file) { if (file_exists ("./App/Cache/" . $file . ".rch")) { return unlink ("./App/Cache/" . $file . ".rch"); } else{ return (bool) false; } } /** * @param $file * @param $data * @param bool $time * @return bool */ static public function InCache ($file, &$data = false, $time = false) { if ((file_exists ("./App/Cache/" . $file . ".rch")) and ($dt = unserialize (file_get_contents ("./App/Cache/" . $file . ".rch")))) { if ($time === true) { if ($dt->_Time <= time ()) { $data = null; return (bool)false; } } $data = $dt->_Data; return (bool)true; } else { $data = null; return (bool)false; } } }
<?php private function getImageList( $urlDirectory = "./public_html/img/items/trumbnuils/" ){ $arr = array(); $arr = scandir( $urlDirectory ); if( count($arr) > 3 ){ for ($i = 0; $i < count($arr); $i++) { if( $arr[$i] != 'index.php' && $arr[$i] != '.' && $arr[$i] != '..' ) { // for Windows directory //$arrImg[] = mb_convert_encoding($arr[$i], "UTF-8", "Windows-1251"); // for Linux directory $arrImg[] = $arr[$i]; } } } return $arrImg; }
<?php $article = JControllerLegacy::getInstance('Content')->getModel('Article')->getItem($ID_ARTICLE);;
<?php require_once JPATH_SITE . '/components/com_content/helpers/route.php'; // category JRoute::_(ContentHelperRoute::getCategoryRoute($catID)) // article JRoute::_(ContentHelperRoute::getArticleRoute($artID, $catID, $sectionID)) // пример $link_polsSogl = JRoute::_(ContentHelperRoute::getArticleRoute(7)); $link_politKonf = JRoute::_(ContentHelperRoute::getArticleRoute(8));
<?php $app = JFactory::getApplication(); $doc = JFactory::getDocument(); $menu = $app->getMenu(); $lang = JFactory::getLanguage(); $template_url = $this->baseurl . '/templates/' . $this->template; $doc->addStyleSheet($template_url . '/css/template.css'); $doc->addStyleSheet('http://fonts.googleapis.com/css?family=Oswald:400,300'); // проверка на главную $is_home_page = $menu->getActive() == $menu->getDefault($lang->getTag());
<?php // проверка модуля if ($this->countModules('moduleName')) // включение модуля в материале html (админка) {loadposition my_position} // включение модуля в шаблоне материала $myblurb_modules = &JModuleHelper::getModules( 'breadcrumbs' ); foreach ($myblurb_modules as $myblurb) { $_options = array( 'style' => 'none', ); echo JModuleHelper::renderModule( $myblurb, $_options ); } // включение модуля в шаблоне материала с передачей параметров $myblurb_modules = &JModuleHelper::getModules( 'categoryChildsPortfolio' ); foreach($myblurb_modules as $myblurb){ $params = (array)json_decode($myblurb->params); $params['catid'] = array($child->id); $myblurb->params = json_encode($params); $_options = array( 'id' => $this->category->id, ); echo JModuleHelper::renderModule( $myblurb, $_options ); }
<?php $doc = JFactory::getDocument(); $template_url = JURI::base() . '/templates/' . $doc->template;
<?php require JModuleHelper::getLayoutPath('mod_menu', 'why_us_menu');
<?php $db = JFactory::getDbo(); $sql = 'SELECT id,title FROM jos_content ORDER BY id ASC'; $db->setQuery($sql); // OR execute $db->query(); // OR result // array $data_row = $db->loadRow(); // object $row = $db->loadObject(); // OR assoc $data_rows_assoc_list = $db->loadAssocList(); $data_object_list = $db->loadObjectList(); // n fields echo $db->getAffectedRows ();
<?php define('_JEXEC', 1); define('DS', DIRECTORY_SEPARATOR); define('JPATH_BASE', $_SERVER['DOCUMENT_ROOT']); require_once(JPATH_BASE . DS . 'includes' . DS . 'defines.php'); require_once(JPATH_BASE . DS . 'includes' . DS . 'framework.php'); //require_once(JPATH_BASE . DS . 'libraries' . DS . 'import.php'); require_once(JPATH_BASE . DS . 'configuration.php');
<?php // link by manufactured $linkGet = 'index.php?option=com_jshopping&view=manufacturer&layout=man&task=view&manufacturer_id=' . $manufacturer_id; $urlLink = SEFLink($linkGet, 2); // link by category $linkget = 'index.php?option=com_jshopping&view=category&layout=category&task=view&category_id=' . $category_id; $urlLink = SEFLink($linkGet, 2); // if isset child category brand $linkget = 'index.php?option=com_jshopping&view=category&layout=category&task=view&category_id=' . $product->category_id . '&manufacturer_id=' . $product->product_manufacturer_id; $db = JFactory::getDbo(); $sql = 'SELECT m.id, m.path, m.link FROM #__menu AS m WHERE m.link = "' . $linkget . '"'; $db->setQuery($sql); $data_object_list = $db->loadObjectList(); if(!empty($data_object_list)){ $prod = explode('/', $product->product_link); $urlLink = '/' . $data_object_list[0]->path . '/' . $prod[(count($prod) - 1)]; }
<?php // with Zend $entityManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); // find one record by ID, result object Doctrine $field = $entityManager->getRepository('Application\Entity\Table')->find(25); $id = $field->getId(); // find all record by find, result array objects Doctrine $fields = $entityManager->getRepository('Application\Entity\Table')->find(array('fieldTableOfDoctrineObject' => 'I find its')); $id[] = foreach($field AS $vFields) $vFields->getId(); // find all record by sql, result array data $query = $entityManager->createQuery('SELECT tbl.id FROM Application\Entity\Table AS tbl WHERE tbl.field IN (:status) AND tbl.oneZn = :oneZn') ->setParameter('status', array()) ->setParameter('oneZn', 'string') ->setMaxResults(10) ->setFirstResult(0); $result = $query->getResult();
<?php // with Zend $entityManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); // match object Doctrine $obj = $entityManager->getRepository('Application\Entity\Table')->find(25); // or create new $obj = new \Application\Entity\Table(); // record fields $obj->setId(26); $obj->setName('Peter'); ..etc // commit object $entityManager->persist($obj); // commit transaction $entityManager->flush(); // if error, then all commit object rollback
Чаще всего для удаления таблицы используют команду drop table
, а затем через запятую перечисляют список всех таблиц. Когда нужно удалить не один десяток таблиц, данный метод будет не самым лучшим выбором.
drop table table1, table2, table3;
Поэтому если таблиц много, то удобнее всего удалить сразу всю базу целиком. Проблема заключается в том, что затем вам придется снова создать эту базу. А с этим могут возникнуть трудности, если у вас нет доступа к учетной записи пользователя root
.
drop database database_name;
Как быть и что делать в этой ситуации? Самый простой способ сразу удалить все таблицы из базы MySQL — использовать утилиту mysqldump
:
mysqldump -u[USERNAME] -p[PASSWORD] --add-drop-table --no-data [DATABASE] | grep ^DROP | mysql -u[USERNAME] -p[PASSWORD] [DATABASE]
или
mysql --silent --skip-column-names -e "SHOW TABLES" DB_NAME | xargs -L1 -I% echo 'DROP TABLE `%`;' | mysql -v DB_NAME
Вместо переменных, которые указаны в квадратных скобках, вам необходимо указать свои данные.
При возникновении ошибки "mysqldump: [Warning] Using a password on the command line interface can be insecure" создаем локальные данные:
mysql_config_editor set --login-path=local --host=localhost --user=username --password
и обращаемся
mysql --login-path=local