How to log error and std output while working with php CLI

KBelow is my exec() command through which I have executed the php script-

$command = ‘php ‘ . WEB_DIRECTORY . ‘/../app/console upload:documents ‘ . $parameters

exec($command);

error_log(‘Info Log :: Command – ‘.print_r($command,true));

Now here the problem is that it will not log any error or std output because it is out of php context. So to do so you to follow the below steps –

  1. Append the error (2) as well as your output (1) to your predefined log file in the below manner –

*$command .= ‘ 1>> ‘ . WEB_DIRECTORY . ‘/../app/logs/php.error.log 2>>&1’;

  1. Now whichever php script is being called, you need to use print_r() or var_dump() to log the data in the above log file  instead of using error_log()  like below –

echo print_r(‘Info Log :: Inside ‘. FUNCTION. ‘ in ‘ .basename(FILE),true) . PHP_EOL; // use like this to log fun and file name. PHP_EOL for end of file

echo print_r(“Response Log :: “.print_r($response,true),true).PHP_EOL;

// use like to log any request or response as per your requirement.

error_log(‘Info Log :: Inside ‘. FUNCTION. ‘ in ‘ .basename(FILE));

//This will not work b/c now exec() call is out of php context.

Note* –  0 is for std input

                  1 is for std output

                  2 is for error. 

So I try to explain the above *$command – whatever the output comes while executing the shell script, it will append (>>) the log to the php.error.log file and if any error comes, it will also log into the same file as error is redirected (pointer) to std output (2>>1).

Note( If you use > operator, it will override the log file always hence you won’t get your previous log. So be aware which you want to use.)

Sometimes you don’t want to log anything and you want to dump it to null device so use the following lines for linux and windows respectively –

if (strtoupper(substr(PHP_OS, 0, 3)) === ‘WIN’) {
$command .= 1>nul 2> nul ; // For windows
} else {
$command .= 1>/dev/null 2>/dev/null ; // For Linux
}

Null Device from wiki page – In some operating systems, the null device is a device file that discards all data written to it but reports that the write operation succeeded. This device is called /dev/null on Unix or Unix-like systems, NUL: or NUL on DOS and CP/M, \Device\Null on Windows NT, nul on newer Windows systems, NIL: on Amiga operating systems, and the NL: on OpenVMS. In Windows Powershell, the equivalent is $null. It provides no data to any process that reads from it, yielding EOF immediately.[1] In IBM DOS/360, OS/360 (MFT, MVT), OS/390 and z/OS operating systems, such files would be assigned in JCL to DD DUMMY.

Advertisements

Redirect Site to Maintenance Page when site is down

First of all, you have to create 2 files inside a site’s document root (mine is C:\xampp\htdocs\other.local-dev.creativesign.com\web) :
1. maintenance.html – A file with the HTML code of the maintenance page.
2. maintenance.enable – An empty file that will activate the maintenance mode.
[maintenance.enable]
Create an empty file, named maintenance.enable, inside the site’s document root.

We’ll use it to turn the maintenance mode ON and OFF, without Apache restart.

So, if we need to TURN ON site’s redirection during maintenance, we create an empty maintenance.enable file.

And when we need to TURN OFF redirection after maintenance, we delete maintenance.enable file.

Redirect to Maintenance Page Using .htaccess ->

Place the following code in your site’s root .htaccess file at the starting  to redirect all visitors to the maintenance page :
<IfModule mod_rewrite.c>

#Following line should be added before any existing lines.
RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^123.456.789.000
RewriteCond %{DOCUMENT_ROOT}/maintenance.html -f
RewriteCond %{DOCUMENT_ROOT}/maintenance.enable -f
RewriteCond %{SCRIPT_FILENAME} !maintenance.html
RewriteRule ^.*$ /maintenance.html [R=503,L]
ErrorDocument 503 /maintenance.html
Header Set Cache-Control “max-age=0, no-store”
</IfModule>

Hope it works for you. 🙂

PHP Error : file_put_contents() Failed to open stream, invalid argument

If you are getting the following issue and document is not uploaded in your account  so this may be due to invalid path, incorrect file name or some special character in the full path.
Exception ->” [Symfony\Component\Debug\Exception\ContextErrorException]
Warning: file_put_contents(/tmp/echobox/1/4/SIGNED/auditTrail/63051764/Sample testing Local 19 1 17 3:33 PM eSSNu 2
017-01-19 02:03:19_audit.pdf): failed to open stream: Invalid argument
upload:documents documents”

Here , I can see  time-stamp is included in the file name which is not allowed in this function of file_put_contents() in php. Colon (:) is creating the main problem here. Actually the main reason is that we can’t create a text file having the colon in it’s name on windows.

Solution – Either don’t give the colon in the name or make a check to avoid this problem in the php code.

CHANGE THE LOGIC OF BELOW FILE –

file_put_contents($path, $this->file);

BY ADDING THE BELOW CODE –
<?php
$path= ‘C:/temp/test:12_check.txt’;
if (is_writable($path)) {
echo ‘The file is writable’;
} else {
echo ‘The file is not writable’;
}
?>

It’ll say that file is not writable.

