/ Gists / PHP

Gists - PHP

On gists

JSONP - hlavičky

PHP

Headers ajax request - no JSONP. #

<?

header("content-type:text/html; charset=utf-8");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');

On gists

Komplexní IP

PHP

Get location by Ip address.php #

<?

function getLocationInfoByIp(){
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = @$_SERVER['REMOTE_ADDR'];
    $result  = array('country'=>'', 'city'=>'');
    if(filter_var($client, FILTER_VALIDATE_IP)){
        $ip = $client;
    }elseif(filter_var($forward, FILTER_VALIDATE_IP)){
        $ip = $forward;
    }else{
        $ip = $remote;
    }
    $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));    
    if($ip_data && $ip_data->geoplugin_countryName != null){
        $result['country'] = $ip_data->geoplugin_countryCode;
        $result['city'] = $ip_data->geoplugin_city;
    }
    return $result;
}

On gists

Download třída - pro starší projekty

PHP

download.php #

<?php 

/**
 * trida pro stazeni souboru
 * tato trida umoznuje stejnou funkcnost jak v IE tak ve firefoxu
 * 
 * @author Dostal Ales
 * @version 1.1
 * @date 13.4.2006
 *
 */
 
class DownloadFile
{

/****************************** METODY TRIDY ******************************/

    /**
     * konstruktor tridy pro stazeni souboru
     * 
     * @param    String        $file        zdroj k souboru, ktery se bude stahovat
     * 
     */
    function ExecuteDL($file)
    {
        // zjisteni, zda soubor existuje
        if (!is_file($file)) { 
            die("<b>404 Soubor neexistuje!</b>"); 
        }
    
        // ziskani informaci o souboru
        $len = filesize($file);
        $filename = basename($file);
        $file_extension = strtolower(substr(strrchr($filename,"."),1));
    
        // nastaveni content-type pro vybrane soubory
        switch( $file_extension ) 
        {
            case "pdf": $ctype="application/pdf"; break;
            case "exe": $ctype="application/octet-stream"; break;
            case "zip": $ctype="application/zip"; break;
            case "doc": $ctype="application/msword"; break;
            case "xls": $ctype="application/vnd.ms-excel"; break;
            case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
            case "gif": $ctype="image/gif"; break;
            case "png": $ctype="image/png"; break;
            case "jpeg":
            case "jpg": $ctype="image/jpg"; break;
            case "mp3": $ctype="audio/mpeg"; break;
            case "wav": $ctype="audio/x-wav"; break;
            case "mpeg":
            case "mpg":
            case "mpe": $ctype="video/mpeg"; break;
            case "mov": $ctype="video/quicktime"; break;
            case "avi": $ctype="video/x-msvideo"; break;
    
            # tyto soubory nemohou byt stazeny
            case "php":
            case "htm":
            case "html":
            case "txt": die("<b>Není možné stahovat ". $file_extension ." soubory!</b>"); 
            break;
    
            default: $ctype="application/force-download";
        }
    
        # odeslani hlavicek
        session_cache_limiter("private"); # v IE nelze stáhnout dokument pres HTTPS
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
      
        # generuje typ pro content-type
        header("Content-Type: $ctype");
    
        # co stahuji
        $header="Content-Disposition: attachment; filename=".str_replace("./download/", "", $file).";";
        header($header );
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".$len);
        readfile($file);
        exit;
        
    } # public function __construct($file)
    
} # class APIDownloadFile

?>

On gists

Youtube parser videa ( get info )

PHP

youtube-parser.php #

<?

