How to print a debug log?

  • I'd like to debug some PHP code, but I guess printing a log to screen or file is fine for me.

    How should I print a log in PHP code?

    The usual print/printf seems to go to HTML output not the console.

    I have Apache server executing the PHP code.

  • A lesser known trick is that mod_php maps stderr to the Apache log. And, there is a stream for that, so file_put_contents('php://stderr', print_r($foo, TRUE)) will nicely dump the value of $foo into the Apache error log.

  • error_log(print_r($variable, TRUE)); 

    might be useful

  • You can use error_log to send to your servers error log file (or an optional other file if you'd like)

  • If you are on Linux:

    file_put_contents('your_log_file', 'your_content');


    error_log ('your_content', 3, 'your_log_file');

    and then in console

    tail -f your_log_file

    This will show continuously the last line put in the file.

  • You need to change your frame of mind. You are writing PHP, not whatever else it is that you are used to write. Debugging in PHP is not done in a console environment.

    In PHP, you have 3 categories of debugging solutions:

    1. Output to a webpage (see dBug library for a nicer view of things).
    2. Write to a log file
    3. In session debugging with xDebug

    Learn to use those instead of trying to make PHP behave like whatever other language you are used to.

  • Are you debugging on console? There are various options for debugging PHP. The most common function used for quick & dirty debugging is var_dump.

    That being said and out of the way, although var_dump is awesome and a lot of people do everything with just that, there are other tools and techniques that can spice it up a bit.

    Things to help out if debugging in a webpage, wrap <pre> </pre> tags around your dump statement to give you proper formatting on arrays and objects.


    <div> some html code ....
          <a href="<?php $tpl->link;?>">some link to test</a>
          dump $tpl like this:
        <?php var_dump($tpl); ?>

    And, last but not least make sure if debugging your error handling is set to display errors. Adding this at the top of your script may be needed if you cannot access server configuration to do so.

    ini_set('display_errors', '1');

    Good luck!

  • If you don't want to integrate a framework like Zend, then you can use the trigger_error method to log to the php error log.

  • Simply way is trigger_error:

     trigger_error("My error");

    but you can't put arrays or Objects therefore use


  • You can also write to a file like this:

    $logFilePath = '../logs/debug.text';
    // if you want to concatenate:
    if (file_exists($logFilePath)) {
    // for timestamp
    $currentTime = date(DATE_RSS);
    // echo log statement(s) here
    echo "\n\n$currentTime - [log statement here]";
    $logFile = fopen($logFilePath, 'w');
    fwrite($logFile, ob_get_contents());

    Make sure the proper permissions are set so php can access and write to the file (775).

  • You can use the php curl module to make calls to This works great in an secure, corporate environment where certain restrictions in the php.ini exists that restrict usage of file_put_contents.

  • This a great tool for debugging & logging php: PHp Debugger & Logger

    It works right out of the box with just 3 lines of code. It can send messages to the js console for ajax debugging and can replace the error handler. It also dumps information about variables like var_dump() and print_r(), but in a more readable format. Very nice tool!

  • I have used many of these, but since I usually need to debug when developing, and since I develop on localhost, I have followed the advice of others and now write to the browser's JavaScript debug console (see

    That means that I can look at the web page which my PHP is generating in my browser & press F12 to quickly show/hide any debug trace.

    Since I am constantly looking at the developer tools for debugger, CSS layout, etc, it makes sense to look at my PHP loggon there.

    If anyone does decide to us that code, I made one minor change. After

    function debug($name, $var = null, $type = LOG) {

    I added

    $name = 'PHP: ' . $name;

    This is because my server side PHP generates HTML conatining JavaScript & I find it useful to distinguish between output from PHP & JS.

    (Note: I am currently updating this to allow me to switch on & off different output types: from PHP, from JS, and database access)

  • I use cakephp so I use:

    $this->log(YOUR_STRING_GOES_HERE, 'debug');

  • You can use:

    echo '<script>console.log("debug log")</script>';

  • You can use


    or if you want to print that statement in an log you can use

    AddLog("anypage.php","string: ".$string,ERR_DEBUG_LOW);



  • S

    I am trying to create a conditional loop based on the answers from my selection dialog box in Matlab. But i dont know the actual code for it.

    Tried some trial and error but no luck.

    <pre class="lang-matlab prettyprint-override">``` list = {'Raw water','Treated Water','Sample water'}; [indx,tf] = listdlg('PromptString','Select water type:','SelectionMode','single','ListString',list); **I want to provide 3 different conditions for each selection from my selection dialog box.**

    read more
  • S

    I want to let user open file's content into this TextView

    child: SingleChildScrollView( child: Text('**THIS IS WHERE I WANT TO LOAD OPENED FILES**' ), ),

    read more
  • S

    You need to use StartContinuousRecognitionAsync instead of recognizeOnceAsync

    read more
  • S

    It is not transcribing full audio file and the process is exciting before trancribing the full audio file. It is only transcribing first few seconds of the audio file.

    I referred this

    Can somebody help me out with this?

    // pull in the required packages. var sdk = require("microsoft-cognitiveservices-speech-sdk"); var fs = require("fs"); var axios = require('axios') // replace with your own subscription key, // service region (e.g., "westus"), and // the name of the file you want to run // through the speech recognizer. var subscriptionKey = ""; var serviceRegion = ""; // e.g., "westus" var filename = "output2.wav"; // 16000 Hz, Mono // create the push stream we need for the speech sdk. var pushStream = sdk.AudioInputStream.createPushStream(); // open the file and push it to the push stream. fs.createReadStream(filename).on('data', function (arrayBuffer) { // console.log(arrayBuffer); pushStream.write(arrayBuffer.buffer); }).on('end', function () { pushStream.close(); }); // we are done with the setup console.log("Now recognizing from: " + filename); // now create the audio-config pointing to our stream and // the speech config specifying the language. var audioConfig = sdk.AudioConfig.fromStreamInput(pushStream); var speechConfig = sdk.SpeechConfig.fromSubscription(subscriptionKey, serviceRegion); // setting the recognition language to English. speechConfig.speechRecognitionLanguage = "en-US"; // create the speech recognizer. var recognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig); // start the recognizer and wait for a result. recognizer.recognizeOnceAsync( function (result) { console.log(result); recognizer.close(); recognizer = undefined; }, function (err) { console.trace("err - " + err); recognizer.close(); recognizer = undefined; });

    read more
  • S

    Messages with both notification and data payload, when received in the background.

    Change the notification type data

    $arrayToSend = array('to' => $token, 'data' => $notification,'priority'=>'high');

    Please go through the below documentation

    You have to create the custom notification.

    private void setNotification(RemoteMessage content) { Log.d(TAG, "custom notification: "); Intent intent = new Intent(this, NotificationActivity.class); if (!content.getData().get("url").isEmpty()) intent.putExtra("url", content.getData().get("url")); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setAction(Long.toString(System.currentTimeMillis())); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custome_notification); remoteViews.setTextViewText(, currentDate()); remoteViews.setTextViewText(, content.getData().get("text")); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, getPackageName()) .setSmallIcon(R.drawable.ic_alert) .setContent(remoteViews) .setAutoCancel(true) .setSound(defaultSoundUri); notificationBuilder.setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // To avoid replacing old notification by new one. To set new id for every new Notification following notifications. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel mChannel = new NotificationChannel(getPackageName(), "AppName", importance); notificationManager.createNotificationChannel(mChannel); } int notifyId = (int) System.currentTimeMillis(); notificationManager.notify(notifyId,; }

    read more


  • 2
  • 1
  • 5
  • 1
  • 3
  • 3
  • 8
  • 2