Error reporting - How to Debug PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
DogBot
Forum Newbie
Posts: 5
Joined: Tue Sep 25, 2007 9:59 am

Error reporting - How to Debug PHP

Post by DogBot »

I am a complete newbie to PHP. I have done some ColdFusion Programming though.

This is where my question stems from. In CF you get very verbose error reporting which is very helpful when you are starting out with a new language. In PHP there is none, other than error reporting you specifically code yourself ....if your page has errors it just fails and displays nothing at all! and you have NO CLUE what went wrong....was it the database? a variable was mispelled? etc.

MY QUESTION IS : AM I WRONG? I hope I am ....and it is just some server setting I am unable to find a reference to in the documentation.

Java and Javascript also have this problem but there are frameworks that you can load that enable robust error reporting. Perhaps there is a PHP equivalent?

Thanks

P.D. in CF you can also have it report render time, database access information, variables and tons of other info that is very useful while you develop. Is this possible in PHP?
Last edited by DogBot on Wed Sep 26, 2007 1:52 pm, edited 1 time in total.
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Post by aceconcepts »

It sounds like you need to turn on your error reporting

http://uk3.php.net/error-reporting
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Post by Zoxive »

Xdebug is nice too.
User avatar
DogBot
Forum Newbie
Posts: 5
Joined: Tue Sep 25, 2007 9:59 am

I just knew it was something that simple

Post by DogBot »

THANK YOU ALL..

I just knew it was something that simple!

PHP is just too complete to not have this. I am just getting to know PHP. I have developed for a long time with CF but I wish I had tried PHP before, it is really easy and robust.
User avatar
DogBot
Forum Newbie
Posts: 5
Joined: Tue Sep 25, 2007 9:59 am

THIS IS NOT WORKING

Post by DogBot »

THIS IS NOT WORKING. Please remember a a complete newbie. Thanks

Where do I put this instruction? At the top of my php code? In a separate file? I have read about an php.ini file...should it go there? if so, where do I find this file? should I ask my host to do this?

I have tried the following a the top of my script file whitout success:

Code: Select all

<?php error_reporting(2048);?>

Code: Select all

<?php error_reporting(E_ALL);?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

If you are having parse level errors, they fire before any code in the script is processed. If your host uses Apache (and allows overrides) you can upload an .htaccess file that sets the error reporting level among other settings.

If you haven't already, you should also be testing locally. If you need help installing a local server setup on your computer, read through the stickies in the Installation and Configuration board and/or the Starter thread(s) linked from the Forum Tour -- link to that provided in signature at this time.
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Post by Zoxive »

Run the following in a [s]few[/s] file. And post the results.

new*

Code: Select all

<?php

$neg = array('off', 0, false, '', null);
$flags = array(
        'Register Globals' => 'register_globals',
        'Short Tags' => 'short_open_tag',
        'Display Errors' => 'display_errors',
        'Magic Quotes GPC' => 'magic_quotes_gpc',
        'Magic Quotes Runtime' => 'magic_quotes_runtime',
        'Magic Quotes Sybase' => 'magic_quotes_sybase',
);
$ve = phpversion();
$os = PHP_OS;
$er = intval(error_reporting());
foreach ($flags as $n => $v)
{
        $flags[$n] = (in_array(strtolower(ini_get($v)), $neg) ? 'Off' : 'On');
}
$flags['Config file'] = get_cfg_var('cfg_file_path');
if (empty($flags['Config file']))
{
        $flags['Config file'] = '-';
}
$cli = (php_sapi_name() == 'cli');
$eol = "\n";

$gle = get_loaded_extensions();
$rows = array();
$le = '';
$wide = 4;
$j = count($gle);
$pad = $wide - $j % $wide;
$len = max(array_map('strlen', $gle));
$func = create_function('$a', 'return str_pad($a, ' . intval($len) . ');');
$gle = array_map($func, $gle);
for($i = 0; $i < $j; $i += $wide)
{
        $le .= '   ' . implode('   ', array_slice($gle, $i, $wide)) . $eol;
}

