Relation “migration” already exists error while executing yii migrate

If you use PostgreSQL Database and got error
“Relation “migration” already exists error while executing yii migrate”
Just check your config, it seems that you have a mistake in schema section.
Example:

'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'pgsql:host=localhost;dbname=yourdb',
            'username' => 'yourdb_user',
            'password' => 'password',
            'charset' => 'utf8',
            'schemaMap' => [
                'pgsql' => [
                    'class' => 'yii\db\pgsql\Schema',
                    'defaultSchema' => 'public'
                ]
            ], // PostgreSQL
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],

Work with ZIP-archives in PHP 5.2+

Starting with PHP 5.2 you can use useful library ZipArchive for easy working with ZIP archives.
(If your PHP version les 5.2 you’ll get error: class ziparchive not found)

Steps for easy working with ZipArchive
Init:

$zip = new ZipArchive;

Read ZIP archive:

$zip->open('{file_location_path}');

Create new ZIP archive (just add ZipArchive::CREATE):

$zip->open('{file_location_path}', ZipArchive::CREATE);

Example of extracting archive on your server:

$zip = new ZipArchive;
if ($zip->open('{file_location_path}') === true){
	$zip->extractTo('{file_location_extraction_path}');
	$zip->close();
}else{
	echo 'Archive file is not found';
}

Example of creating archive on your server:
Continue reading Work with ZIP-archives in PHP 5.2+

Install Xdebug on Windows (PHP)

Simple steps for install XDebug on your Windows machine.
0. Write on test.php this code:

phpinfo();

1. Copy all informmation from phpinfo page.
2. Open https://xdebug.org/wizard.php and insert phpinfo to textarea
3. Click “Analyse my phpinfo() output” and follow to provided instructions
Something like:

  • Download php_xdebug-2.5.1-7.1-vc14.dll
  • Move the downloaded file to E:\xampp\php\ext
  • Update E:\xampp\php\php.ini and change the line zend_extension = E:\xampp\php\ext\php_xdebug-2.5.1-7.1-vc14.dll
  • Restart the webserver
$obj1 = new stdClass();
$obj1->name = 'A';
$obj1->date = date('Y-m-d H:i:s', 1458754362);
var_dump($result);

Happy debugging.

Yii requirements.php error after moving to /web folder.

If you get:

Error

The path to yii framework seems to be incorrect.

You need to install Yii framework via composer or adjust the framework path in file requirements.php.

Please refer to the README on how to install Yii.

Warning: require_once({your_site}/web/vendor/yiisoft/yii2/requirements/YiiRequirementChecker.php): failed to open stream: No such file or directory in {your_site}\web\requirements.php on line 23

Fatal error: require_once(): Failed opening required '{your_site}/web/vendor/yiisoft/yii2/requirements/YiiRequirementChecker.php' (include_path='...php\PEAR') in {your_site}\web\requirements.php on line 23

Then just change 14 line on:

$frameworkPath = dirname(__FILE__) . '/../vendor/yiisoft/yii2';

Happy codding.

Fast installing Yii framework

Steps:
0. If you do not already have Composer installed, you may do so by following the instructions at getcomposer.org.
1. Install Yii)

composer global require "fxp/composer-asset-plugin:^1.2.0"

and final

composer create-project --prefer-dist yiisoft/yii2-app-basic my_project_name

That’s all. Happy Codding.
Continue reading Fast installing Yii framework

If you catch: php5-imap requires ext-imap * -> the requested PHP extension imap is missing from your system.

If you see: “The requested PHP extension imap is missing from your system.”
It seems that you need to install imap extension on your system.
The following simple steps below:

apt-get install php5-imap

However, it’s not enabled IMAP by default so enable it with:

php5enmod imap

Then bounce apache:

service apache2 restart

If you got “IMAP extension must be enabled.” in PHP.
Continue reading If you catch: php5-imap requires ext-imap * -> the requested PHP extension imap is missing from your system.

Native PHP Sort array of objects by property

Usually, it is very often necessary to sort the data in an array. But when in the array we have objects it happened little bit difficult.
Fast solution for sorting array objects by property name.
Bacis solution (PHP 5.3+) :

function sortArrayWithObjects($array, $property)
{
    usort($array, function ($a, $b) use ($property) {
        return (($a->$property == $b->$property) ? 0 : (($a->$property < $b->$property) ? -1 : 1));
        //[short version] return strcmp($a->$property, $b->$property);
    });
    return $array;
}

$obj1 = new stdClass();
$obj2 = clone $obj1;
$obj3 = clone $obj2;
$obj1->name = 'B';
$obj2->name = 'C';
$obj3->name = 'A';
$data = [$obj1, $obj2, $obj3];
$result = sortArrayWithObjects($data, 'name');
echo '<pre>';
var_dump($result);
echo '</pre>';

