Debug by writing the variables down the file

Submitted by phannphong on 12 March, 2019
Debug by writing down the file

Sometimes in the development process, you need to debug to define the values or to find the errors. Debugging is very important for any developers.

In Drupal 8, you can use the devel contributed module with kint() function. Beside you also use the simple PHP function likes the  print_r() function or var_dump(). But in some situations, like working with the AJAX form, you have a problem to see an output of  kint()print_r() or var_dump() functions. At this time, I use file_put_contents function to writing the variables that you want to debug into the file.


$data = ['red', 'black', 'blue'];
$file = '/example/path/drupaltut.txt';
file_put_contents($file, print_r($data, TRUE));

I used print_r with the last parameter is TRUE.

Opening the drupaltut.txt file, you will see a below output:

    [0] => red
    [1] => black
    [2] => blue

Note: you have to set the file and the folder with write permission.

Following the above example, you need to run this command line:

chmod 777 /example/path/

chmod 777 /example/path/drupaltut.txt