|
Ok!
|
|
|
Ok!
|
---|---|---|---|---|
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 |
318 | последний день месяца $d = new DateTime('now'); $priceValidUntil = $d->format('Y-m-t'); | php, date | 890 | последний день месяца на php |
317 | $info = pathinfo($file); $file_name = basename($file,'.'.$info['extension']); | php, filename | 700 | 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 |
312 | <?=(date('W') + 5) % 5 + 1?> | php, чередование | 39080 | Раз в неделю из пяти: первую - одно, вторую - второе. 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 | Сканировать папку и вывести только изображения |
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 для вставки видео Рутуб по кнопке с превью картинкой |
300 | $today = new DateTime(); $ny1 = new DateTime('December 25'); $ny2 = new DateTime('January 9'); if ($today < $ny2 && $today > $ny1) { ... } | php, ny, новый год | 45800 | Автоматический показ объявления о новогодних праздниках php |
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 |
276 | preg_replace('~D~', '', $phone); | regex, php, phone, телефон регекс | 20530 | Оставить только цифры в номере телефона |
269 | if ($handle = opendir('.')) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { echo "$entry "; } } closedir($handle); } | readdir, php | 290 | Прочесть файлы в папке |
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 |
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 | Генераторы особенно полезны в сценариях обработки больших файлов или потоков данных, например при построчном считывании большого файла |
255 | class Foo extends \stdClass // to fix Deprecated: Creation of dynamic property | php, deprecation, dynamic | 650 | Исправление ошибки создания динамически свойства в php8.2 |
250 | <?php $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array( PDO::ATTR_PERSISTENT => true )); ?> | pdo, php, mysql, постоянное соединение | 2200 | Настройка постоянного соединения с MySQL |
248 | <?php $haystack = 'abcde'; $needle = 'f'; strpos($haystack,$needle) !== FALSE OR print "$needle not in $haystack"; | php, print | 100 | Как использовать возвращаемое print значение (1) |
246 | JSON_UNESCAPED_UNICODE => 256 | unicode, json, php | 240 | Числовое представление константы JSON_UNESCAPED_UNICODE |
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 |
222 | echo <<<EOH ---------- ----------- -- ---------- результат значение оп тест ---------- ----------- -- ---------- EOH; | eoh, php print formated | 12090 | Форматированная строка в 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 |
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 сколько лет с тех пор по-русски |
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 мая) |
210 | return ($month === 12 && $day >= 15) || ($month === 1 && $day < 10); | новый год, php | 20090 | Вернёт true если новогодние праздники близко |
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 |
156 | basename(__DIR__) | php, родительская папка, parent folder | 120 | одительская папка php текущей директории без начального слеш |
153 | print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); выведет 1988-08-01 | печать даты, php | 5900 | Печать даты в php |
147 | $r = str_replace("ʹ", "", transliterator_transliterate('Any-Latin; Latin-ASCII', "Пробежаться на травалотре")); echo $r; | транслитератор, php, translit | 1470 | Транслитератор на php |
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 скрипт пагинации |
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 |
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 |
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 |
74 | print <<<INDEX_MED INDEX_MED; | печать блока php | 340 | Форматированная печать блока php |
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 |
62 | count(preg_grep('~^[0-9]$~', str_split($str))) | считать сколько цифр, php цифр, count digits | 2390 | Посчитать число цифр в строке php |
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 | Сформировать файл и передать его на загрузку в браузер |
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 |
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 | Парсер страницы или блока страницы |
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 |
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 |
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 |
5 | function cmp($a,$b){ return strtotime($a['PROPERTY_DATER_VALUE'])<strtotime($b['PROPERTY_DATER_VALUE']); } usort($item_happ,"cmp"); | функция, сравнение дат, даты, php | 30 | Пример функции сравнения в php |
3 | setlocale( LC_ALL, "ru_RU.UTF-8" ); strftime("%A %e %B %Y", mktime(0, 0, 0, 1, 1, 2016)); | дата по-русски, php дата | 100 | Вывод даты в php в русской локали |
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 | Транслит |