/ Gists / PHP

Gists - PHP

On gists

List of HTTP headers

PHP

List of HTTP headers.php #

 private function get_status_message(){
            $status = array(
                        100 => 'Continue',  
                        101 => 'Switching Protocols',  
                        200 => 'OK',
                        201 => 'Created',  
                        202 => 'Accepted',  
                        203 => 'Non-Authoritative Information',  
                        204 => 'No Content',  
                        205 => 'Reset Content',  
                        206 => 'Partial Content',  
                        300 => 'Multiple Choices',  
                        301 => 'Moved Permanently',  
                        302 => 'Found',  
                        303 => 'See Other',  
                        304 => 'Not Modified',  
                        305 => 'Use Proxy',  
                        306 => '(Unused)',  
                        307 => 'Temporary Redirect',  
                        400 => 'Bad Request',  
                        401 => 'Unauthorized',  
                        402 => 'Payment Required',  
                        403 => 'Forbidden',  
                        404 => 'Not Found',  
                        405 => 'Method Not Allowed',  
                        406 => 'Not Acceptable',  
                        407 => 'Proxy Authentication Required',  
                        408 => 'Request Timeout',  
                        409 => 'Conflict',  
                        410 => 'Gone',  
                        411 => 'Length Required',  
                        412 => 'Precondition Failed',  
                        413 => 'Request Entity Too Large',  
                        414 => 'Request-URI Too Long',  
                        415 => 'Unsupported Media Type',  
                        416 => 'Requested Range Not Satisfiable',  
                        417 => 'Expectation Failed',  
                        500 => 'Internal Server Error',  
                        501 => 'Not Implemented',  
                        502 => 'Bad Gateway',  
                        503 => 'Service Unavailable',  
                        504 => 'Gateway Timeout',  
                        505 => 'HTTP Version Not Supported');
            return ($status[$this->_code])?$status[$this->_code]:$status[500];
        }
                        
                      
                          private function set_headers(){
            header("HTTP/1.1 ".$this->_code." ".$this->get_status_message());
            header("Content-Type:".$this->_content_type);
        }

On gists

curl POST examples

PHP

server.js #

var app = require('express')();
var bodyParser = require('body-parser');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.post('/data', function (req, res) {
  console.log(req.body);
  res.end();
});

app.listen(3000);

On gists

DateTime

PHP

DateTimeTest.php #

<?php

require_once __DIR__ . '/DateTime.php';

class DateTimeTest extends \PHPUnit_Framework_TestCase
{
    public function providerSetDate()
    {
        $now = new \MyNamespace\DateTime();
        return array(
            array('2014-02-28', 31, 2),
            array('2014-02-01', 1, 2),
            array('2014-06-30', 31, 6),
            array($now->format('Y-m-d'), null, null, null),
        );
    }

    /**
     * @test
     * @dataProvider providerSetDate
     */
    public function setDate($result, $day, $month, $year = '2014')
    {
        $dateTime = new \MyNamespace\DateTime();
        $dateTime->setDate($year, $month, $day);
        $this->assertEquals($result, $dateTime->format('Y-m-d'));
    }

    public function providerModify()
    {
        return array(
            array('2014-02-28', '0 day 0 month 0 year'),
            array('2014-01-28', 'next month'),
            array('2014-01-28', 'next months'),
            array('2014-01-02', '+1 month', '2014-02-02'),
            array('2014-01-31', '1 months'),
            array('2014-03-31', '-1 month'),
            array('2012-02-29', '24 month'),
            array('2016-02-29', '-24 months'),
            array('2014-02-27', 'next day'),
            array('2014-02-27', '1 day'),
            array('2014-02-27', '+1 day'),
            array('2013-02-01', '-1 day next month next year'),
            array('2013-01-27', '1 day 1 month 1 year'),
            array('2015-04-01', '-1 day -1 month -1 year'),
            array('2011-12-26', '2 day 2 month 2 year'),
            array('2011-12-31', '2 month 2 year'),
        );
    }

