Category Archives: PHP

PHP INI directives configuration methods

This morning i had come across an issue while setting value for upload_max_filesize and post_max_size.
Tried .htaccess method as below,

php_value upload_max_filesize              256M
php_value post_max_size                    280M

Also used below method too from php script

ini_set('memory_limit', '880M'); // worked
ini_set('post_max_size', '280M'); // didn't work
ini_set('upload_max_filesize', '256M'); // didn't work

Unfortunately both method didn’t work. I could set values in php.ini and made it work. But, I dont wanted to touch php.ini.
What worked is setting the directives and values in .user.ini file as below.

post_max_size = 280M
upload_max_filesize = 256M

Below 2 links explains the reason:
http://php.net/manual/en/configuration.changes.modes.php
http://www.php.net/manual/en/ini.list.php

PHP – Array dereferencing

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly.
Before it was only possible using a temporary variable.

As of PHP 5.5 it is possible to array dereference an array literal.

<?php
function getArray() {
    return array(1, 2, 3, 4);
}

// on PHP 5.4
$secondElement = getArray()[1];

// earlier
$temp = getArray();
$secondElement = $temp[1];
?>

PHP 5.5 new features

Generators added
Support for generators has been added via the yield keyword. Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A simple example that reimplements the range() function as a generator

<?php
function xrange($start, $limit, $step = 1) {
    for ($i = $start; $i <= $limit; $i += $step) {
        yield $i;
    }
}

echo 'Single digit odd numbers: ';

/*
 * Note that an array is never created or returned,
 * which saves memory.
 */
foreach (xrange(1, 9, 2) as $number) {
    echo "$number ";
}

echo "\n";
?>

It outputs : Single digit odd numbers: 1 3 5 7 9

finally keyword added

try-catch blocks now support a finally block for code that should be run regardless of whether an exception has been thrown or not.

New password hashing API

A new password hashing API that makes it easier to securely hash and manage passwords using the same underlying library as crypt() in PHP has been added. See the documentation for password_hash() for more detail.

foreach now supports list()

The foreach control structure now supports unpacking nested arrays into separate variables via the list() construct. For example:

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b)) {
    echo "A: $a; B: $b\n";
}
?>

Above example outputs:
A: 1; B: 2
A: 3; B: 4

empty() supports arbitrary expressions

Passing an arbitrary expression instead of a variable to empty() is now supported. For example:

<?php
function always_false() {
    return false;
}

if (empty(always_false())) {
    echo "This will be printed.\n";
}

if (empty(true)) {
    echo "This will not be printed.\n";
}
?>

It outputs: This will be printed.

array and string literal dereferencing

Array and string literals can now be dereferenced directly to access individual elements and characters:

<?php 
echo 'Array dereferencing: '; 
echo [1, 2, 3][0]; 
echo "\n"; 

echo 'String dereferencing: '; 
echo 'PHP'[0]; 
echo "\n"; 
?>

The above example will output:
Array dereferencing: 1
String dereferencing: P

Class name resolution via ::class

It is possible to use ClassName::class to get a fully qualified name of class ClassName. For example:

<?php 
namespace Name\Space; 
class ClassName {} 

echo ClassName::class; 

echo "\n"; 
?>

The above example will output:
Name\Space\ClassName

OPcache extension added

The Zend Optimiser+ opcode cache has been added to PHP as the new OPcache extension. OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request. See the installation instructions for more detail on enabling and using OPcache.

foreach now supports non-scalar keys

foreach now supports keys of any type. While non-scalar keys cannot occur in native PHP arrays, it is possible for Iterator::key() to return a value of any type, and this will now be handled correctly.

Apache 2.4 handler supported on Windows

The Apache 2.4 handler SAPI is now supported on Windows.

Improvements to GD

Various improvements have been made to the GD extension, these include:

– Flipping support using the new imageflip() function.
– Advanced cropping support using the imagecrop() & imagecropauto() functions.
– WebP read and write support using imagecreatefromwebp() & imagewebp() respectively.

Connect to multiple database in Yii framework

Yii configuration file protected/main/config.php by default comes up with one db connection. To have multiple db connections like, same db withing mysql or sqlite or something else, then do follow the below code

<?php
// protected/main/config.php
return array(
    ...
    'components' => array(
        // connection one
        'db' => array(
            'connectionString' => 'mysql:host=dbserver1;dbname=my1db',
            ...
        ),
        // connection two
        'dblogs' => array(
            'connectionString' => 'mysql:host=logshost;dbname=logs',
            'username'         => 'loguser',
            'password'         => '*******',
            ...
            'class'            => 'CDbConnection'          // Important! DO NOT FORGET THIS!
        ),
        ...
?>

If you notice the dblogs has class as CDbConnection, which is used for connection purpose. Internally, Yii assigns CDbConnection class to db by default.

How to use: You can use the second database using Yii::app()->dblogs and first by Yii::app()->db.

We can also connect to db as shown below

<?php
$connection=new CDbConnection($dsn,$username,$password);
// establish connection. Check for try and catch for errors
$connection->active=true;
.......... do your stuff here
$connection->active=false;  // close connection
?>

Format date – Convert from one format to another in PHP

Here is the function i used for some of my projects where date format to be needed in different formats. What it does is, it takes the format you need from the format you have. It does check for which format the date is. ie, is it in mm/dd/YYYY or mm-dd-YYYY or YYYY-mm-dd format. You may add more formats if you would like to compare with other formats.

function dateFormat($format='m/d/Y', $inputFormat=NULL, $showTodayDate=true) {
	if(!is_null($inputFormat)){
		//$arrInputFormat = split
		if($inputFormat[2]=='/'){//mm/dd/YYYY format
			list($m,$d,$Y) = explode("/", $inputFormat);
		}

		if($inputFormat[2]=='-'){//mm-dd-YYYY format
			list($m,$d,$Y) = explode("-", $inputFormat);
		}

		if($inputFormat[4]=='-'){//YYYY-mm-ddd format
			list($Y,$m,$d) = explode("-", $inputFormat);
		}
		if(empty($inputFormat)){
			return '';
		}

		$time = strtotime("$Y-$m-$d");
	} else {
		//$inputFormat is empty
		if(!$showTodayDate){
			return '';
		} else {
			$time = time();
		}
	}
	return date($format, $time);
}

If the inputFormat is empty and showTodayDate is true then you get the today date in formatted date, else empty string. Empty string is because, if sometime we display date from DB table which is  null or empty.

Simple email function to send html content

Use the the below send_mail() function to send the text or html mail to specific recipients

<?php
function send_mail($to, $from, $subject, $body, $cc='', $bcc=''){
    // To send HTML mail, you can set the Content-type header.
    $headers = "From: $from\r\n";
    $headers .= "Content-type: text/html\r\n";
    //add additional headers like, reply-to, etc if you need
    if(!empty($cc)){
        $headers .= "Cc: $cc\r\n";
    }
    if(!empty($bcc)){
    $headers .= "Bcc: $bcc\r\n";
    }
    // and now native mail function
    mail($to,$subject, $body, $headers);
   //you can use the return type for success message or error message
}
?>

You can use the above function by calling the function with parameters as below

<?php
    send_mail('recipient@domain.com', 'frommail@fromdomainname.com', 'Hello subject', 'Content');
?>