User Tools

Site Tools


programming:php

PHP Fiddle

Multibyte UCFirst

function mb_ucfirst($string)
{
    return mb_strtoupper(mb_substr($string, 0, 1)).mb_strtolower(mb_substr($string, 1));
}
function find_closest_ip($my_ip, $ips) {
    $my_ip = ip2long($my_ip);
    $distances = array();
    foreach ($ips as $ip) {
        $distances[$ip] = ceil(log(($my_ip ^ ip2long($ip)) + 1, 2));
    }
    return array_search(min($distances), $distances);
}
function check_email($email) {
    $atom = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]'; // znaky tvořící uživatelské jméno
    $domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])'; // jedna komponenta domény
    return eregi("^$atom+(\\.$atom+)*@($domain?\\.)+$domain\$", $email);
}

Number with leading zeros

sprintf('%02d', $month)

Import XML

$xmlendpoint = 'http://blabla/endpoint';

setlocale(LC_NUMERIC, 'C');

$file = file_get_contents($xmlendpoint, false);
$xml = new SimpleXMLElement($file);

foreach ($xml->neco as $neco) {
sql("INSERT INTO neco VALUES ('".$neco->typ."','".$neco->evcj."','".$neco->popis."')");
}

Sort Array by key

foreach($xml->sap as $id) {
	$znakSort[] = $id->znak;
}
array_multisort($znakSort, SORT_ASC, SORT_STRING, $xml->sap);

Input filtering (UTF8)

function filterinput($string)
{
    preg_match_all("/[\@\\.\s\w\p{L}\p{N}\p{Pd}]/u", $string, $result);
    return implode('', $result[0]);
}

Compile PHP to Windows EXE

Insert image to HTML

function getDataURI($imagePath) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $type = $finfo->file($imagePath);
    return 'data:'.$type.';base64,'.base64_encode(file_get_contents($imagePath));
}

//Use the above function like below:
echo '<img src="'.getDataURI('./images/my-file.svg').'" alt="">';
echo '<img src="'.getDataURI('./images/my-file.png').'" alt="">';

cURL fetch IMAP

$ch = curl_init();

      if($ch) {

        /* Set username and password */ 
        curl_setopt($ch, CURLOPT_USERNAME, "user");
        curl_setopt($ch, CURLOPT_PASSWORD, "secret");

        /* This will fetch message 1 from the user's inbox */ 
        curl_setopt($ch, CURLOPT_URL, "imap://imap.example.com/INBOX/;UID=1");

            $proxy = '127.0.0.1:8888';
            //$proxyauth = 'user:password';

            curl_setopt($ch, CURLOPT_PROXY, $proxy);
            //curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 1);


        /* Perform the fetch */ 
        $res = curl_exec($ch);

        /* Always cleanup */ 
        curl_close($ch);
      }
programming/php.txt · Last modified: 2018/08/21 22:30 by Jan Forman