    /**
     * @test
     * @dataProvider providerModify
     */
    public function modify($date, $shift, $result = '2014-02-28')
    {
        $dateTime = new \MyNamespace\DateTime($date);
        $dateTime->modify($shift);
        $this->assertEquals($result, $dateTime->format('Y-m-d'));
    }

    /**
     * @test
     * @expectedException PHPUnit_Framework_Error_Warning
     */
    public function modifyError()
    {
        $dateTime = new \MyNamespace\DateTime();
        $dateTime->modify('2 month sdfg year');
    }
}

On gists

Ul to select (for responsive navigation)

JavaScript jQuery PHP Responsive

example.js #

$(function(){

    var select = $("select");
    $("nav a").each(function(){
        
        var $this = $(this);
        var text = $this.text();  
        var level = $this.parents("ul").length;
        var indent = '';
        if (level > 1)
        {
            indent = str_repeat("\u2013", level);
        }
        select.append('<option>'+indent + text+'</option>');
    
    
    });   



});


function str_repeat(string, times) {
  var repeatedString = "";
  while (times > 0) {
    repeatedString += string;
    times--;
  }
  return repeatedString;
}

On gists

PHP in the command line

PHP

commands.cmd #

# To parse and execute a php script:
php file
 
# To check syntax on (i.e. lint) a PHP script:
php -l file
 
# To run PHP interactively:
php -a
 
# To run PHP code (Notes: Don't use <? ?> tags; escape double quotes with backslash):
php -r "code"
 
# To start a PHP built-in web server in the current directory:
php -S host:port

On gists

PHP Method Chaining

PHP

PHP Method Chaining.php #

<?php
 
class QueryMaker
{
    $table = '';
$field = '';
 
    // this is a static method, it doesn't
    // run on an object, it only runs on a class
    public static function make()
    {
        // create an instance of class
        // QueryMaker and return it
        return new static();
    }
 
    // this is not static, it doesn't run on
    // a class, only on an object
    public function setTable($name)
    {
        $this->table = $name;
        return $this;
    }
 
    // this is also not static
    public function setField($name)
    {
        $this->field = $name;
        return $this;
    }
 
    // again, not static, just renders
    // the "query"
    public function flush()
    {
        return "select {$this->field} from {$this->table}";
    }
}
 
// Here is the implementation with method chaining
$query = QueryMaker::make()->setTable('users')->setField('name')->flush();
 
// Here is the implementation without method chaining
$object = new QueryMaker();
$object->setTable('users');
$object->setField('name');
$query = $object->flush();
// the output is: select name from users
 
// The methods setTable() and setField() return $this.
// In that context $this is the QueryMaker object that was created by make().
 
// Let's go step by step:
 
$query = QueryMaker::make()->setTable('users')->setField('name')->flush();
// The static method QueryMaker::make() returns an object instantiation of the QueryMaker class.
 
$query = $object->setTable('users')->setField('name')->flush();
// $object->table is set, setTable() returns the object instance.
 
$query = $object->setField('name')->flush();
// $object->field is set, setField() returns the object instance.
 
$query = $object->flush();
// The flush method is called on the object, returning the string.

On gists

Get Array Values Recursively

PHP

demo.php #

<?php
 
/**
 * Get Array Values PHP Recursively
 *
 * https://davidwalsh.name/get-array-values-with-php-recursively
 *
 * @param array $array The source array.
 * @return array The flattened array values.
 */
function array_values_recursive($array)
{
    $flat = array();
 
    foreach ($array as $value) {
        if (is_array($value)) {
            $flat = array_merge($flat, array_values_recursive($value));
        } else {
            $flat[] = $value;
        }
    }
 
    return $flat;
}

On gists

Sanitize all PHP Super Globals

PHP Protecting

demo.php #

