IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » debug The latest public debug snipts.

showing 1-19 of 19 snipts for debug
  • A Friendly print_r version
    /**
     * Friendly print_r version
     **/
    function print_arr($variabile, $text='', $return=FALSE){
      if($text<>'') $text=" $text=";
      $type=gettype($variabile);
      switch($type){
          case "array":
          case "object":
              #$out="<p><pre>$text".var_export($variabile,TRUE)."</pre></p>";
              $out="<p><pre>$text".print_r($variabile,TRUE)."</pre></p>";
              break;
          case "NULL":
              $str="<p>NULL</p>";
          case "string":
          default:
              if(!isset($str)) $str=strval($variabile);
             $out="<p><pre>#".$type."[".strlen($str)."]:$text".($str)."</pre></p>";
              break;
      }
      if(!$return) echo $out;
      else return $out;
    }#end print_arr
    

    copy | embed

    0 comments - tagged in  posted by artilibere on Sep 03, 2010 at 8:10 a.m. EDT
  • Magento: debug
    <?php 
    
    // debug in magento
    
    Zend_Debug::dump($_product->getData()); 
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Jul 07, 2010 at 9:29 p.m. EDT
  • PHP enable error reporting
    <?php
    
    ini_set('error_reporting', E_ALL);
    ini_set('display_errors',1);
    
    ?>
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Jun 11, 2010 at 6:45 p.m. EDT
  • show php errors
    ini_set('display_errors', "1");
    ini_set('error_reporting', E_ALL ^ E_NOTICE);
    

    copy | embed

    0 comments - tagged in  posted by pazzypunk on Feb 02, 2010 at 2:20 p.m. EST
  • Log errors in diffent folders/files reflecting the application folder structure.
    <?php
    /**
     * Log PHP's error into separate files. Recommended for use in production site.
     * Should be used in set_error_handler() to handle certain PHP errors (i.e. E_STRICT).
     * @link http://www.php.net/manual/en/function.set-error-handler.php Reference
     */
    function errorHandler($errno, $errstr, $errfile=NULL, $errline=NULL, $errcontext=NULL) {
      // Log uncategorized errors
      if (is_null($errfile)) {
        $errfile = 'errors.log';
      }
    
      // Reconstruct the path
      // define('APP_DIR', '/my/application/')
      // define('LOG_DIR', '/log_dir/')
      // E.g. /my/application/controller/index.php -> /log_dir/controller/index.php
      $pos = strpos($errfile, APP_DIR);
      if ($pos !== FALSE) {
        // Strip off the application directory and attach log directory
        $errfile = LOG_DIR.substr($errfile, $pos + strlen(CMS_ROOT));
      }
      else {
        $errfile = LOG_DIR.$errfile; // E.g. /log_dir/errors.log
      }
      $dir = dirname($errfile);
      // Create dir if necessary
      if (! file_exists($dir)) {
        mkdir($dir, 0775, TRUE);
      }
      
      $logFile = fopen($errfile, 'a');
      fwrite($logFile, date('Y-m-d H:i:s ').$errstr);
      if ($errline) fwrite($logFile, " on line $errline");
      fwrite($logFile, "\n");
      fclose($logFile);
      
      if (PRODUCTION_SITE) // Prevent err msg from being printed out (log errors silently)
        return TRUE;
    
      return FALSE;
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Jan 21, 2010 at 2:46 a.m. EST
  • PHP Debug Print
    // inside PHP
    echo "<pre>"; var_dump($variable); echo "</pre>"; // DEBUGPRINT
    
    // inside HTML
    <?php echo "<pre>"; var_dump($variable); echo "</pre>"; // DEBUGPRINT ?>
    

    copy | embed

    0 comments - tagged in  posted by cbeier on Jan 05, 2010 at 11:27 a.m. EST
  • Code to format a printed PHP session, used to debug
    <?php
    //for normal session
    <pre>print_r($_SESSION)</pre>
    
    //for Codeigniter session
    <pre>print_r($this->session)</pre>
    

    copy | embed

    0 comments - tagged in  posted by richard on Dec 18, 2009 at 9:52 a.m. EST
  • debug for FireFox-FireBug / Other
    function debug(what){
    	if(window.console && window.console.firebug){
    		console.log((new Date).toString() + ' - ' + what);
    	}
    	else{
    		alert(what);
    	}
    }
    

    copy | embed

    0 comments - tagged in  posted by CorPao on Nov 11, 2009 at 4:09 a.m. EST
  • javascript debug for console or browser (uses jquery)
    function debug(a,tag) {
    	var bugs="", header = "[functionName](" + (tag||"")  + ")";
    	($.isArray(a) || isObject(a)) ? $.each(a, function(i, val) { bugs = bugs +i + ":" + val + ", ";}) :  bugs = a;
    	
    	if (window.console && window.console.log) {
    		window.console.log(header + bugs);
    	} else {
    		if ($("#debug").size() == 0) $("<ul id='debug'></ul>").appendTo("body").css({border:"1px solid #ccf",position:"absolute",top:"10px",right:"10px",width:"300px",padding:"10px",listStyle:"square"});
    		$("<li>").css({margin:"0 0 5px"}).appendTo("#debug").append(header).wrapInner("<b></b>").append(" " + bugs);
    	}
    }
    

    copy | embed

    0 comments - tagged in  posted by catcubed on Nov 10, 2009 at 6:39 p.m. EST
  • WP db debug plugin
    <?php
    
    
    	/*
         ** Plugin Name: debug
         ** Plugin URI: http://made.com.ua/en/
         ** Description: debug
         ** Version: 0
         ** Author: Oleg Butuzov
         ** Author URI: http://made.com.ua/
         */
    	 
    
    	add_action('wp_footer', 'made_com_ua_wp_footer');
    	   
    	function made_com_ua_wp_footer(){
    		global $wp_object_cache, $wpdb;
    		echo '<table width="90%" align="center">';
    		echo "<tr><th style='padding:5px;text-align:left;'>Cache Hits</th><td style='padding:5px;'>".$wp_object_cache->cache_hits."</td></tr>";
    		echo "<tr><th style='padding:5px;text-align:left;'>Cache Misses</th><td style='padding:5px;'>".$wp_object_cache->cache_misses."</td></tr>";
    		echo "<tr><th style='padding:5px;text-align:left;'>Total Time</th><td style='padding:5px;'>".timer_stop(0, 3)."</td></tr>";
    		echo "<tr><th style='padding:5px;text-align:left;'>DB Queries</th><td style='padding:5px;'>".get_num_queries()."</td></tr>";
    		echo '</table>';
    
    		echo "<table width='90%' align='center'>";
    		echo "<tr><th>SQL</th><td>TIME</td></tr>";
    		foreach($wpdb->queries as $item){
    			echo "<tr><td style='padding:5px;text-align:left;font-family:courier;'>".$item[0]."</td><td style='font-family:courier;padding:5px;text-align:left;'>".$item[1]."</td></tr>";
    		}
    		echo "</table>";
    		var_dump($GLOBALS['SQLCACHE']);
    	}
    
    ?>
    

    copy | embed

    0 comments - tagged in  posted by Butuzov on Sep 09, 2009 at 2:31 a.m. EDT
  • jquery print_r
    (function($){ 
      $.debug = { 
        dump: function(arr, level) { 
          var dumped_text = ""; 
          if(!level) level = 0; 
          var level_padding = ""; 
          for(var j=0;j<level+1;j++) level_padding += "    "; 
          if(typeof(arr) == 'object') { //Array/Hashes/Objects 
           for(var item in arr) { 
            var value = arr[item]; 
            
            if(typeof(value) == 'object') { //If it is an array, 
             dumped_text += level_padding + "'" + item + "' ...\n"; 
             dumped_text += $.debug.dump(value,level+1); 
            } else { 
             dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n"; 
            } 
           } 
          } else { //Stings/Chars/Numbers etc. 
           dumped_text = "===>"+arr+"<===("+typeof(arr)+")"; 
          } 
          return dumped_text; 
        }, 
        print_r: function(obj){ 
          document.write("<div id='debugContent'></div>"); 
           
          $("#debugContent").css({ 
            display: "block", 
            position: "absolute", 
            top: "0px", 
            right: "0px", 
            padding: "10px", 
            width: "700px", 
            background: "#ddd", 
            color: "black", 
            border: "solid 1px black" 
          }).html("<pre>"+$.debug.dump(obj)+"</pre><div id='close-debug'>Close</div>"); 
           
          $("#close-debug").css({cursor: "pointer"}).click(function(){ 
            $("#debugContent").remove(); 
          }); 
        } 
      }; 
    })(jQuery);
    
    // use: $.debug.print_r(arr)
    

    copy | embed

    1 comment - tagged in  posted by tbeseda on Aug 21, 2009 at 12:38 p.m. EDT
  • Network TCP backend for console access
    import code 
    import SocketServer
    import threading
    from select import select
    from time import sleep
    import sys
    
    ##indent or comment
    waitchars = (' ','\9','\11','#')
    
    useglobaldict = True #False
    
    class fakeout:
        """
        fakes the write method, if a thread register himself with a different writer
        the new writer is used when writing on this. Otherwise default writer is used
        """
        
        def __init__(self,default):
            self.default=default
            self.others={}
            
        def setout4thread(self,newkey,outs):
            self.others[newkey]=outs
            
        def write(self,s2w):
            t = threading.currentThread()
            if t in self.others:
                self.others[t].write(s2w)
            else:
                self.default.write(s2w)
                
        def __getattr__(self,name):
            t = threading.currentThread()
            if t in self.others:
                return getattr(self.others[t],name)
            else:
                return getattr(self.default,name)
        
    def registerouts(df,of,ef):
        """
        register on faked stdout and stderr
        """
        sys.stdout.setout4thread(df,of)
        sys.stderr.setout4thread(df,ef)
        
    class ipconsole(SocketServer.StreamRequestHandler):    
        """
        handles incoming connections
        and redirect network incomings to a python console
        """    
        
        def mywrite(self,str2w):
            sys.stdout.default.write(str2w)
            
        def mainloop(self):
            #fake stdout and stderr to redirect all to our socket
            registerouts(threading.currentThread(),self.wfile,self.wfile)
            # the interpreter and the buffer
            if useglobaldict:gdict = globals()
            else:gdict=dict(globals())
            c = code.InteractiveInterpreter(gdict)
            mybuf=""
            while True:
                r,w,x=select([self.rfile],[],[])
                if len(r)==0:continue
                data = self.rfile.readline()  
                if len(data)==0:
                    #closed socket => exit
                    return
                #strip it on the right side...some telent append unwanted chars                
                mybuf+=data.rstrip()+"\n"
                #check if we have indentation or comment...if so no use for compiling it
                if data[0] in waitchars:
                    continue
                try:
                    #try to compile
                    res = code.compile_command(mybuf)
                    if res is None: 
                        #uncompilable because incomplete...it should never enter here
                        #as long as incomplete source should not ahve been compiled (see above)
                        continue
                    #empy the buffer
                    mybuf=""
                    #execute whatsoever
                    c.runcode(res)                             
                except Exception,e:
                    #some exception...we print it and empy the buffer
                    print "exception ",e," in:\n",mybuf
                    mybuf=""
        
        def handle(self):
            #we do it in a thread to joke the stdout 
            df = threading.Thread(target=self.mainloop)
            df.start()
            #wait for the thread to end because exiting from here shuts down the connection
            df.join()
            
    sys.stdout=fakeout(sys.stdout)
    sys.stderr=fakeout(sys.stderr)
    
    def createServer(ip,port):
        """
        create the tcp console on the given ip and port
        """
        ss = SocketServer.TCPServer((ip,port),ipconsole)
        st = threading.Thread(target=ss.serve_forever)
        st.setDaemon(True)
        st.start()
        return st
    

    copy | embed

    0 comments - tagged in  posted by pdepmcp on Jun 09, 2009 at 5:04 a.m. EDT
  • Affiche le contenu d'un objet dans une nouvelle fenêtre
    function debug(object, returnSource) {
    	// Vérification de l'objet
    	if (typeof object == "object") {
    		// Création de la sortie HTML
    		output = '<html><head><title>Debug</title><style type="text/css">'
    			+'body { background: #FFF; font-family: sans-serif; font-size: 10px; }\n'
    			+'</style></head>\n'
    			+'<body><table style="width: 100%">';
    		j = 0;
    		for (i in object) {
    			if (object[i]) {
    				// Remplacement de caractères HTML dans les chaines
    				if (typeof object[i].replace == "function" && typeof object[i] == "string") {
    					value = object[i].replace(/&/g,"&amp;").replace(/\"/g,"&quot;").replace(/\'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
    				}
    				else {
    					value = object[i];
    				}//*/
    				output += '<tr>'
    					+'<th style="background: #'+(j%2 ? "DDD" : "EEE")+'; text-align: right; font-weight: bold;">'+i+'</th>\n'
    					+'<td style="background: #'+(j%2 ? "EEE" : "FFF")+';">';
    					if (i == "innerHTML") {
    						output += '<div>'+object[i]+'</div>'
    							+'<pre><b>Contenu HTML brut&nbsp;:</b>\n'
    							+object[i].replace(/&/g,"&amp;").replace(/\"/g,"&quot;").replace(/\'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;")
    							+'</pre>';
    					}
    					else {
    						output += object[i];
    					}
    					
    					+value+'</td></tr>\n';
    				j++;
    			}
    		}
    		output += '</table></body></html>';
    		
    		// Affichage ou retour de la sortie
    		if (!returnSource) {
    			outputWin = open('about:blank', 'debugOutputWin_'+Math.random());
    			outputWin.document.write(output);
    			outputWin.focus();
    			return outputWin;
    		}
    		else {
    			return output;
    		}
    	}
    	else {
    		alert("Impossible de debugger : la variable passée à la fonction debug() n'est pas un objet mais "
    			+"est de type \""+typeof(object)+"\".");
    		return false;
    	}
    }
    

    copy | embed

    0 comments - tagged in  posted by joanfabregat on Apr 08, 2009 at 1:39 p.m. EDT
  • simple class to work with SOS (http://solutions.powerflasher.com/products/sosmax/)
    import mx.utils.Delegate;
    
    class com.cyberhull.SOS {
    
    	private var _sendOnConnect:Array = [];
    	private var _socket:XMLSocket;
    	
    	private var _send:Function;
    	
    	private static var _instance:SOS; 
    		
    	public function SOS(port:Number) {
    		_socket = new XMLSocket();
    		_socket.onConnect = Delegate.create(this, handleConnect);
    		_socket.connect("localhost", port?port:4444);
    	}	
    	
    	private function handleConnect(success:Boolean) : Void {
    		if (!success) {
    			trace("Unable to connect to SOS!");
    			_send = trace;
    		} else {
    			trace("Connected to SOS!");
    			_send = Delegate.create(_socket, _socket.send);
    			SOS.info("SOS connected!");
    		}
    			
    		for (var i:Number = 0; i<_sendOnConnect.length; i++) {
    			_send(_sendOnConnect[i]);	
    		}		
    	
    	}
    	
    		
    	private function sendXML(xml:String):Void {
    		if (_send) {
    			_send(xml);
    			return;
    		}
    		
    		_sendOnConnect.push(xml);
    	}
    	
        private static function serialize(obj:Object, all:Array):String {
        	
        	if (typeof(obj)=="string") return "\""+obj+"\"";
        	if (typeof(obj)=="number") return String(obj);
    		if (typeof(obj)=="boolean") return String(obj);
    		if (obj==null) return "null";
    		if (obj==undefined) return "undefined";
    		
    		if (!all) {
    			all = [];
    		} else {
    			for (var i:Number =0; i< all.length; i++) if (all[i]===obj) {
    				return "#"+obj.toString();
    			}
    		}
    		all.push(obj);
    		
    		if (obj instanceof Array) {			
    			var s:String = "[";
    			var delim:String = "";
    			for (var i:Number=0; i<obj.length; i++) {
    				s+=delim;
    				s+=serialize(obj[i], all);
    				delim = ", ";
    			}		
    			s+="]";
    			return s;
    		}
        	
        	var s:String = "{";  	
        	for (var p in obj){
        		if (typeof(obj[p])=="function") continue;
        		s += p + ": "+serialize(obj[p], all)+", ";	
        	}
        	
        	s+="}";
        	return s;
        }
        
        private static function send(message:String, key:String): Void {
        	var xml:String = "!SOS<showMessage key='"+key+"'>"+message+"</showMessage>";
        	
        	if (!_instance) _instance = new SOS();
        	_instance.sendXML(xml);
    
        }
        
        private static function sendFolded(title:String, message:String, key:String):Void {
        
        }
        
        public static function fatal(message:Object):Void {
        	send(serialize(message), "fatal");
        }
        
        public static function error(message:Object):Void {
        	send(serialize(message), "error");
        }
        
        public static function warn(message:Object):Void {
        	send(serialize(message), "warn");
        }
        
        public static function info(message:Object):Void {
        	send(serialize(message), "info");
        }
        
        public static function debug(message:Object): Void {
        	send(serialize(message), "debug");
        }
        
        
        	
    }
    

    copy | embed

    2 comments - tagged in  posted by ambienthack on Apr 08, 2009 at 10:52 a.m. EDT
  • CakePHP's debug function
    <?php
    function debug($var = false, $showHtml = false, $showFrom = true) {
        if ($showFrom) {
            $calledFrom = debug_backtrace();
            echo '<strong>';
            echo substr(str_replace(ROOT, '', $calledFrom[0]['file']), 1);
            echo '</strong>';
            echo ' (line <strong>' . $calledFrom[0]['line'] . '</strong>)';
        }
        echo "\n<pre class=\"cake-debug\">\n";
    
        $var = print_r($var, true);
        if ($showHtml) {
            $var = str_replace('<', '&lt;', str_replace('>', '&gt;', $var));
        }
        echo $var . "\n</pre>\n";
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by wvega on Apr 06, 2009 at 11:13 p.m. EDT
  • debug apache variables
    RewriteCond %{QUERY_STRING} !vardump 
    RewriteRule (.*) http://localhost/debug.php?vardump&HTTP_USER_AGENT=%{HTTP_USER_AGENT}&HTTP_REFERER=%{HTTP_REFERER}&HTTP_COOKIE=%{HTTP_COOKIE}&HTTP_FORWARDED=%{HTTP_FORWARDED}&HTTP_HOST=%{HTTP_HOST}&HTTP_PROXY_CONNECTION=%{HTTP_PROXY_CONNECTION}&HTTP_ACCEPT=%{HTTP_ACCEPT}&DOCUMENT_ROOT=%{DOCUMENT_ROOT}&SERVER_ADMIN=%{SERVER_ADMIN}&SERVER_NAME=%{SERVER_NAME}&SERVER_ADDR=%{SERVER_ADDR}&SERVER_PORT=%{SERVER_PORT}&SERVER_PROTOCOL=%{SERVER_PROTOCOL}&SERVER_SOFTWARE=%{SERVER_SOFTWARE}&REMOTE_ADDR=%{REMOTE_ADDR}&REMOTE_HOST=%{REMOTE_HOST}&REMOTE_PORT=%{REMOTE_PORT}&REMOTE_USER=%{REMOTE_USER}&REMOTE_IDENT=%{REMOTE_IDENT}&REQUEST_METHOD=%{REQUEST_METHOD}&SCRIPT_FILENAME=%{SCRIPT_FILENAME}&PATH_INFO=%{PATH_INFO}&QUERY_STRING=%{QUERY_STRING}&AUTH_TYPE=%{AUTH_TYPE}&TIME_YEAR=%{TIME_YEAR}&TIME_MON=%{TIME_MON}&TIME_DAY=%{TIME_DAY}&TIME_HOUR=%{TIME_HOUR}&TIME_MIN=%{TIME_MIN}&TIME_SEC=%{TIME_SEC}&TIME_WDAY=%{TIME_WDAY}&TIME=%{TIME}&API_VERSION=%{API_VERSION}&THE_REQUEST=%{THE_REQUEST}&REQUEST_URI=%{REQUEST_URI}&REQUEST_FILENAME=%{REQUEST_FILENAME}&IS_SUBREQ=%{IS_SUBREQ}&HTTPS=%{HTTPS} [R=302,L,QSA] 
    

    copy | embed

    0 comments - tagged in  posted by wally on Mar 31, 2009 at 8:40 a.m. EDT
  • ruby ssh debug
    #step 0
    mtr status
    
    #step 1
    mtr set_option [appname] debug=true 
    
    #step 2
    mtr stop [appname]
    mtr start [appname] 
    

    copy | embed

    0 comments - tagged in  posted by AvidDeville on Mar 06, 2009 at 2:01 a.m. EST
  • Php debug
    <?php
    $debug = true;// false for live website
    $contact_email  =  "";
    
    # **************************** #
    # ***** ERROR MANAGEMENT ***** #
    // Create the error handler.
    function my_error_handler ($e_number, $e_message, $e_file, $e_line, $e_vars) {
    
    	global $debug, $contact_email;
    	
    	// Build the error message.
    	$message = "An error occurred in script '$e_file' on line $e_line: \n<br />$e_message\n<br />";
    	
    	// Add the date and time.
    	$message .= "Date/Time: " . date('n-j-Y H:i:s') . "\n<br />";
    	
    	// Append $e_vars to the $message.
    	$message .= "<pre>" . print_r ($e_vars, 1) . "</pre>\n<br />";
    	
    	if ($debug) { // Show the error.
    	
    		echo '<p class="error">' . $message . '</p>';
    		
    	} else { 
    	
    		// Log the error:
    		error_log ($message, 1, $contact_email); // Send email.
    		
    		// Only print an error message if the error isn't a notice or strict.
    		if ( ($e_number != E_NOTICE) && ($e_number < 2048)) {
    			echo '<p class="error">A system error occurred. We apologize for the inconvenience.</p>';
    		}
    		
    	} // End of $debug IF.
    
    } // End of my_error_handler() definition.
    // Use my error handler:
    set_error_handler ('my_error_handler');
    ?>
    

    copy | embed

    0 comments - tagged in  posted by rlweb on Dec 28, 2008 at 11:39 a.m. EST
  • fix for console.log
    if (typeof console.log != function) {
        console.log = function(){ /* ... */ } 
    }
    

    copy | embed

    0 comments - tagged in  posted by misterbrandt on Dec 23, 2008 at 5:15 p.m. EST
Sign up to create your own snipts, or login.