In JavaScript, I can use console.log()
to print values to the browser console, which helps me debug my code. I am now working with PHP and want to know how I can log or print values in PHP for debugging. What is the equivalent of console.log()
in PHP?
1. You can use echo
or print_r()
to display values on the web page.
2. Using error_log
:
$message = "Something went wrong!";
error_log($message);
This will add the message to the server’s error log
or
error_log($message, 3, "/path/to/logfile.log");
Logging to a custom file
3. Create your own Log file
file_put_contents('/path/to/log_'.date("j.n.Y").'.log', 'Sexy', FILE_APPEND);
I created a function myself to text wordpress code
function woolog($msg){
file_put_contents(ABSPATH . '/log_'.date("j.n.Y").'.log', $msg . PHP_EOL, FILE_APPEND);
}