$ec = array(
        'E_STRICT' => 2048, 'E_ALL' => 2047, 'E_USER_NOTICE' => 1024,
        'E_USER_WARNING' => 512, 'E_USER_ERROR' => 256, 'E_COMPILE_WARNING' => 128,
        'E_COMPILE_ERROR' => 64, 'E_CORE_WARNING' => 32, 'E_CORE_ERROR' => 16,
        'E_NOTICE' => 8, 'E_PARSE' => 4, 'E_WARNING' => 2, 'E_ERROR' => 1,
);

$e = array();
$t = $er;
foreach ($ec as $n => $v)
{
        if (($t & $v) == $v)
        {
                $e[] = $n;
                $t ^= $v;
        }
}
if (ceil(count($ec) / 2) + 1 < count($e))
{
        $e2 = array();
        foreach ($ec as $n => $v)
        {
                if (!in_array($n, $e) and $n != 'E_ALL')
                {
                        $e2[] = $n;
                }
        }
        $er = $er . ' ((E_ALL | E_STRICT) ^ ' . implode(' ^ ', $e2) . '))';
}
else
{
        $er = $er . ' (' . implode(' | ', $e) . ')';
}

if (!$cli)
{
        echo '<html><head><title>quick info</title></head><body><pre>', $eol;
}

echo 'PHP Version: ', $ve, $eol;
echo 'PHP OS: ', $os, $eol;
echo 'Error Reporting: ', $er, $eol;
foreach ($flags as $n => $v)
{
        echo $n, ': ', $v, $eol;
}
echo 'Loaded Extensions:', $eol, $le, $eol;

if (!$cli)
{
        echo '</pre></body></html>', $eol;
}

?>
Last edited by Zoxive on Wed Sep 26, 2007 1:59 pm, edited 1 time in total.
User avatar
DogBot
Forum Newbie
Posts: 5
Joined: Tue Sep 25, 2007 9:59 am

Post by DogBot »

User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Post by Zoxive »

DogBot wrote:Zoxive, Take a look

http://www.arrowdata.com/foo.php
Display_Errors is off. Either look in usr/local/Zend/etc/php.ini, and set it on.

Code: Select all

display_errors = On
Or in your .htaccess put

Code: Select all

php_value display_errors on
OR if you just want it temporarily, on the top of the page you want to see the bugs put..

Code: Select all

ini_set('display_errors',1);
User avatar
DogBot
Forum Newbie
Posts: 5
Joined: Tue Sep 25, 2007 9:59 am

Post by DogBot »

I hate posting GOBS of code for other people to wade through, but I am just SO green

I am simply trying to figure out why this PayPal IPN script I got from someone does not work. The page just dies without giving any output!

I have added the variables at the top for testing purposes. I am not asking that someone debug this code, I would not be so brazen as to ask for others to do my work. I simply put the whole thing here so you can see what I have and perhaps help me figure out why the debugger is not working

Code: Select all

<?php


error_reporting(E_ALL);
ini_set('display_errors',1);


$invoice="00465";
$receiver_email="alex@asdf.net";
$item_name="item name";
$item_number="0003";
$quantity="5";
$payment_status="COMPLETED";
$pending_reason="PEND_RSN";
$payment_date="11/22/2007";
$payment_gross="54.00";
$payment_fee="1.25";
$txn_id="txn_id";
$txn_type="txn_type";
$first_name="FIRSTNAME";
$last_name="LASTNAME"
$address_street="123 MAIN STREET";
$address_city="NEYYORK";
$address_state="MAIN";
$address_zip="12345";
$address_country="US";
$address_status="GOOD";
$payer_email="alex@asdf.net";
$payer_status="GOOD";
$payment_type=" ";
$notify_version="1.5";
$verify_sign="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

//------------------------------------------------------------------
// Open log file (in append mode) and write the current time into it.
// Open the DB Connection. Open the actual database.
//-------------------------------------------------------------------

$log = fopen("log.txt", "a");
fwrite($log, "\n\nipn - " . gmstrftime ("%b %d %Y %H:%M:%S", time()) . "\n");
$db = mysql_connect("localhost", "XXXXXXXXX", "XXXXXXXXXXXX");
mysql_select_db("XXXXXXXXXXX",$db);