//The Youtube's API url
    define('YT_API_URL', 'http://gdata.youtube.com/feeds/api/videos?q=');
     
    //Change below the video id.
    $video_id = '66Wi3isw3NY';
     
    //Using cURL php extension to make the request to youtube API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, YT_API_URL . $video_id);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //$feed holds a rss feed xml returned by youtube API
    $feed = curl_exec($ch);
    curl_close($ch);
     
    //Using SimpleXML to parse youtube's feed
    $xml = simplexml_load_string($feed);
     
    $entry = $xml->entry[0];
    //If no entry whas found, then youtube didn't find any video with specified id
    if(!$entry) exit('Error: no video with id "' . $video_id . '" whas found. Please specify the id of a existing video.');
    $media = $entry->children('media', true);
    $group = $media->group;
     
    $title = $group->title;//$title: The video title
    $desc = $group->description;//$desc: The video description
    $vid_keywords = $group->keywords;//$vid_keywords: The video keywords
    $thumb = $group->thumbnail[0];//There are 4 thumbnails, the first one (index 0) is the largest.
    //$thumb_url: the url of the thumbnail. $thumb_width: thumbnail width in pixels.
    //$thumb_height: thumbnail height in pixels. $thumb_time: thumbnail time in the video
    list($thumb_url, $thumb_width, $thumb_height, $thumb_time) = $thumb->attributes();
    $content_attributes = $group->content->attributes();
    //$vid_duration: the duration of the video in seconds. Ex.: 192.
    $vid_duration = $content_attributes['duration'];
    //$duration_formatted: the duration of the video formatted in "mm:ss". Ex.:01:54
    $duration_formatted = str_pad(floor($vid_duration/60), 2, '0', STR_PAD_LEFT) . ':' . str_pad($vid_duration%60, 2, '0', STR_PAD_LEFT);
     
    //echoing the variables for testing purposes:
    echo 'title: ' . $title . '<br />';
    echo 'desc: ' . $desc . '<br />';
    echo 'video keywords: ' . $vid_keywords . '<br />';
    echo 'thumbnail url: ' . $thumb_url . '<br />';
    echo 'thumbnail width: ' . $thumb_width . '<br />';
    echo 'thumbnail height: ' . $thumb_height . '<br />';
    echo 'thumbnail time: ' . $thumb_time . '<br />';
    echo 'video duration: ' . $vid_duration . '<br />';
    echo 'video duration formatted: ' . $duration_formatted;

On gists

FTP připojení a upload via PHP

PHP

FTP.php #

$connection = ftp_connect($server);

$login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);

if (!$connection || !$login) { die('Connection attempt failed!'); }

$upload = ftp_put($connection, $dest, $source, $mode);

if (!$upload) { echo 'FTP upload failed!'; }

ftp_close($connection);

On gists

czech sorting

PHP

czech sorting.php #

<?php

setlocale(LC_ALL, 'cs_CZ.UTF-8');
header("content-type: text/html; charset=UTF-8");

$arr = explode(",", "č, d, b, a, š, ř, o, x, z, ž, á, s, m");

uasort($arr, "strcoll");
echo "<pre>" . print_r($arr, 1) . "</pre>";

On gists

Komplení regexp na username

PHP

User RegExp #

$userRegExp = "#^[_A-Za-z0-9áäéëěíóöôúůüýčďňŕřšťžĺľÁÄÉËĚÍÓÖÔÚŮÜÝČĎŇŔŘŠŤŽĹĽ ]{3,40}\$#";

On gists

PHP Curl to check if url is alive

PHP

curl_example.php #

<?php

function check_alive($url, $timeout = 10, $successOn = array(200, 301)) {
  $ch = curl_init($url);

  // Set request options
  curl_setopt_array($ch, array(
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_NOBODY => true,
    CURLOPT_TIMEOUT => $timeout,
    CURLOPT_USERAGENT => "page-check/1.0"
  ));

  // Execute request
  curl_exec($ch);

  // Check if an error occurred
  if(curl_errno($ch)) {
    curl_close($ch);
    return false;
  }

  // Get HTTP response code
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  // Page is alive if 200 OK is received
  //return $code;
  return in_array( $code, $successOn );
}

$checks = array(
	'http://www.google.co.uk',
	'http://www.facebook.com',
	'http://www.bbc.co.uk',
	'http://photogabble.co.uk',
	'http://youtube.com'
	);

foreach($checks as $check)
{
	echo $check . ' is ' . ( (check_alive($check) ) ? 'Alive' : 'Dead' ) . "\n";
}

On gists

Download via Iframe // wo refresh

PHP

Downlad file via iframe (no refr #

<a href="" id="csv-export">export</a>
<iframe id="downloadIframe" src="" style="height: 0px; width: 0px; display: none;"></iframe>
<script>
    $("#csv-export").click(function(e){
        e.preventDefault();
        oIFrm = document.getElementById('downloadIframe');
        oIFrm.src = '' // URL to download file -- via php download headers;
    });
</script>

On gists

Convert UTF - win1250 - CSV

PHP

Convert utf-8 to win1250 - csv e #

 <?php
 
 $out = iconv('utf-8', 'windows-1250//TRANSLIT', $out);
 
         
 $filename = 'katalog-export___' . date('YmdHis') . '.csv';
 header('Content-Encoding: windows-1250');
 header('Content-type: text/csv; charset=windows-1250');
 header('Content-Disposition: attachment; filename=' . $filename);
 //echo "\xEF\xBB\xBF"; // UTF-8 BOM
 echo $out;
 exit(0);
 
 ?>