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?

How to fix (errno: 150 “Foreign key constraint is incorrectly formed”) MySQL, MariaDB

If you catch errno: 150 “Foreign key constraint is incorrectly formed” when you try to create a new table in mySQL(or another relational DB) then you can use a simple way to find a bad foreign key(s). Just execute this query:

SELECT
  CONSTRAINT_NAME, 
  TABLE_NAME, 
  COLUMN_NAME, 
  REFERENCED_TABLE_NAME, 
  REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = '<your table name here>' OR TABLE_NAME = '<your table name here>';

After that you can see where this bad table using and you can go and delete bad foreign key(s).

Happy SQLing)

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

UPDATE with random number between range 1-n [MYSQL UPDATE RAND]

Sometimes you need to update your latest added field in DB table by random numbers.
For that reason you can use this simple SQL command:
[1 – min, 100-max]

UPDATE `...` 
SET `columnName` = FLOOR( 1 + RAND( ) *100 );
WHERE ...

In this way you can easy update `columnName` by random value in defined range.
Happy SQLing… Continue reading UPDATE with random number between range 1-n [MYSQL UPDATE RAND]

How to add one/two/n days or hours to date in MySQL (DATE_ADD in MYSQL)

Suppose you have a table in the database where the stored data and you need to check or get that dates but with the changes – calculate directly by MySQL.
Example, you want to get users end dates (7-day licence after registration):

SELECT `register_date`, `uid`, 
DATE_ADD(`register_date`, INTERVAL 7 DAY) AS `end_date` 
FROM `...`
WHERE...

Perfect, now you can show for user that his licence if over `end_date`…
In addition, you can subtract the required number of days
Continue reading How to add one/two/n days or hours to date in MySQL (DATE_ADD in MYSQL)

How to run Python Scripts ( *.py files) on Apache2 (configuring unix apache2 servers)

Preparing (install apache2, python):
Installation Apache2:

sudo apt-get install apache2

Installation Python(choose one):

sudo apt-get install python
sudo apt-get install python2.7
sudo apt-get install python3

First step: enabling CGI processing in your apache (automatically enable mod_cgid).

sudo a2enmod cgi

Second step: Allow run CGI scripts in your directory.
You can try allow by .htaccess in your “python” web folder

Options +ExecCGI
AddHandler cgi-script .py

or you can allow .py files to be executed as scripts in a particular folder you would use config in apache conf file:

    <Directory /srv/www/mysite/public_html/python_folder>
        Options +ExecCGI
        AddHandler cgi-script .py
    </Directory>

Finish step:
Continue reading How to run Python Scripts ( *.py files) on Apache2 (configuring unix apache2 servers)

Yii 2 Response formats: RAW, HTML, JSON, JSONP, XML

If you want that your method return data in specific format in Yii2 then you can use this simple construction:
Example method return in JSON format:

use yii\web\Response;
//......
public function actionJson()
    {
        $something = true; // or you can set for test -> false;
        $return_json = ['status' => 'error'];
        if ($something == true)
        {
            $return_json = ['status' => 'success', 'message' => ' is successfully saved'];
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $return_json;
    }

/*header results
Connection: Keep-Alive
Content-Length: 55
Content-Type : application/json; charset=UTF-8
*/

Continue reading Yii 2 Response formats: RAW, HTML, JSON, JSONP, XML

How to sort array with objects by object property in Yii 2?

If you want to sort your array with objects by specific property in Yii 2 then you can use beautiful method ArrayHelper::multisort (&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
Example (you have unsorted array ‘history’ with objects):

Array
(
    [0] => stdClass Object
        (
            [sent_date] => 2016-01-28 13:42:10
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

    [1] => stdClass Object
        (
            [sent_date] => 2016-01-29 10:08:35
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

    [2] => stdClass Object
        (
            [sent_date] => 2016-01-31 10:08:35
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

    [3] => stdClass Object
        (
            [sent_date] => 2015-12-01 10:08:35
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

)

Continue reading How to sort array with objects by object property in Yii 2?