Полезные коды в PHP и MySQL

8.44K
.
Писал когда-то, МБ кому-то пригодится
/**
 * Функция позволяет узнать будет ли слово
 * одинаково если его перевернуть задом наперед
 * Работает только с англ. яз.
 *
 * @param string $string строка для проверки
 * @param bool   $case   без учета регистра символов
 *
 * @return bool
 * @author Jahak <ya.jahak@yandex.ru>
 */
function isRev($string, $case = false)
{
    if ( $case )
    {
        $string = strtolower($string);
    }
    return strrev($string) === $string;
}

// Пример
$array = array(
    'php', 'Php', 'pHp', 'phP', 'PHp',
    'pHP', 'PHP', 'mi4ok', 'aslkjhygd', '744957'
);
foreach ( $array as $value )
{
    if ( isRev($value) )
//    if ( !isRev($value) )
//    if ( isRev($value, true) )
//    if ( !isRev($value, true) )
    {
        echo $value . '<br>';
    }
}
.
# Jahak (06.10.2015 / 14:05)
Писал когда-то, МБ кому-то пригодится
Уже было такое на здешнем форуме. Можно же и ещё короче записать
<?php
function palindrome($string) {
    $string = str_replace(' ', '', mb_strtolower($string, 'UTF-8'));
    $result = $string == implode(array_reverse(preg_split('||u', $string))) ? 'Палиндромная строка' : 'Простая строка';
    return $result;
}
echo palindrome('А роза упала на лапу Азора'); // Выведет "Палиндромная строка"
.
ДоХтор, Вот точно, это же палиндром называется, а я забыл, не знал что тут уже было такое
.
(\/)____o_O____(\/)
переписал функцию, понадобилось отправлять запросы ajax
function koecurl($url, $post = '', $mode = array()) {

    $defaultmode = array('charset' => 'utf-8', 'ajax' => 0, 'ssl' => 0, 'cookie' => 1, 'headers' => 0, 'useragent' => 'Opera/9.80 (Windows NT 5.1; U; ru) Presto/2.10.229 Version/11.61');

    foreach ($defaultmode as $k => $v) {
        if (!isset($mode[$k]) ) {
            $mode[$k] = $v;
        }
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, $mode['headers']);
    if (!$mode['ref']) {
        curl_setopt($ch, CURLOPT_REFERER, $url);
    } else {
        curl_setopt($ch, CURLOPT_REFERER, $mode['ref']);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $mode['useragent']);
    curl_setopt($ch, CURLOPT_ENCODING, $mode['charset']);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 200);
    if ($post) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }

    if ($mode['cookie']) {
        curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt');
        curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');
    }
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    if ($mode['ssl']) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    }
    if ($mode['ajax']) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Requested-With: XMLHttpRequest", "Content-Type: application/x-www-form-urlencoded; charset=UTF-8"));
    }

    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
.
Писал для себя
<?php
/**
 * Функция создает навигационную цепочку как на GitHub ;)
 *
 * @param string $string
 * @param string $link      &lt;a href=&quot;?s=%s&quot;&gt;%s&lt;/a&gt;
 * @param string $delimiter /
 *
 * @return string
 *
 * @author Jahak <ya.jahak@yandex.ru>
 */
function breadcrumb($string, $link = null, $delimiter = null)
{
    if ( (null === $link) || (substr_count($link, '%s') != 2 ) )
    {
        $link = '<a href="%s">%s</a>';
    }
    if ( (null === $delimiter) || !(is_string($delimiter) && strlen($delimiter) == 1) )
    {
        $delimiter = '/';
    }
    $arrayString = array_filter(array_map('trim', explode($delimiter, $string)));
    $arrayStringReverse = array_map('htmlspecialchars', array_reverse($arrayString));
    $return = [];
    for ( $index = 0, $count = count($arrayString); $index < $count; $index++ )
    {
        if ( 0 == $index )
        {
            $return[] = (($index == ($count - 1)) ? sprintf($link, '#', '<b>' . $arrayStringReverse[$index] . '</b>')
                                : '<b>' . $arrayStringReverse[$index] . '</b>');
        }
        else
        {
            $return[] = sprintf($link, urlencode(implode($delimiter, array_slice($arrayString, 0, -$index))), (($index == ($count - 1))
                                ? '<b>' . $arrayStringReverse[$index] . '</b>' : $arrayStringReverse[$index]));
        }
    }
    return implode(' ' . $delimiter . ' ', array_reverse($return)) . ' ' . $delimiter;
}