<?php
 
//
// Sanitize all dangerous PHP super globals.
//
// The FILTER_SANITIZE_STRING filter removes tags and remove or encode special
// characters from a string.
//
// Possible options and flags:
//
//   FILTER_FLAG_NO_ENCODE_QUOTES - Do not encode quotes
//   FILTER_FLAG_STRIP_LOW        - Remove characters with ASCII value < 32
//   FILTER_FLAG_STRIP_HIGH       - Remove characters with ASCII value > 127
//   FILTER_FLAG_ENCODE_LOW       - Encode characters with ASCII value < 32
//   FILTER_FLAG_ENCODE_HIGH      - Encode characters with ASCII value > 127
//   FILTER_FLAG_ENCODE_AMP       - Encode the "&" character to &amp;
//
//
// <?php
//
// // Variable to check
// $str = "<h1>Hello WorldÆØÅ!</h1>";
//
// // Remove HTML tags and all characters with ASCII value > 127
// $newstr = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
// echo $newstr;
//  -> Hello World!
//
// ?>
//
 
foreach ($_GET as $key => $value)
{
    $_GET[$key] = filter_input(INPUT_GET, $key, FILTER_SANITIZE_STRING);
}
 
foreach ($_POST as $key => $value)
{
    $_POST[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_STRING);
}
 
foreach ($_COOKIE as $key => $value)
{
    $_COOKIE[$key] = filter_input(INPUT_COOKIE, $key, FILTER_SANITIZE_STRING);
}
 
foreach ($_SERVER as $key => $value)
{
    $_SERVER[$key] = filter_input(INPUT_SERVER, $key, FILTER_SANITIZE_STRING);
}
 
foreach ($_ENV as $key => $value)
{
    $_ENV[$key] = filter_input(INPUT_ENV, $key, FILTER_SANITIZE_STRING);
}
 
$_REQUEST = array_merge($_GET, $_POST);

On gists

ArrayToObject / ObjectToArray

PHP Helpers-Filters-Plugins

object-to-array-vice-versa.php #

<?php

function objectToArray($d) {
		if (is_object($d)) {
			// Gets the properties of the given object
			// with get_object_vars function
			$d = get_object_vars($d);
		}
 
		if (is_array($d)) {
			/*
			* Return array converted to object
			* Using __FUNCTION__ (Magic constant)
			* for recursive call
			*/
			return array_map(__FUNCTION__, $d);
		}
		else {
			// Return array
			return $d;
		}
	}
 
 
 
 	function arrayToObject($d) {
		if (is_array($d)) {
			/*
			* Return array converted to object
			* Using __FUNCTION__ (Magic constant)
			* for recursive call
			*/
			return (object) array_map(__FUNCTION__, $d);
		}
		else {
			// Return object
			return $d;
		}
	}
 

On gists

CURL - functions

PHP Helpers-Filters-Plugins

CURL.php #

function curl_file_get_contents($url) 
{	
	 $c = curl_init(); // iniciuje práci s curl
	 curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
	 curl_setopt($c, CURLOPT_URL, $url);
	 $contents = curl_exec($c);
	 curl_close($c); 
 
	 return $contents;
 }


function better_curl($url)
{
	
  $curl = curl_init();
 
  $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  $header[] = "Cache-Control: max-age=0";
  $header[] = "Connection: keep-alive";
  $header[] = "Keep-Alive: 300";
  $header[] = "Accept-Charset: ISO-8859-1,utf-8,utf-16;q=0.7,*;q=0.7";
  $header[] = "Accept-Language: en-us,en;q=0.5";
  $header[] = "Pragma: "; // browsers keep this blank.
 
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.1) Gecko/20061223 Firefox/2.0.0.1');
//  curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
//  curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);
 
  $html = curl_exec($curl); // execute the curl command
  curl_close($curl); // close the connection
 
  return $html; // and finally, return $html
}