PHP based utility to do the re-encryption to migration application from PHP 5.5 to PHP 5.6

Context : The idea is to execute the php based utility which decrypts the column1 and column2 of table1 and table2 as well with crypt_key of size 12  and then encrypts the same column1 and column2 with crypt_key of size 24 in database. Now we can upgrade the app from PHP 5.5 to PHP 5.6. Followings are the steps which are needed to perform the desired task –

  1. Take the backup of application database. Please follow the below steps to take the backup –
    1. Go to Mysql installation bin directory (Mine is C:\Program Files\MySQL\MySQL Server 5.7\bin).
    2. Execute the below command and it’ll prompt for the database_password.
      1. C:\Program Files\MySQL\MySQL Server 5.7\bin> mysqldump -u database_user –password -h localhost database_name > C:\Users\tangupta\Desktop\AppDatabase_Backup.sql (Please change this path where you want to take backup)
        Enter password: ***********
      2. In case, you are not able to run the above command and getting the error like “mysqldump: Got error: 1045: Access denied for user ‘ODBC’@’localhost’ (using password: NO) when trying to connect”, Please check whether you had granted all the privilages on this database (local_app) in Mysql. if not , Please execute the below command on Mysql Command line client for the same –                       mysql> grant all privileges on db_name.* to ‘username’@’localhost’ identified by ‘password’;
  2. Execute the PHP script to decrypt and then encrypt the keys (column1 and column12 of table1 and table2 as well) in database. Please follow the below steps to execute the PHP script –
    1. Go to the path where script is saved (Mine is C:\xampp\htdocs)
    2. Execute the below command to do the same –
      1. C:\xampp\htdocs>php MigrationScript.php 127.0.0.1 local_user local_pass local_dbname 012345678901 012345678901234567890123 C:\Users\tangupta\Desktop\DbMigrationScriptLogs.txt
        1. MigrationScript.php (Name of the PHP Script)
        2. 127.0.0.1 (ServerName)
        3. local_user (database_user)
        4. local_pass (database_password)
        5. local_dbname (database_name)
        6. 012345678901 (Old 12 characters Encrypt Key as stored in PHP 5.5 chef recipe)
        7. 012345678901234567890123 (New 24 characters Encrypt Key as stored in PHP 5.6 chef recipe)
        8. C:\Users\tangupta\Desktop\DbMigrationScriptLogs.txt (path where you want to save the script logs)
          Note* – If you are not able to execute the script because of invalid character error, Please give the arguments in single quotes (Ex- ‘012345678901’). If there is some issue regarding database access with the user, please execute the query mentioned in step 1. (a. (ii.)).
      2. Now script will give ask user whether he/she wants to execute the script or not (Yes or No). If yes, script will continue to execute else it will halt the execution.
  3. Upgrade the App from PHP 5.5 to PHP 5.6.
  4. Update the crypt_key as per PHP5.6 statndard (Only keys of sizes 16, 24 or 32 supported) in the chef-recipe-bag.
  5. Deploy the application.
  6. In case there is any failure, Please rollback the database by using below steps-
    1. Go to Mysql Command line client.
    2. Execute the below command to restore from DB backup created at step 1 –
      1. mysql> source  C:\Users\tangupta\Desktop\AppDatabase_Backup.sql (Path where you took the db backup, please change this accordingly.)
    3. Downgrade the App from PHP 5.6 to PHP 5.5.
    4. Revert to the old 12 character encryt key in chef recipe and rebuild the app server.
  7. Finish.

How to enable debugging through Eclipse/STS

This is the post excerpt.

  1. First Add below lines in php.ini –

;[XDebug]

;zend_extension = “C:\xampp\php\ext\php_xdebug.dll”

;xdebug.remote_enable = 1

;xdebug.remote_autostart=1

;xdebug.remote_host=localhost

;xdebug.remote_port=9000

semicolon (;) is used to comment the line.

  1. Now go to STS –

Right Click on Box Project -> Debug As -> Debug Configurations -> PhP Web Aplication -> New

Name it as Box_Integration or whatever you want –

In the Server Tab -> Php Server Configure -> Configure

Server Tab ->

Server Name : other.local-dev.creativesign.com (change yrs)

Base URL : http://other.local-dev.creativesign.com:447 (change yrs)

Document Root : Browse the root directory of the php project (My path – C:\xampp\htdocs\other.local-dev.creativesign.com)

Debugger Tab ->

Debugger : XDebug

Port : 9000

Path Mapping Tab ->

Path On Server :  C:\xampp\htdocs\other.local-dev.creativesign.com

Path in Wrokspace : /echosign-box-integration

Now Finish and come to main Server Tab .

In File : Give path of php page which you want to debug . /echosign-box-integration/src/Adobe/EchoSign/BoxBundle/Api/EchoSign.php

URL :   http://other.local-dev.creativesign.com:447/  map to /

Now Enjoy debugging.

Note* – If you are stuck at the 2nd line of app.php or app_dev.php while debuging, Go to preferences of IDE (Eclipse in my case), search debug. Click on the Debug of PHP, you can see that “Break at First line” is checked by default. You need to uncheck it. Hope now the problem will be solved.