//Пример
$examples = [
    '/' => [
        'src', ' src/incfiles /', 'src//incfiles///classes', 'src // /incfiles// /classes/ CleanUser.php'
    ],
    '>' => [
        'api-2.0', 'api-2.0>>>lib', 'api-2.0>lib>  >  >>  >>>         >Tmdb','>>>api-2.0>lib>Tmdb>Client.php'
    ]
];
foreach ( $examples as $key => $value )
{
    echo '<b>' . $key . '</b> => [<br>' . PHP_EOL;
    foreach ( $value as $string )
    {
        echo str_repeat('&nbsp;', 4) . breadcrumb($string, null, $key) . '<br>' . PHP_EOL;
    }
    echo ']<br>' . PHP_EOL;
}
.
(\/)____o_O____(\/)
Jahak, это для статики?
.
Koenig, Да
.
Люди берегите воду - пейте пиво...
Jahak, Сп за код...
.
Koenig
(\/)____o_O____(\/)
отковырял из дампа сайта, когда то глубоко изучал данный вопрос
http://annimon.com/code/?act=v ... =4675
class KMail {

    private $mb = false;

    private $header = false;

    private $subject = '(No subject)';

    private $to = array();

    private $body = ''; 

    public function __construct() {
        $this->set_mb();    
    }   

    public function send_mail_utf8($to, $subject, $message, $header) { 
        return mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=', $message, 'MIME-Version: 1.0' . PHP_EOL . $header); 
    }

    public function send() {

        if (!$this->get_mb()) {
            throw new Exception('Ошибка установки уникального значения');            
        }

        if (!$this->get_header()) {
            $this->set_header();
        }

        if (!$this->get_body()) {
            throw new Exception('Отсутсвует тело письма');        
        }

        if (sizeof($this->to) > 0) {
            foreach($this->to as $to) {
                $this->send_mail_utf8($to, $this->get_subject(), $this->get_body() . $this->end_body(), $this->get_header());
            }    
        } else {
            throw new Exception('Отсутствует адресат');    
        }

    }

    public function add_to($mail) {
        $this->to[] = $mail;    
    }

    public function add_body_message($text) {
        $this->body .= '--' . $this->mb . PHP_EOL . 
        'Content-Type: text/plain; charset="UTF-8"' . PHP_EOL . 
        'Content-Disposition: inline' . PHP_EOL . 
        'Content-Transfer-Encoding: base64' . PHP_EOL . PHP_EOL . 
        chunk_split(base64_encode($text)) . PHP_EOL;    
    }

    public function add_body_file($file_name, $file_stream) {
        $this->body .= PHP_EOL . '--' . $this->mb . PHP_EOL .
        'Content-Type: application/octet-stream; name="' . $file_name . '"' . PHP_EOL . 
        'Content-Disposition: attachment;' . PHP_EOL . 
        ' filename="' . $file_name . '"' . PHP_EOL . 
        'Content-Transfer-Encoding: base64' . PHP_EOL . PHP_EOL . chunk_split(base64_encode($file_stream));    
    }

    public function end_body() {
        return '--' . $this->mb . '--';    
    }

    public function get_body() {
        return $this->body;    
    }

    public function set_mb() {
        $this->mb = '_=_Multipart_Boundary_' . substr(md5(uniqid(time())), 0, 8);
    }

    public function set_subject($subject) {
        if ($subject) {
            $this->subject = $subject;
        }
    }

    public function get_subject() {
        return $this->subject;
    }

    public function get_mb() {
        return $this->mb;    
    }

    public function set_header($email = 'No reply') {
        $this->header = 'Content-Type: multipart/mixed; boundary="' . $this->get_mb() . '"' . PHP_EOL . 'X-Mailer: PHP' . PHP_EOL . 'Reply-To: ' . $email . PHP_EOL;    
    }

    public function get_header() {
        return $this->header;    
    }

}


как юзать
require('kmail.class.php');

$mail = new KMail;
$mail->add_to('test@mail.ru');
$mail->add_to('annonimus@gmail.com');
$mail->set_subject('TESTUS');
$mail->add_body_message('Test mail script');
$mail->add_body_file('картинка.png', file_get_contents('mirror.png'));
$mail->add_body_file('картинка2.png', file_get_contents('mirror2.png'));
$mail->send();
.
__________________________________________________
# Koenig (27.10.2015 / 00:31)
отковырял из дампа сайта, когда то глубоко изучал данный вопрос
http://annimon.com/code/?act=v ... =4675
[php]
class KMail {

private $mb = false;

private $header = false;

priv
Полезный код
Заберу себе
Всего: 360