PHP Debugging PHP

The debugging functions help you figure out just what the heck is going on with the inevitable broken script. Some of these functions make diagnostic information available to you inside your script. Others communicate with either a system log or a remote debugger.

assert(expression)
The assert function tests an expression. If the assertion is true, no action is taken and the script continues. If the assertion is false, behavior is dictated by the assertion options. By default, assertions are not active, which means they are simply ignored. Use assert_options to activate them.

Assertions are a nice way to add error checking to your code, especially paranoid checks that are useful during development but unneeded during production.

<?
//create custom assertion function
function failedAssertion($file, $line, $expression)
{
print("On line $line, in file '$file' ");
print("the following assertion failed:
'$expression'<BR>n");
}
//turn on asserts
assert_options(ASSERT_ACTIVE, TRUE);
//bail on assertion failure
assert_options(ASSERT_CALLBACK, "failedAssertion");
//assert a false expression
assert(1 == 2);
?>

value assert_options(integer flag, value)
Use assert_options to get and set assert flags. Table 8.8 lists the flags and their meanings. The revious value is returned. Most of the options expect a boolean because they are either on or ff. The exception is the option for setting the callback function. This option expects the name of a function to be called when an assertion fails. This function will be called with three arguments: he filename, the line number, and the expression that evaluated as FALSE.

value call_user_function(string function, ...)
Use call_user_function to execute a function you've defined. The function argument names the function. Arguments to be passed to the function follow.

value call_user_function(string function, ...)

value call_user_method(string method, string object, ...)
Use call_user_method to execute a method defined in an object. You are required to name a method and an object. Any arguments to pass to the method follow.

closelog()
The closelog function closes any connection to the system log. Calling it is optional, as PHP will close the connection for you when necessary. See syslog for an example of use.

boolean connection_aborted()
Use connection_aborted to test if a request for your script was aborted. The user may do this by clicking the stop button on the browser, or closing the browser completely. Ordinarily your script will stop execut- ing when aborted. However, you may change this behavior with the ignore_user_abort function. You can also set abort handling using commands in php.ini or with an Apache directive.

<?
//allow script continuation if aborted
ignore_user_abort(TRUE);
//fake a long task
sleep(20);
//check for abort
if(connection_aborted())
{
//write to log that the process was aborted
openlog("TEST", LOG_PID | LOG_CONS, LOG_USER);
syslog(LOG_INFO, "The fake task has been aborted!");
closelog();
}
else
{
print("Thanks for waiting!n");
}
?>

integer connection_status()
The connection_status function returns an integer describing the status of the connection to the browser. The integer uses bitfields to signal whether a connection was aborted or timed out. That is, binary digits are flipped on to signal either of the conditions. The first bit signals whether the script aborted. The second signals whether the script reached its maximum execution time. Rather than using 1 or 2, you can use the convenient constants ABORTED and TIMEOUT. There's also a constant named NORMAL, which is set to zero, meaning no bitfields are turned on. An alternative to connection_status is to use connect_aborted and connection_timeout, which each return TRUE or FALSE.

<?
function cleanUp()
{
$status = connection_status();
$statusMessage = date("Y-m-d H:i:s");
$statusMessage .= " Status was $status. ";
if($status & ABORTED)
{
$statusMessage .= "The script was aborted. ";
}
if($status & TIMEOUT)
{
$statusMessage .= "The script timed out. ";
}
$statusMessage .= "n";
//write status to log file
error_log($statusMessage, 3, "status.log");
}
//set cleanUp to the shutdown function
register_shutdown_function("cleanUp");
//wait out the max execution time
sleep(35);
print("Fake task finished.n");
?>

boolean connection_timeout()
The connection_timeout function returns TRUE when the current script has stopped because the maximum execution time was reached. It is really of use only inside a function you've registered as a shutdown function with register_shutdown_function. You can use set_time_limit to adjust the time a script is allowed to run. Alternatively, you may wish to use connection_status.

<?
function cleanUp()
{
if(connection_timeout())
{
$statusMessage = date("Y-m-d H:i:s");
$statusMessage .= " The script timed out. n";
//write status to log file
error_log($statusMessage, 3, "status.log");
}
}
//set cleanUp to the shutdown function
register_shutdown_function("cleanUp");
//wait out the max execution time
while(true);
print("Fake task finished.n");
?>

debugger_off()
The debugger_off function tells PHP to stop sending debugging information to the remote debugger.

<?
debugger_off();
?>

boolean debugger_on(string host)
Use debugger_on to enable remote debugging. Diagnostic information will be sent to the specified host using the port set in php.ini, which is 7869 by default.

<?
debugger_on("127.0.0.1");
?>

boolean error_log(string message, integer type, string destination, string extra_headers)
The error_log function sends an error message to one of four places depending on the type argument. The four values for the type argument are listed in Table 8.9. An alternative to error_log is the syslog function.

<?
//send log message via email to root
error_log("The error_log is working", 1, "root", "");
?>

error_log-Message-Types

boolean extension_loaded(string extension)
Use extension_loaded to test for the presence of an extension.

<?
if(extension_loaded("php_mysql.dll"))
{
print("php_mysql.dll is present");
}
else
{
print("php_mysql.dll is not present");
}
?>

value func_get_arg(integer argument)
The func_get_arg function allows you to get by number an argument passed to a function you write. The first argument will be number zero. This allows you to write functions that take any number of arguments. The return value might be any type, matching the type of the argument being fetched. The func_num_args function returns the number of arguments available.

<?
/*
** Function concat
** Input: any number of strings
** Output: string
** Description: input strings are put together in
** order and returned as a single string.
*/
function concat()
{
//start with empty string
$returnValue ="";
//loop over each argument
for($i=0; $i < func_num_args(); $i++)
{
//add current argument to return value
$returnValue .= func_get_arg($i);
}
return($returnValue);
}
//prints "OneTwoThree"
print(concat("One", "Two", "Three") . "<BR>n");
?>

array func_get_args()
Use func_get_args to get an array containing all the arguments passed as arguments to the function. The elements of the array will be indexed withintegers, starting with zero. This provides an alternative to using func_get_arg and func_num_args.

<?
/*
** Function gcd
** Input: any number of integers
** Output: integer
** Description: Returns the greatest common
** denominator from the input.
*/
function gcd()
{
/*
** start a smallest value and try every value
** until we get to 1, which is common to all
*/
$start = 2147483647;
foreach(func_get_args() as $arg)
{
if(abs($arg) < $start)
{
$start = abs($arg);
}
}
for($i=$start; $i > 1; $i-)
{
//assume we will find a gcd
$isCommon = TRUE;
//try each number in the supplied arguments
foreach(func_get_args() as $arg)
{
//if $arg divided by $i produces a
//remainder, then we don't have a gcd
if(($arg % $i) != 0)
{
$isCommon = FALSE;
}
}
//if we made it through the previous code
//and $isCommon is still TRUE, then we found
//our gcd
if($isCommon)
{
break;
}
}
return($i);
}
//prints 5
print(gcd(10, 20, -35) . "<BR>n");
?>

integer func_num_args()
The func_num_args function returns the number of arguments passed to a function. See the description of func_get_arg for an example of use.

boolean function_exists(string function)
Use function_exists to test that a function is available, either natively or defined previously by PHP code.

<?
$function = "date";
if(function_exists($function))
{
print($function . " exists");
}
?>

object get_browser(string user_agent)
The get_browser function works with the browscap.ini (browser capabilities) file to report the capabilities of a browser. The user_agent argument is the text a browser identifies itself with during an HTTP transaction. If you leave out this argument, PHP uses HTTP_USER_AGENT, a variable created by PHP for you. The argument is matched against all the browsers in the browscap.ini file. When a match occurs, each of the capabilities becomes a property in the object returned.

The location of the browscap.ini file is specified in php.ini using the browscap directive. If the directive is not used, or PHP can't match a browser to an entry in your browscap.ini file, no error will be produced. However, the returned object will have no properties.

Microsoft provides a browscap.ini file for use with its Web server, but it is not freely distributable. In response, PHP has an official browscap.ini file.

$browser = get_browser();
print("You are using " . $browser->browser . "<BR>n");
if($browser->javascript)
{
print("Your browser supports JavaScript.<BR>n");
}
?>

string get_cfg_var(string variable)
The get_cfg_var function returns the value of the specified configuration variable. These are the variables specified in php.ini or in Apache's configuration files. You can get a report on all configuration information by calling the phpinfo function.

<?
print("Scripts are allowed to run " .
get_cfg_var("max_execution_time") .
" seconds");
?>

string get_class(object variable)
The get_class function returns the name of the class for the given object.

<?
class animal
{
var $name;
}
$gus = new animal;
print("Gus is of type " . get_class($gus) . "<BR>n");
?>

array get_class_methods(string class)
The get_class_methods function returns an array of the names of the methods for the given class.

<?
class dog
{
var $name="none";
var $sound="woof!";
function speak()
{
print($this->sound);
}
}
$gus = new dog;
$gus->name = "Gus";
foreach(get_class_methods("dog") as $method)
{
print("$method<BR>n");
}
?>

array get_class_vars(string class)
The get_class_vars function returns an array containing properties of a class and their default values. Compare this function to get_object_vars.

get_meta_tags

get_meta_tags

get_meta_tags

string get_current_user()
The get_current_user function returns the name of the user who owns the script being executed. This function isn't guaranteed to have any meaning under Windows 98.

<?
print(get_current_user());
?>

string getcwd()
The getcwd function returns the name of the current working directory, including the full path.

<?
print(getcwd());
?>

array get_extension_funcs(string extension)
Use get_extension_funcs to get an array of the names of functions created by an extension.

array get_loaded_extensions()
The get_loaded_extensions function returns an array of the names of the extensions available. This includes extensions compiled into PHP or loaded with dl. Another way to see this list is with phpinfo.

array get_object_vars(object data)
The get_object_vars function returns an array describing the properties of an object and their values. See get_class_vars for an example of use.

boolean highlight_file(string filename)
The highlight_file function prints a PHP script directly to the browser using syntax highlighting. HTML is used to emphasize parts of the PHP language in order to aid readability.

<?
//highlight this file
highlight_file(__FILE__);
?>

boolean highlight_string(string code)
The highlight_string function prints a string of PHP code to the browser using syntax highlighting.

<?
//create some code
$code = "print("a string");";
//highlight sample code
highlight_string($code);
?>

string get_html_translation_table (integer table)
Use get_html_translation_table to get the table used by htmlentities and htmlspecialchars. By default the former is returned, but if table is 1, the table used by htmlspecialchars is returned.

<?
$trans = get_html_translation_table(HTML_ENTITIES);
print("pre>");
var_dump($trans);
print("/pre>n");
?>

integer get_magic_quotes_gpc()
The get_magic_quotes_gpc function returns the magic_quotes_gpc directive setting, which controls whether quotes are escaped automatically in user-submitted data.

<?
if(get_magic_quotes_gpc() == 1)
{
print("magic_quotes_gpc is on");
}
else
{
print("magic_quotes_gpc is off");
}
?>

integer get_magic_quotes_runtime()
The get_magic_quotes_runtime function returns the magic_quotes_ runtime directive setting, which controls whether quotes are escaped automatically in data retrieved from databases. You can use set_magic_quotes_runtime to change its value.

<?
if(get_magic_quotes_runtime() == 1)
{
print("magic_quotes_runtime is on");
}
else
{
print("magic_quotes_runtime is off");
}
?>

string get_parent_class(object variable)
The get_parent_class function returns the name of the parent class for an object.

<?
class animal
{
var $name;
}
class dog extends animal
{
var $owner;
}
$gus = new dog;
$gus->name = "Gus";
//Gus is of type dog, which is of type animal
print("$gus->name is of type " .
get_class($gus) . ", which is of type ".
get_parent_class($gus) . "BR>n");
?>

integer getlastmod()
The getlastmod function returns the date the executing script was last modified. The date is returned as a number of seconds since January 1, 1970. This is the same as calling filemtime on the current file.

<?
printf("This script was last modified %s",
date("m/d/y", getlastmod()));
?>

integer getmyinode()
The getmyinode function returns the inode of the executing script. Under Windows, zero is always returned. You can get the inode of any file using fileinode.

print(getmyinode());
?>

integer getmypid()
The getmypid function returns the process identifier of the PHP engine. It may not return anything under Windows 98.

<?
print(getmypid());
?>

integer getmyuid()
The getmyuid function returns the user identifier of the owner of the script.

<?
print(getmyuid());
?>

array getrusage(integer children)

The getrusage function is a wrapper for the C function of the same name. It reports information about the resources used by the calling process. If thechildren argument is 1, the function will be called with the RUSAGE_CHILDREN constant. You may wish to read the man page for more information.

<?
//show CPU time used
$rusage = getrusage(1);
print($rusage["ru_utime.tv_sec"] . " seconds
used.");
?>

boolean headers_sent()
The headers_sent function returns TRUE if HTTP headers have been sent. Headers must precede any content, so executing a print statement or placing text outside PHP tags will cause headers to be sent. Attempting to add headers to the stack after they're sent causes an error.

<?
if(headers_sent())
{
print("Can't add more headers!BR>n");
}
else
{
header("X-Debug: It's OK to send a header");
}
?>

boolean leak(integer bytes)
The leak function purposely leaks memory. It is useful mostly for testing the garbagecollecting routines of PHP itself. You might also use it to simulate lots of memory usage if you were stress-testing.

<?
//leak 8 megs
leak(8388608);
?>

boolean method_exists(object variable, string method)
The method_exists function returns TRUE when the named method exists in the specified object.

<?
class animal
{
var $name;
}
class dog extends animal
{
var $owner;
function speak()
{
print("woof!");
}
}
$gus = new dog;
$gus->name = "Gus";
if(method_exists($gus, "speak"))
{
$gus->speak();
}
?>

openlog(string identifier, integer option, integer facility)
The openlog function begins a connection to the system log and calls C's openlog function. It is not strictly required to call openlog before using syslog, but it may be used to change the behavior of the syslog function. You may wish to refer to the man page for openlog for more details. On Windows, emulation code is used to mimic UNIX functionality.

The identifier argument will be added to the beginning of any messages sent to the system log. Usually this is the name of the process or task being performed.

The option argument is a bitfield that controls toggling of miscellaneous options. Use a logical-or operator to combine the options you want. Only the LOG_PID option has any effect under Windows.

openlog(string identifier, integer option, integer facility)

The facility argument sets a default value for the source of the error—that is, from which part of the system the report comes. The argument is ignored under Windows.See syslog for an example of use.

openlog-Facilities

phpcredits(integer flags)
The phpcredits function prints information about the major contributors to the PHP project. If the optional flags argument is left out, all information will be provided. Otherwise, you may combine the flags listed to choose a specific set of information. The PHP_FULL_PAGE constant will cause the credits to be surrounded with minimal tags for defining an HTML page.

phpcredits

phpcredits

Flags-for-phpcredits

boolean phpinfo(integer flags)
The phpinfo function sends a large amount of diagnostic information to the browser and returns TRUE. The flags argument is not required. By default all information is returned. You may use the flags listed with bitwise OR operators to choose specific information.
The complete set of information will contain
PHP version
Credits
Operating system of the Web server
Extensions compiled into PHP executable
Every configuration variable
Every environment variable
Apache variables if running as an Apache module
HTTP headers

Flags-for-phpcredits

Calling phpinfo is a good way to find out which environment variables are available to you.

<?
phpinfo();
?>

string phpversion()
The phpversion function returns a string that describes the version of PHP executing the script.

<?
print("PHP version" . phpversion() . "<BR>n");
<?

print_r(expression)
The print_r function prints the value of an expression. If the expression is a string, integer, or double, the simple representation of it is sent to the browser. If the expression is an object or array, special notation is used to show indices or property names. Arrays and objects are explored recursively in the cases where objects or arrays are contained within each other.

<?
//define some test variables
$s = "a string";
$a = array("x", "y", "z", array(1, 2, 3));
//print a string
print_r($s);
print("n");
//print an array
print_r($a);
print("n");
?>

show_source
Use show_source as an alias to highlight_file.

syslog(integer priority, string message)
The syslog function adds a message to the system log. It is a wrapper for C's function of the same name. The priority is an integer that stands for how severe the situation is. Under UNIX the priority may cause the system to take special measures.

Under Windows NT, emulation code is used to simulate the UNIX functionality. Messages generated by the syslog function are added to theapplication log, which may be viewed with Event Viewer. The priority isused in two ways. First, it is translated into being either an error, a warning, or information. This determines the icon that appears next to the message in Event Viewer. It is also used to fill the Category column. The Event column will always be set to 2000 and the User column will be set to null.

syslog-Prioritiessyslog-Priorities

var_dump(expression,...)
The var_dump function reports all information about a given variable. Information is printed directly to the browser. You may supply any number of variables separated by commas. The output of the command is well formatted, including indention for cases such as arrays containing other arrays. Arrays and objects are explored recursively.

<?
//create a directory object
$d = dir(".");
//dump info about it
var_dump($d)
?>

string zend_version()
Use zend_version to get the version of the Zend library.

<?
print(zend_version());
?>


Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP Topics