Functions PHP
Мелкие кирпичики для ваших проектов
Functions
function add_log($array) {
/*$fp = fopen('./log.txt', "a");
fwrite($fp,
'['.date("d.m.Y H:i.s").'] '.
print_r($array, true).
"\n\n\n"
);
fclose($fp);*/
$maximum_size = 1048576; // 1mb
$text = "\n\n\n@ ".date("Ymd H:i.s")."\n".print_r($array, true);
$url = $_SERVER['DOCUMENT_ROOT'].'/logs/log.php'; // $_SERVER['DOCUMENT_ROOT'].
if (file_exists($url)) {
if (filesize($url) > $maximum_size) {
rename($url, $_SERVER['DOCUMENT_ROOT'].'/logs/log_'.date("Ymd_His").'.php');
$text = "<?php return; ?>$text";
}
} else {
$text = "<?php return; ?>$text";
}
$file = fopen($url, "a");
fwrite($file, $text);
fclose($file);
}
function string_to_int($text) {
$text = strval($text);
$text = preg_replace("/[^0-9]/", '', $text);
return (int) $text;
}
function get_date_now() {
return date('Y-m-d H:i:s');
}
function get_rand_string($length) {
if(!isset($length)) $length = 64;
$result = '';
$chars = '012345678901234567890123456789'.
'abcdefghijklmnopqrstuvwxyz'.
'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
//'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'.
//'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ';
$char_i_last = strlen($chars) - 1;
for ($i = 0; $i < $length; $i++) {
$result .= $chars[rand(0, $char_i_last)];
}
return $result;
}
function check($type, $value) {
$length = strlen($value);
switch ($type) {
case 'name': {
if ($length < 3 || $length > 30) return ['ok' => 0, 'text' => 'Количество символов должно быть от 3 до 30'];
if (!preg_match("/^[-a-zA-Zа-яА-ЯёЁ]+[-a-zA-Z-а-яА-ЯёЁ]$/u", $value)) return ['ok' => 0, 'text' => 'Должны присутствовать только буквы русского или английского алфавита'];
// https://ru.stackoverflow.com/questions/417568/preg-match-понимает-не-все-русские-буквы
return ['ok' => 1];
}
case 'email': {
if ($length < 5) return ['ok' => 0, 'text' => 'Почта должна быть более 5 символов'];
if ($length > 50) return ['ok' => 0, 'text' => 'Почта должна быть менее 50 символов'];
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) return ['ok' => 0, 'text' => 'Почта не валидная'];
return ['ok' => 1];
}
case 'date': { // 17.12.1994
// Собрать заново
$value_array = explode('.', $value);
$day = (int) $value_array[0];
$month = (int) $value_array[1];
$year = (int) $value_array[2];
unset($value_array);
if (!checkdate($month, $day, $year)) return ['ok' => 0, 'text' => 'НЕ корректная дата'];
if ((strtotime("$year-$month-$day") - strtotime('-18 year')) > 0) return ['ok' => 0, 'text' => 'Вам меньше 18 лет'];
//return ['ok' => 0, 'text' => 'Удачно'];
return ['ok' => 1];
}
}
return ['ok' => 0, 'text' => 'Нет такой проверки'];
}
function phone_form_8($phone) {
$quantity =11;
$phone = strval($phone);
$phone = preg_replace("/[^0-9]/", '', $phone);
$phone = preg_replace("/[+\-\s()]/", '', $phone);
$phone = preg_replace("/^7/", '8', $phone);
//$phone = (int) $phone;
$length = strlen($phone);
if ($length > $quantity) $phone = substr($phone, $quantity);
while ($length < $quantity) { $phone = '8'.$phone; }
$phone = (int) $phone;
return $phone;
}
function phone_form_7($phone) {
$quantity = 11;
$phone = strval($phone);
$phone = preg_replace("/[^0-9]/", '', $phone);
$phone = preg_replace("/[+\-\s()]/", '', $phone);
$phone = preg_replace("/^8/", '7', $phone);
//$phone = (int) $phone;
$length = strlen($phone);
if ($length > $quantity) $phone = substr($phone, $quantity);
while ($length < $quantity) { $phone = '7'.$phone; }
$phone = (int) $phone;
return $phone;
}
function get_file_name($url) {
return array_pop( (explode('/', $url)) );
}
function array_to_php($data, $shift) {
$type = gettype($data);
switch ($type) {
case 'string': {
return '\''.str_replace('\'', '\\\'', $data).'\'';
}
case 'object': {
return '\'OBJECT\'';
}
case 'array': {
if (count($data) === 0) return '[]';
$result_array = [];
if (array_key_first($data) === 0) {
foreach ($data as $key => $value) {
$result_array[] = array_to_php($value, ($shift+1));
}
} else {
foreach ($data as $key => $value) {
$result_array[] = '\''.$key.'\' => '.array_to_php($value, ($shift+1));
}
}
$shift_text = "\n";
while ($shift-- > 0) $shift_text .= "\t";
return '['.$shift_text."\t".implode(', '.$shift_text."\t", $result_array).$shift_text.']';
}
case 'boolean': {
return ($data ? 1 : 0);
}
case 'integer':
case 'double': {
return $data;
}
}
return '\'NOT_TYPE\'';
}
function name_to_dirs($name) {
return '/'.implode(
'/',
(str_split(
(strval($name))
))
).'.php';
}
Efficiency
function get_efficiency($name) {
return [
memory_get_usage(),
microtime(true),
$name
];
}
function count_efficiency($efficiency) {
$time = microtime(true);
$memory = memory_get_usage();
$decimals = 6;
$time -= $efficiency[1];
$memory -= $efficiency[0]; ; // 1024 * 1024
$time = number_format($time, $decimals, '.', '');
$memory = number_format(($memory/1048576), $decimals, '.', '');
$memory_max = ini_get('memory_limit');
$time_max = ini_get('max_execution_time');
echo '<table class="table_efficiency">
<caption>Efficiency '.$efficiency[2].'</caption>
<tbody><tr>
<th>Name</th>
<th>Type</th>
<th>Maximum</th>
<th>Use</th>
<th>Use %</th>
</tr>
<tr><td>Memory</td><td>Megabytes</td><td>',$memory_max,'</td><td>',$memory,'</td><td>',number_format((100/ (int) $memory_max*$memory), $decimals, '.', ''),'</td></tr>
<tr><td>Time</td><td>Seconds</td><td>',$time_max,'</td><td>',$time,'</td><td>',number_format((100/$time_max*$time), $decimals, '.', ''),'</td></tr>
</tbody></table>';
}
Json
function json_to_array($string_json) {
try {
return json_decode($string_json, true);
} catch (Exception $e) {
return ['error' => $e->getMessage()];
}
}
function array_to_json($array) {
return json_encode($array);
}
File
код
function set_file($url, $text) {
$file = fopen($url, 'w');
fwrite($file, $text);
fclose($file);
if (file_exists($url)) return true;
return false;
}
function get_file($url) {
if (!file_exists($url)) return 'not file';
return file_get_contents($url);
}
function set_file_hard($url, $text) {
if (empty($url)) return;
$array = explode('/', $url);
$name_file = array_pop($array);
$url = '';
foreach($array as $i => $name) {
$url .= $name;
if (
$name !== '' &&
!is_dir($url) &&
!mkdir($url, 0777)
) return;
$url .= '/';
}
return set_file($url.$name_file, $text);
}
function set_file_cache($url, $data) {
return set_file($url, '<?php return '.array_to_php($data, 0).';');
}
Base
function get_sql() {
require($_SERVER['DOCUMENT_ROOT'].'/bitrix/php_interface/dbconn.php');
$sql = new mysqli(
$DBHost,
$DBLogin,
$DBPassword,
$DBName
);
if ($sql->connect_errno) {
add_log([$sql->connect_errno, $sql->connect_error]);
return false;
}
$sql->set_charset('utf8');
return $sql;
}
function get_sql_clear_name($text) {
$text = trim($text);
$text = preg_replace( "/[^a-zA-Z0-9_]/", '', $text);
$text = mb_strimwidth($text, 0, 255);
return $text;
}
function get_sql_clear_text($text) {
$text = trim($text);
$text = str_replace(["\r", '"', "'", '`'], '-', $text); // "\n",
if (function_exists('mb_ereg_replace')) {
return mb_ereg_replace('[\x00\x0A\x0D\x1A\x22\x27\x5C]', '\\\0', $text);
}
return preg_replace('~[\x00\x0A\x0D\x1A\x22\x27\x5C]~u', '\\\$0', $text);
// return $text;
}
function date_sql_to_show($date) {
$date_old = $date;
//'1980-12-08 00:00:00'
$date = explode(' ', $date);
$date = explode('-', $date[0]);
if (!isset($date[2]) || !isset($date[1])) return $date_old;
$date = implode('.', [$date[2], $date[1], $date[0]]);
return $date;
}
Request
function request($url, $array) {
if (
empty($url) ||
empty($array)
) return false;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($array));
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Только возврат, а не echo
if( ! $result = curl_exec($curl) ) $result = curl_error($curl);
curl_close($curl);
return $result;
}
Catalog
function get_sections($use_cache) {
$cache_url = $_SERVER['DOCUMENT_ROOT'].'/app/database/sections.php';
if ($use_cache && file_exists($cache_url)) {
return require($cache_url);
}
$result = [];
$children = [];
$to_int = ['ID', 'SORT', 'IBLOCK_SECTION_ID'];
$sql = get_sql();
if ($query = $sql->query(
"SELECT
`ID`,
`IBLOCK_SECTION_ID`,
`SORT`,
`NAME`,
`CODE`
FROM `b_iblock_section`
WHERE
`IBLOCK_ID` = '9' AND
`ACTIVE` = 'Y'
LIMIT 100", //ORDER BY `SORT`
MYSQLI_USE_RESULT)) {
while ($array = $query->fetch_array(MYSQLI_ASSOC)) {
if ($array['NAME'] === 'OZ') continue;
foreach ($to_int as $i => $name)
$array[$name] = (int) $array[$name];
$result[$array['ID']] = $array;
if (empty($array['IBLOCK_SECTION_ID'])) continue;
if (!isset($children[$array['IBLOCK_SECTION_ID']])) {
$children[$array['IBLOCK_SECTION_ID']] = [$array['ID']];
continue;
}
$children[$array['IBLOCK_SECTION_ID']][] = $array['ID'];
}
}
$sql->close();
foreach ($children as $id => $value)
$result[$id]['children'] = $value;
set_file_cache($cache_url, $result);
return $result;
}
CSV
function csv_to_array($csv_string) {
$result = [];
$lines = explode("\n", $csv_string);
foreach ($lines as $i => $line) {
$array = explode('"', $line);
foreach ($array as $i0 => $bit) {
if ($i0 % 2 === 1) continue;
$array[$i0] = str_replace(',', ';', $bit);
}
$line = implode('"', $array);
$array = explode(';', $line);
foreach ($array as $i0 => $bit) {
$bit = trim($bit);
if ($bit[0] === '"')
$bit = trim( (substr($bit, 1, -1)) );
$array[$i0] = $bit;
}
$result[] = $array;
}
return $result;
}
Resize image
function resize_image(
$image_url,
$new_image_url,
$new_width = 140,
$new_height = 140,
$quality = 80,
$crop = false
) {
if (!file_exists($image_url)) return false;
$format = strtolower(
(array_pop(
(explode('.', $image_url))
))
);
list($width, $height) = getimagesize($image_url);
$difference = $width / $height;
if ($crop)
if ($width > $height)
$width = ceil(
$width - ($width * abs($difference - $new_width / $new_height))
);
else
$height = ceil(
$height - ($height * abs($difference - $new_width / $new_height))
);
else
if ($new_width / $new_height > $difference)
$new_width = $new_height * $difference;
else
$new_height = $new_width / $difference;
$new_image = imagecreatetruecolor($new_width, $new_height);
if ($format === 'png') {
$image = imagecreatefrompng($image_url);
//imagealphablending($new_image , false);
//imagesavealpha($new_image , true);
} else
$image = imagecreatefromjpeg($image_url);
imagecopyresampled(
$new_image, $image,
0, 0, 0, 0,
$new_width, $new_height,
$width, $height
);
//header('Content-Type: image/jpeg');
//imagejpeg($new_image);
if ($format === 'png') {
//imagealphablending($new_image , false);
//imagesavealpha($new_image , true);
imagepng($new_image, $new_image_url, round((100 - $quality) / 10));
} else
imagejpeg($new_image, $new_image_url, $quality);
return true;
}
resize_image($url, './f.jpg', 140, 140);