// Create a reply to validate the PayPal post. (Standard PayPal Code)
//This bit of code first creates a new array ($postvars) containing all of the values posted from PayPal.
//Then it begins a reply message ($req), with 'cmd=_notify-validate'
//Using a 'for' loop, it adds a list of posted vars in the format 'variable=value .

//------------------------------------------------
// Read post from PayPal system and create reply
// starting with: 'cmd=_notify-validate'...
// then repeating all values sent - VALIDATION.
//------------------------------------------------
$postvars = array();
while (list ($key, $value) = each ($HTTP_POST_VARS)) {
$postvars[] = $key;
}
$req = 'cmd=_notify-validate';
for ($var = 0; $var < count ($postvars); $var++) {
$postvar_key = $postvars[$var];
$postvar_value = $$postvars[$var];
$req .= "&" . $postvar_key . "=" . urlencode ($postvar_value);
}

//INFO: Note the values are urlencoded - this is the format in which data is transmitted in a post from a web page.

//The function 'urlencode':
//   "Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs" (from the PHP manual).

//This is basically a method of transmitting an 8-bit character set in just 7-bits.


// Create an HTTP header for the reply message, open a connection...

//--------------------------------------------
// Create message to post back to PayPal...
// Open a socket to the PayPal server...
//--------------------------------------------
//$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
//$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
//$header .= "Content-Length: " . strlen ($req) . "\r\n\r\n";
//$fp = fsockopen ("www.sandbox.paypal.com", 80, $errno, $errstr, 30);

//============
// Write the transaction details to the log file.
//The log file is useful for debugging problems. You'll ideally never lose any details, and if the database is 
//down for any reason, you need a backup..

//---------------------------------------------
$somecontent = "Add this to the file\n";
fwrite($log, "Vals: ".$invoice." ".$receiver_email." ".$item_name." ". $item_number." ". $quantity." ". $payment_status." ". $pending_reason." ".$payment_date. " ". $payment_gross." ". $payment_fee." ". $txn_id." ". $txn_type." ". $first_name." ". $last_name." ". $address_street." ". $address_city." ". $address_state . " ".$address_zip." ". $address_country." ". $address_status." ". $payer_email. " ". $payer_status." ". $payment_type." ". $notify_version." ". $verify_sign. "\ n");

//==============

//Check Connection...
//The variables $errstr and $errno are system variables which report details on the last error.

//----------------------------------------------------------------------
// Check HTTP connection made to PayPal OK, If not, print an error msg
//----------------------------------------------------------------------
if (!$fp) {
	echo "$errstr ($errno)";
	fwrite($log, "Failed to open HTTP connection!\n");
	$res = "FAILED";
}

//Final Verification
//At last, the string of posted variables ($req) is sent to PayPal's server. When it receives it - the server gives a 'VERIFIED' response if the transaction was real and successful.

