/ Gists

Gists

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);
 
 ?>

On gists

Kontrola BOOMu na začátku souboru

PHP

UTF-8 BOOM check #

echo "\xEF\xBB\xBF"; // UTF-8 BOM

On gists

Nette CSV response

Nette

NetteCsvResponse.php #

<?php

namespace Nette\Application\Responses;

use Nette;

/**
 * CSV download response.
 * Under New BSD license.
 *
 * @property-read string $name
 * @property-read string $contentType
 * @package Nette\Application\Responses
 */
class CsvResponse extends Nette\Object implements Nette\Application\IResponse
{
	/** @var array */
	private $data;

	/** @var string */
	private $name;

	/** @var bool */
	public $addHeading;

	/** @var string */
	public $glue;

	/** @var string */
	private $charset;

	/** @var string */
	private $contentType;


	/**
	 * @param array[]|\Traversable $data
	 * @param string $name
	 * @param bool $addHeading
	 * @param string $glue
	 * @param string $charset
	 * @param string $contentType
	 * @throws \InvalidArgumentException
	 */
	public function __construct($data, $name = NULL, $addHeading = TRUE, $glue = ';', $charset = 'utf-8', $contentType = NULL)
	{
		if (is_array($data)) {
			if (count($data) && !is_array(reset($data))) {
				$invalid = TRUE;
			}
		} elseif (!$data instanceof \Traversable) {
			$invalid = TRUE;
		}
		if (isset($invalid)) {
			throw new \InvalidArgumentException(__CLASS__.": data must be array of arrays or instance of Traversable.");
		}
		if (empty($glue) || preg_match('/^[\n\r]+$/s', $glue) || $glue === '"') {
			throw new \InvalidArgumentException(__CLASS__.": glue cannot be an empty or reserved character.");
		}

		$this->data = $data;
		$this->name = $name;
		$this->addHeading = $addHeading;
		$this->glue = $glue;
		$this->charset = $charset;
		$this->contentType = $contentType ? $contentType : 'text/csv';
	}


	/**
	 * Returns the file name.
	 * @return string
	 */
	final public function getName()
	{
		return $this->name;
	}


	/**
	 * Returns the MIME content type of a downloaded content.
	 * @return string
	 */
	final public function getContentType()
	{
		return $this->contentType;
	}


	/**
	 * Sends response to output.
	 * @param Nette\Http\IRequest $httpRequest
	 * @param Nette\Http\IResponse $httpResponse
	 */
	public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $httpResponse)
	{
		$httpResponse->setContentType($this->contentType, $this->charset);

		if (empty($this->name)) {
			$httpResponse->setHeader('Content-Disposition', 'attachment');
		} else {
			$httpResponse->setHeader('Content-Disposition', 'attachment; filename="' . $this->name . '"');
		}

		$data = $this->formatCsv();

		$httpResponse->setHeader('Content-Length', strlen($data));
		print $data;
	}


	protected function formatCsv()
	{
		if (empty($this->data)) {
			return '';
		}

		$csv = array();

		if (!is_array($this->data)) {
			$this->data = iterator_to_array($this->data);
		}
		$firstRow = reset($this->data);

		if ($this->addHeading) {
			if (!is_array($firstRow)) {
				$firstRow = iterator_to_array($firstRow);
			}

			$labels = array();
			foreach (array_keys($firstRow) as $key) {
				$labels[] = ucfirst(str_replace(array("_", '"'), array(' ', '""'), $key));
			}
			$csv[] = '"'.join('"'.$this->glue.'"', $labels).'"';
		}

		foreach ($this->data as $row) {
			if (!is_array($row)) {
				$row = iterator_to_array($row);
			}
			foreach ($row as &$value) {
				$value = str_replace(array('"'), array('""'), $value);
			}
			$csv[] = '"'.join('"'.$this->glue.'"', $row).'"';
		}

		return join("\r\n", $csv);
	}
}

On gists

Validation date & time

PHP

PHP: Date validation (datetime) #

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

var_dump(validateDate('2012-02-28 12:12:12')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
var_dump(validateDate('14:50', 'H:i')); # true
var_dump(validateDate('14:77', 'H:i')); # false
var_dump(validateDate(14, 'H')); # true
var_dump(validateDate('14', 'H')); # true

var_dump(validateDate('2012-02-28T12:12:12+02:00', 'Y-m-d\TH:i:sP')); # true
# or
var_dump(validateDate('2012-02-28T12:12:12+02:00', DateTime::ATOM)); # true

var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', 'D, d M Y H:i:s O')); # true
# or
var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', DateTime::RSS)); # true
var_dump(validateDate('Tue, 27 Feb 2012 12:12:12 +0200', DateTime::RSS)); # false
# ...

On gists

Input limiter

jQuery jQuery-plugins

JS: Input limiter #

	function($) {
	$.fn.extend( {
		limiter: function(limit, elem) {
			$(this).on("keyup focus", function() {
				setCount(this, elem);
			});
			function setCount(src, elem) {
				var chars = src.value.length;
				if (chars > limit) {
					src.value = src.value.substr(0, limit);
					chars = limit;
				}
				elem.html( limit - chars );
			}
			setCount($(this)[0], elem);
		}
	});
})(jQuery);

On gists

Clone table header to footer

jQuery

JS: Clone table header to footer #

var $tfoot = $('<tfoot></tfoot>');
$($('thead').clone(true, true).children().get().reverse()).each(function(){
    $tfoot.append($(this));
});
$tfoot.insertAfter('table thead');

On gists

Preload images

jQuery jQuery-plugins

JS: Preload Images #

$.preloadImages = function() {
       for(var i = 0; i<arguments.length; i++) {
               $("<img />").attr("src", arguments[i]);
       }
}

$(document).ready(function() {
       $.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
});

On gists

Sort a list alphabetically

JavaScript jQuery jQuery-plugins

JS: Sort a list alphabetically #

$(function() {
    $.fn.sortList = function() {
    var mylist = $(this);
    var listitems = $('li', mylist).get();
    listitems.sort(function(a, b) {
        var compA = $(a).text().toUpperCase();
        var compB = $(b).text().toUpperCase();
        return (compA < compB) ? -1 : 1;
    });
    $.each(listitems, function(i, itm) {
        mylist.append(itm);
    });
   }

    $("ul#demoOne").sortList();

});