(☞ຈل͜ຈ)☞ Главная  Статьи  Загрузчик Домой

Ok!
Ok!
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, func110flog 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>";
}
генератор, php40010Генераторы особенно полезны в сценариях обработки больших файлов или потоков данных, например при построчном считывании большого файла
255
class Foo extends \stdClass
// to fix Deprecated: Creation of dynamic property
php, deprecation, dynamic650Исправление ошибки создания динамически свойства в 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, print100Как использовать возвращаемое print значение (1)
246
JSON_UNESCAPED_UNICODE => 256
unicode, json, php240Числовое представление константы JSON_UNESCAPED_UNICODE
235
$to = '[email protected]'; 
$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, php30098Отправить письмо php
222
echo <<<EOH
 ----------   ----------- -- ----------
 результат      значение      оп тест
 ----------   ----------- -- ----------
EOH;
eoh, php print formated12090Форматированная строка в 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, php120Перенаправляем пользователя на страницу оплаты 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 . "&nbsp;" . $year_text;
}
php, years, year, лет по-русски23090php сколько лет с тех пор по-русски
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];
последний день месяца, php21090Последний день месяца PHP (напр. 31 мая)
210
return ($month === 12 && $day >= 15) || ($month === 1 && $day < 10);
новый год, php20090Вернёт 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, canonical32090php link rel canonical
156
basename(__DIR__)
php, родительская папка, parent folder120одительская папка php текущей директории без начального слеш
153
print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); выведет 1988-08-01
печать даты, php5900Печать даты в php
147
$r = str_replace("ʹ", "", transliterator_transliterate('Any-Latin; Latin-ASCII', "Пробежаться на травалотре"));
echo $r;
транслитератор, php, translit1470Транслитератор на 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, php10290Php скрипт пагинации
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 cgi1390Настроить php через cgi
100
<?if($_REQUEST) {
	if ( htmlspecialchars( $_REQUEST['mail'], 3 ) != ''
	     && strpos( htmlspecialchars( $_REQUEST['mail'], 3 ), '@' ) != false
	) {
		$to = '[email protected]'; 
		$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, mail230Отправка письма 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, php1200WP date modified php file
74
print <<<INDEX_MED
INDEX_MED;
печать блока php340Форматированная печать блока 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, php12000Ресайз картинок php
62
count(preg_grep('~^[0-9]$~', str_split($str)))
считать сколько цифр, php цифр, count digits2390Посчитать число цифр в строке 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, php10030Сформировать файл и передать его на загрузку в браузер
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, php1004PRE 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, parser1000Парсер страницы или блока страницы
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, php90Функция 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);
}
координаты, гугл, php1050Функция получения координат через Гугл на 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");
функция, сравнение дат, даты, php30Пример функции сравнения в 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, транслит, php15Транслит