//--------------------------------------------------------
// If connected OK, write the posted values back, then...
//--------------------------------------------------------
else {
	echo "Connected to paypal\n";
	fwrite($log, "SUCCESFULLY Opened HTTP connection!\n");
	fputs ($fp, $header . $req);
//-------------------------------------------
// ...read the results of the verification...
// If VERIFIED = continue to process the TX...
//-------------------------------------------
	while (!feof($fp)) {
		$res = fgets ($fp, 1024);
		if (strcmp ($res, "VERIFIED") == 0) {

//If payment is complete, get the password from the database.
//If the payment status is 'Completed'... The payment wasn't by e-check. The transaction's complete.

//Using the 'while' construct to get the data into a local variable is just a convenience... We know that only 1 row will come back from the query.

//----------------------------------------------------------------------
// If the payment_status=Completed... Get the password for the product
// from the DB and email it to the customer.
//----------------------------------------------------------------------
			if (strcmp ($payment_status, "Completed") == 0) {
				//$qry = "SELECT password FROM products WHERE pid = \"$item_number\" ";
				//$result = mysql_query($qry,$db);
//----------------------------------------------------------------------
// Create message. Send the email
// The message is created in the variable '$message' then sent using the PHP 'mail' function.
// Note the sender and reply-to info goes at the end. 
//----------------------------------------------------------------------
				//while ($myrow = mysql_fetch_row($result)) { $passwd = $myrow[0]; }
 				$message .= "Dear Customer,\n Thankyou for your order.\n\nThe password f or the item you ordered is: row[0]\n\nIf you have any problems, please contact us: \n\nsales\@yourdomain.com";
				mail($payer_email, "Your Book Password...", $message, "From: ipn@yourdomain.com\nReply-To: sales@yourdomain.com");
			}

//Handle Incomplete Transactions
//Inform the customer, and also inform yourself that something needs doing.

//----------------------------------------------------------------------
// If the payment_status is NOT Completed... You'll have to send the
// password later, by hand, when the funds clear...
//----------------------------------------------------------------------
		else {
		$message .= "Dear Customer,\n Thankyou for your order.\n\nThe password for the item you ordered will be sent to you when the funds have cleared.\n\nThankyou \n\nsales\@yourdomain.com";
		mail($payer_email, "Your Book Password...", $message, "From: ipn@yourdomain.com\nReply-To: sales@yourdomain.com");
		mail($receiver_email, "Incomplete PayPal TX...", "An incomplete transaction requires your attention.");
		}
//Deal with 'Unverified' transactions
//If, for example, the transaction you just processed didn't originate with PayPal, but was an attempted hack - it would cause this error to occur. An invalid transaction needs human intervention.

//----------------------------------------------------------------
// ..If UNVerified - It's 'Suspicious' and needs investigating!
// Send an email to yourself so you investigate it.
//----------------------------------------------------------------
		else {
		mail($payer_email, "An Error Occurred...", "Dear Customer,\n an error occurred while PayPal was processing your order. It will be investigated by a human at the earliest opportunity.\n\nWe apologise for any inconvenience.", "From: ipn@yourdomain.com\nReply-To: sales@yourdomain.com");
		mail($receiver_email, "Invalid PayPal TX...", "An invalid transaction requires your attention.");
		}
	}
}

//Insert Details Into DB
//The '\"' is placed around each of the variable to ensure that they appear in double quotes in the query string. This ensures that whatever they contain, they'll get inserted.

//--------------------------------------
// Insert Transaction details into DB.
//--------------------------------------
$qry = "INSERT into sales (
invoice, receiver_email, item_name, item_number, quantity, payment_status, pendi ng_reason, payment_date, payment_gross, payment_fee, txn_id, txn_type, first_nam e, last_name, address_street, address_city, address_state, address_zip, address_ country, address_status, payer_email, payer_status, payment_type, notify_version , verify_sign )
VALUES
( \"$invoice\", \"$receiver_email\", \"$item_name\", \"$item_number\", \"$quanti ty\", \"$payment_status\", \"$pending_reason\", \"$payment_date\", \"$payment_gr oss\", \"$payment_fee\", \"$txn_id\", \"$txn_type\", \"$first_name\", \"$last_na me\", \"$address_street\", \"$address_city\", \"$address_state\", \"$address_zip \", \"$address_country\", \"$address_status\", \"$payer_email\", \"$payer_status \", \"$payment_type\", \"$notify_version\", \"$verify_sign\" ) ";

$result = mysql_query($qry,$db);

// Close up.
//-------------------------------------------
// Close PayPal Connection, Log File and DB.
//-------------------------------------------
fclose ($fp);
fclose ($log);
mysql_close($db);
include "pypl-transc-log.txt";
?>
Thanks
MicahCarrick
Forum Newbie
Posts: 23
Joined: Sat Apr 09, 2005 5:40 pm

Post by MicahCarrick »

When using IPN, you can't debug in the browser because nothing happens in the browser. That's the way IPN works. In my script: PHP Paypal IPN Integration Class I use a text file for debugging the IPN portion of the code.

The IPN works like this:
Paypal's server contacts your IPN script (no browser... think back end, behind the scenes, asynchronous from the code that submitted the payment). So if your script craps out or there is an error, it will only show up in your php error log (depending on if you have that turned on). You can either test for error/problem conditions and write to a text file or the error log by using log_error() or something.

The trick is, the text file you're writing to will need write access for the script execution user.
Post Reply