Author Archives: admin

Basic Linux commands for beginners

As a beginner to Linux OS, one should have some basic knowledge about below linux commands to interact with files, directories and permissions

ls – list files and directories in current directory
#list all files including hidden
ls -a
#list files with all the details
ls -l
#list files sorted by time with all details
ls -lt

pwd – display current working directory

mkdir – Create a directory
mkdir <directory name>

rmdir – Remove specific directory
rmdir <directory name>

cd – change to directory
# change or get inside specific directory
cd <directrory name>
# move one level up from current directory
cd ...

rm – removes files and directory.
#remove one file
rm <filename>
# remove a folder and files in it. use -f command as well
rm -r <directory name>

cp – copy files from one directory to another directory or same with different name
cp file1.txt filecopy.txt
cp /dir1/file1.txt /dir2/

mv – move a file from place to another or rename a file
mv file1.txt filecopy.txt # renaming withing same directory
mv /dir1/file1.txt /dir2/file2.txt # moving from dir1 to dir2 and renaming

chmod – change permission of files and directory
# changing file1.txt permission read write for owner and only read for others
chmod 644 file1.txt

chown – Change ownership of file or directory
# change ownership of file
chown <username>:<groupname> file2.txt

sudo – “Super user do” run any command as super user (root). You should have sudo access
# run a service using sudo
sudo service httpd start

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

Difference Between DATE, DATETIME and TIMESTAMP data types

The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in ‘YYYY-MM-DD’ format. The supported range is ‘1000-01-01’ to ‘9999-12-31’.

The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ‘YYYY-MM-DD HH:MM:SS’ format. The supported range is ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’.

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of ‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC.

A major difference between these three data types is that TIMESTAMP data type values are converted from current time zone to UTC for storage purpose and converted back from UTC to current time zone when used. The datetime and date data type values are unchanged in relation to time zone.

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.

GIT Commands

git init
Create an empty git repository or reinitialize an existing one

git config

git clone
Example: git clone git@github.com:user/test.git

git add
Example: git add .

git rm
Removes files from your index and your working directory so they will not be tracked.
Example: git rm filename.txt

git commit
Examples: git commit -m ‘adding changes’
git commit -a -m ‘commit all changes. Its same as git add and git commit’

git status

git branch
Example: git branch -a

git checkout
Checkout a branch or paths to the working tree
Example: git checkout filename.txt

git merge

git reset
Resets your index and working directory to last commit.
Example: git reset –hard HEAD

git stash
Temporarily saves changes so that you don’t want to commit immediately. You can apply the   changes later.
Example: git stash
To restore stash back type “git stash apply”

git tag
Tags a specific commit with a simple, human readable handle that never moves.
Example: git tag -a v1.0 -m ‘version 1.0 tag’

git fetch
Fetch objects and refs from another repository
Example: git fetch origin

git pull
Fetch objects from remote repository and merg it with local repository.
This is same as git fetch and the git merge commands one by one.
Example: git pull origin

git push
Push all the changes to remote repository.
Example: git push origin master

git remote
Shows all the remote versions of your repository.
Example: git remote

git log
Shows a list of latst commits.
Example: git log

git show

git grep
Lets you search through your trees of content.
Example: git grep “sendmail” — *.php

git diff
Show changes between commits, commit and working tree, etc.

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.

GIT – Ignore file permission changes

I had seen, git use to consider the file permission change as a modification to the files/folders. And we use to either commit the changes or stash before taking pull. This was really not needed.

To fix this issue, please use the below command which ignores the file permission changes.

git config core.filemode false

Rename files and folders with GIT

Here are the steps for renaming a old folder folder_old with new folder folder_new
Step 1: User git mv to move the folder

git mv folder_old folder_new

Step 2: Add the changes to index

git add -u folder_new

Step 3: Finally commit the changes to git server

git commit -m "renamed folder_old to folder_new"

Note: For step 1 if folder_new already exists in repository then -f (force) option will overwrite new folder

git mv -f folder_old folder_new