Result:
Continue reading Native PHP Sort array of objects by property

PHPExcel not working with PHP 7.+ – ZipArchive not found

PHPExcel ZipArchive not found

If you catch this error (and you use PHP 7 version) you need:
1. update PHPExcel to 1.8.+
or
2. try to use this preparing method:

PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);

P.s. https://github.com/PHPOffice/PHPExcel/issues/716

How to get timestamp of start to end (current) day period on PHP?

$dtNow = new \DateTime();
$beginOfDay = clone $dtNow;
$beginOfDay->modify('today');

$endOfDay = clone $beginOfDay;
$endOfDay->modify('tomorrow');
$endOfDay->modify('1 second ago');

$start_timestamp = $beginOfDay->getTimestamp();
$end_timestamp = $endOfDay->getTimestamp();

echo 'Start: '.$start_timestamp." [".date("Y-m-d H:i:s",$start_timestamp)."]"."\n";
echo 'End: '.$end_timestamp." [".date("Y-m-d H:i:s",$end_timestamp)."]"."\n";

Also, you can get first and last timestamps of a current month:
Continue reading How to get timestamp of start to end (current) day period on PHP?

Web-server on Ubuntu (PHP + MySQL + Apache) in 2 commands

Fast and easy install (PHP + MySQL + Apache) LAMP on Ubuntu

Step 1: install tasksel

sudo apt-get install tasksel

Step 2: Run install PHP, MySQL & Apache as LAMP server

sudo tasksel install lamp-server

Completed! Now you have installed PHP, MySQL, and Apache on your Ubuntu

Additional: Create site area
Continue reading Web-server on Ubuntu (PHP + MySQL + Apache) in 2 commands

If you got 500 (Internal Server Error) PHP/Nginx/Apache – Where you can found logs/reason?

Oh, noooo. You got most popular developer error 🙂
Firstly, No despair – say “Yes, I CAN”, and concentrate on possible errors.

1 step: Double check your PHP/Python/ETC code.
find_errors_ercule
Show all errors (how to show all errors/warnings/nootices in php)
Also, you can do “fast debug” in main parts of you code (Sure, use die() command but very carefully)

 

2 step: Check server/Apache&PHP settings
domino_server_settings_phpFirstly check .htaccess file on strange symbols or sentences.
Also, if you using POST method with uploading files then check php settings in php.ini (max_post_size, max_executing_time…)

 

3 step: Check error logs (Ubuntu/Linux)
find_errors_in_logs
Standard Apache logs dev finiding here:

/var/log/apache2/...

nginx logs here:

/var/log/nginx/...

Also, some popular frameworks logs folders:
Continue reading If you got 500 (Internal Server Error) PHP/Nginx/Apache – Where you can found logs/reason?

How to get Swift Mailer Delivery/Failures/Errors Status when you sending emails

Example of send email method with using Swift_Mailer (Swift_SmtpTransport, Swift_Message)
If you want get Delivery/Failures/Errors Status you can use this construction:

 /**
     * Method for sending emails via Swift_Mailer
     * @param $email - object
     * example $email = \new StdClass();
     * $email->login = 'sender@mail.example';
     * $email->password = 'password_of_sender_email';
     * $email->host = 'imap.gmail.com'; //real example for Gmail
     * $email->first_name = 'Test Example Name';
     * $email->to = 'reciepient@mail.example'; //or array ['reciepient1@mail.example','reciepient2@mail.example','reciepient3@mail.example']
     * $email->subject = 'Example of subject';
     * $email->body = 'Example of <br/> email body message';
     * @return boolean
     */
    public static function sendEmail($email)
    {
        $isSent = $failures = false;
        try {
            $transport = \Swift_SmtpTransport::newInstance()->setHost($email->host)->setPort(465)->setUsername($email->login)->setPassword($email->password)->setEncryption('ssl');

            $mailMessage = \Swift_Message::newInstance()->setFrom([$email->login => $email->first_name])->setReturnPath($email->to)->setTo($email->to)->setSubject($email->subject)->setBody($email->body, 'text/html');

            $mailer = \Swift_Mailer::newInstance($transport);

            if ($mailer->send($mailMessage, $failures)) {
                $isSent = true;
                echo ' SUCCESS SENDING!:' . $email->login . ' to ' . $email->to;
            } else {
                echo ' SENDING ERROR TO :' . print_R($failures);
            }
        } catch (\Exception $e) {
            echo 'Catch Error with ' . $email->login . ' : ' . $e->getErrorMessage() . "\n";
        }
        return $isSent;
    }

swift_SmtpTransport / Swift_Message /Swift_Mailer