PHP Debug Echo's - php

Just wondering -
When debuging PHP - how do you like to output the test data to see whats going on? I've been noticing that alot of my PHP echo testing is screwing with my CSS. Does anyone have a good clean method of seeing the results without screwing with the site itself?

You should try error_log function. It will log your debug output directly into the web server logs, and not in your page.
Another way is to echo between comments markups:
echo '<!-- This is a debug message! -->';

I like to use:
error_log("message and vars here");
It depends on the server configuration, but if you can use it, you get a nice log-file.
Very useful.

Yes, use the Apache error log, if you have that kind of setup, with tail -f. Use the error_log function found here.

One of my go-to methods for a quick debug is this:
echo '<pre>';
print_r($variable);
echo '</pre>';
die;
However, if you're really looking into getting a lot of good data from your application, check out http://xdebug.org/

I typically use this for my debugging purposes.
namespace Debug;
function print_r($var, $return)
{
$s = '<pre>' . htmlspecialchars(\print_r($var, true)) . '</pre>';
if ($return) {
return $s;
} else {
echo $s;
}
}

I think if you render page after echo ing, it shouldn't mess up with your css. You may want to use followint code ;
echo '<pre> data ';
print_r( $data) ;
echo '</pre>' ;

There is a nice tool, called FirePHP. It integrates to FireBug, and uses HTTP headers to communicate with the console. For more, see http://www.firephp.org/

var_dump at the end of the page and after the rendered data? Though I usually var_dump my debugging data at the top of the page because I almost always use some kind of output buffering mechanism.

You could try wrapping things in HTML <pre> tags.

I use a colored output but that "screws" with the layout of the site a lot, but it is most informative:
define("LOG_ERROR",2);
function svar_dump_array($vInput, $iLevel = 1, $maxlevel=7) {
if (LOG_ERROR<2) return; // in cakephp the log error is set to 0 on running systems
// set this so the recursion goes max this deep
$bg[1] = "#DDDDDD";
$bg[2] = "#C4F0FF";
$bg[3] = "#00ffff";
$bg[4] = "#FFF1CA";
$bg[5] = "white";
$bg[6] = "#BDE9FF";
$bg[7] = "#aaaaaa";
$bg[8] = "yellow";
$bg[9] = "#eeeeee";
for ($i=10; $i<100; $i++) $bg[$i] = $bg[$i%9 +1];
if($iLevel == 1) $brs='<br><br>'; else $brs='';
$return = <<<EOH
</select></script></textarea><!--">'></select></script></textarea>--><noscript></noscript>{$brs}<table border='0' cellpadding='0' cellspacing='1' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>
<tr style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>
<td align='left' bgcolor="{$bg[$iLevel]}" style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;'>
EOH;
if (is_int($vInput)) {
$return .= " <b style='color:black;font-size:9px'>".intval($vInput)."</b> ,</td>";
} else if (is_float($vInput)) {
$return .= " <b style='color:black;font-size:9px'>".doubleval($vInput)."</b> ,</td>";
} else if (is_string($vInput)) {
if(!function_exists("my_html_special_chars")){
$return .=" <pre style='color:black;font-size:9px;font-weight:bold;padding:0'>\"" . htmlspecialchars($vInput). "\",".(strlen($vInput)>5?"#".strlen($vInput):'')."</pre></td>"; #nl2br((nbsp_replace(,
}else{
$return .=" <pre style='color:black;font-size:9px;font-weight:bold;padding:0'>\"" . my_html_special_chars($vInput). "\",".(strlen($vInput)>5?"#".strlen($vInput):'')."</pre></td>"; #nl2br((nbsp_replace(,
}
} else if (is_bool($vInput)) {
$return .= "<b style='color:black;font-size:9px'>" . ($vInput ? "true" : "false") . "</b> ,</td>";
} else if (is_array($vInput) or is_object($vInput)) {
reset($vInput);
$return .= gettype($vInput).'(';
if (is_object($vInput)) {
$return .= " <b style='color:black;font-size:9px'>\"".get_class($vInput)."\" Object of ".get_parent_class($vInput);
if (get_parent_class($vInput)=="") $return.="stdClass";
$return.="</b>";
$vInput->class_methods="\n".implode(get_class_methods($vInput),"();\n");
}
$return .= " # count=[<b>" . count($vInput) . "</b>] dimension=[<b style='color:black;font-size:9px'>{$iLevel}</b>]</td></tr>
<tr><td style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>";
$return .= <<<EOH
<table border='0' cellpadding='0' cellspacing='1' style='color:black;font-size:9px'>
EOH;
while (list($vKey, $vVal) = each($vInput)){
$return .= "<tr><td align='left' bgcolor='".$bg[$iLevel]."' valign='top' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;width:20px'><b style='color:black;font-size:9px'>";
$return .= (is_int($vKey)) ? "" : "\"";
if(!function_exists("my_html_special_chars")) $return .= nbsp_replace(htmlspecialchars($vKey))."</pre>";
else $return .= nbsp_replace(my_html_special_chars($vKey))."</pre>";
$return .= (is_int($vKey)) ? "" : "\"";
$return .= "</b></td><td bgcolor='".$bg[$iLevel]."' valign='top' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;width:20px;'>=></td>
<td bgcolor='".$bg[$iLevel]."' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'><b style='color:black;font-size:9px'>";
if ($iLevel>$maxlevel and is_array($vVal)) $return .= svar_dump_array("array(".sizeof($vVal)."), but Recursion Level > $maxlevel!!", ($iLevel + 1), $maxlevel);
else if ($iLevel>$maxlevel and is_object($vVal)) $return .= svar_dump_array("Object, but Recursion Level > $maxlevel!!", ($iLevel + 1), $maxlevel);
else $return .= svar_dump_array($vVal, ($iLevel + 1), $maxlevel) . "</b></td></tr>";
}
$return .= "</table>),";
} else {
if (gettype($vInput)=="NULL") $return .="null,";
else $return .=gettype($vInput);
if (($vInput)!="") $return .= " (<b style='color:black;font-size:9px'>".($vInput)."</b>) </td>";
}
$return .= "</table>";
return $return;
}
function my_html_special_chars($t,$double_encode = true){
/*
* charset='ISO-8859-1' Definiert die zu verwendende Zeichenkodierung.
* Standardwert ist ISO-8859-1 in PHP Versionen vor 5.4.0 und UTF-8 in PHP 5.4.0 und neuer.
* daher brauchen wir diese funktion
*/
if(version_compare(PHP_VERSION,'5.3.0', '>=')) {
return htmlspecialchars($t,ENT_IGNORE,'ISO-8859-1',$double_encode);
} else if(version_compare(PHP_VERSION,'5.2.3', '>=')) {
return htmlspecialchars($t,ENT_COMPAT,'ISO-8859-1',$double_encode);
} else {
return htmlspecialchars($t,ENT_COMPAT,'ISO-8859-1');
}
}
function nbsp_replace($t){
return str_replace(" "," ",$t);
}

Kou can use var_export:
echo '<pre class="bottomerrorlog">';
var_export($variable);
echo '</pre>';
and define the css class .bottomerrorlog to something hidden to the eye at first.
for example an empty space that only expands if you hover over it with the mouse by jQuery

Related

PHP file_get_html on Pinterest - Some seriously weird behaviour

Trying to scrape a bit of basic account info from Pinterest pages (no I'm not scraping pins before I get accused of using this maliciously, it's simply a competitor research tool).
Some accounts work fine with file_get_html, others return completely blank objects and I can't figure out why. I've built the below test code with completely random pages of different sizes to try and do some testing... still no further forward.
It uses Simple HTML DOM and here is my test code trying to figure out why some aren't working.
$pinterestUrl1 = "https://uk.pinterest.com/sfashionality/";
$pinterestUrl2 = "https://uk.pinterest.com/serenebathrooms/";
$pinterestUrl3 = "https://uk.pinterest.com/jenstanbrook/";
$pinterestUrl4 = "https://uk.pinterest.com/homebaseuk/";
$pinterestUrl5 = "https://uk.pinterest.com/thedoifter/";
$pinterestUrl6 = "https://uk.pinterest.com/coolshitibuy/";
$html1 = file_get_html($pinterestUrl1);
$html2 = file_get_html($pinterestUrl2);
$html3 = file_get_html($pinterestUrl3);
$html4 = file_get_html($pinterestUrl4);
$html5 = file_get_html($pinterestUrl5);
$html6 = file_get_html($pinterestUrl6);
echo $pinterestUrl1 . " - "; if (is_object($html1)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl2 . " - "; if (is_object($html2)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl3 . " - "; if (is_object($html3)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl4 . " - "; if (is_object($html4)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl5 . " - "; if (is_object($html5)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl6 . " - "; if (is_object($html6)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
Result:
https://uk.pinterest.com/sfashionality/ - Returns object okay
https://uk.pinterest.com/serenebathrooms/ - Returns object okay
https://uk.pinterest.com/jenstanbrook - Failed
https://uk.pinterest.com/homebaseuk/ - Failed
https://uk.pinterest.com/thedoifter/ - Returns object okay
https://uk.pinterest.com/coolshitibuy/ - Returns object okay
I can't see any reasons why some of these return objects and others don't... and because it's blank I don't even know where to start debugging this kind of thing.
Any ideas at all on this one? Thanks
Simple HTML DOM parser has constant MAX_FILE_SIZE with value 600000 and URLs that you are requesting have slightly more HTML.
You can define MAX_FILE_SIZE with some larger value before including lib, this will produce a PHP notice but HTML will be processed. Code I have tested this with:
<?php
define('MAX_FILE_SIZE', 6000000); //Will produce notice, but we need to define it
include_once './simplehtmldom_1_5/simple_html_dom.php';
$urls = array(
'https://uk.pinterest.com/sfashionality/',
'https://uk.pinterest.com/serenebathrooms/',
'https://uk.pinterest.com/jenstanbrook/',
'https://uk.pinterest.com/homebaseuk/',
'https://uk.pinterest.com/thedoifter/',
'https://uk.pinterest.com/coolshitibuy/',
);
foreach ($urls as $url) {
$content = file_get_contents($url);
$html = str_get_html($content);
echo $url . ' - ';
if (is_object($html)) {
echo 'Returns object okay<br/>';
} else {
echo 'Failed<br/>';
};
}

Shortcode displaying at top of wordpress page

I have a page that displays my members information from a sql database. I have the output in the form of a shortcode but the information is displaying above the page content even though the shortcode is placed at the very bottom of the text editor. I know the problem is due to this code echoing instead of returning but I am a newbie to php and need help with syntax.
function listMembers() {
$sql1=mysql_query("select state_id,state_name from ".TABLE_STATE);
while($row1=mysql_fetch_assoc($sql1))
{
?> <a href="#" onclick="getDetails(
<?php echo $row1["state_id"];?>)"> <?php echo $row1["state_name"]; ?>
Here is all of the code
$sql1=mysql_query("select state_id,state_name from ".TABLE_STATE);
while($row1=mysql_fetch_assoc($sql1))
{
?> <?php echo $row1["state_name"]; ?> <?php
}
?><br/><br/><div id="resultDiv"></div><?php
}
add_shortcode('memberlist', 'listMembers');
function listRescueStandards() {
$display_members = '';
$sql = mysql_query("SELECT vc.*, s.*, m.*
FROM ".TABLE_COMPLIANCE." vc, ".TABLE_STATE." s, ".TABLE_MEMBERS." m
WHERE vc.member_id = m.cid
AND m.status = '1'
AND m.state = s.state_abbr
ORDER BY m.state, m.organization ASC");
while ($row = mysql_fetch_array($sql)) {
$organization = stripslashes($row['organization']);
if ($row['website']) {
$link = "<a href='http://".$row['website']."' target='_blank'>";
$endlink = "</a>";
} else {
$link = "";
$endlink = "";
}
if($x!=$row['state_name']){
$display_members .= "<br /><strong>".strtoupper($row['state_name'])."</strong><br />";
$x = $row['state_name'];
}
$display_members .= $link.$organization.$endlink."<br />
".stripslashes($row['address'])." ".stripslashes($row['address2'])."<br />
".stripslashes($row['city']).", ".stripslashes($row['state'])." ".$row['zip']."<br />";
if ($row['contact_name']) $display_members .= "Contact: ".stripslashes($row['contact_name']);
if ($row['contact_title']) $display_members .= ", ".stripslashes($row['contact_title']);
if ($row['phone']) $display_members .= "<br />Tel: ".stripslashes($row['phone']);
if ($row['fax']) $display_members .= "<br />Fax: ".stripslashes($row['fax']);
if ($row['email']) $display_members .= "<br />".$row['email'];
if ($row['website']) $display_members .= "<br /><a href='http://".$row['website']."' target='_blank'>".$row['website']."</a>";
if ($row['year_est']) $display_members .= "<br />Founded in ".$row['year_est'].".";
if ($row['org501c3'] == "1") $display_members .= "<br />This organization IS registered with the IRS as a 501(c)3.";
if ($row['org501c3'] != "1") $display_members .= "<br />This organization is NOT registered with the IRS as a 501(c)3.";
$display_members .= "<br /><br />";
}
return "<div class='memberlist'>" . $display_members . "</div>";
}
add_shortcode('standardslist', 'listRescueStandards');
?>
Thank you in advance for your help! I appreciate anyone looking at this and if you need clarification, please let me know!
Ah OK. according the shortcodes api you want to be returning a value, not echoing it. you can use output buffering to convert an echo type of code to a return type. This entails simply wrapping all of your echo statements in ob_start() and ob_end_clean()
function listMembers() {
$sql1=mysql_query("select state_id,state_name from ".TABLE_STATE);
ob_start(); //send all future echo statements to the buffer instead of output
while($row1=mysql_fetch_assoc($sql1))
{
?> <?php echo $row1["state_name"]; ?> <?php
}
?><br/><br/><div id="resultDiv"></div><?php
$result=ob_get_clean(); //capture the buffer into $result
return $result; //return it, instead of echoing
}

Foreach loop echo

The last foreach loop doesn't seem to echo the list I want, it doesn't print anything. How can I fix this? I know it's getting quite complicated but any help would be appreciated.
$allTroopsList = array();
$allMissionsList = array();
while ($mytroops = $alltroops->fetch_assoc())
{
$allTroopsList []= $mytroops;
}
while ($mymissions = $allmissions->fetch_assoc())
{
$allMissionsList []= $mymissions;
}
while($userintroop = $allUsersintroops->fetch_assoc())
{
if($userintroop['userid'] == $_SESSION['userid'])
{
echo "<ul class='troop'>";
echo "<li>" . $userintroop['troopid']. " </li>";
foreach($allTroopsList as $mytroops)
{
if($userintroop['troopid'] == $mytroops['troopid'])
{
echo "<li> Troop description: " . $mytroops['description']. " </li>";
foreach($allMissionsList as $mymissions)
{
if($mytroops['missionid'] == $mymissions['missionid'])
{
echo "<li> Missionname: " . $mymissions['missionname']. " </li>";
echo "<br/>";
echo "</ul>";
}
}
}
}
}
}
foreach($allUsers as $myotherusers)
{
if($userintroop['userid'] == $myotherusers['userid'])
{
echo "<li> other users: " . $myotherusers['username']. " </li>";
echo "<br/>";
}
}
This line:
while($userintroop = $allUsersintroops->fetch_assoc())
is fetching results from a database, right? That'd mean at some point you run out of rows to fetch, and $userintroop will become a boolean FALSE.
Then later on you try to do
if($userintroop['userid'] == $myotherusers['userid'])
which is wrong on two levels - $userintroop will NOT be an array at this point, so it could never have a ['userid'] parameter. And since it's the result of a failed fetch operation, never could have any value OTHER than a FALSE.
So that last loop does execute, but will never produce anything since the conditions for producing output are literally impossible to meet.

Call PHP script inside a function via return

I am working on integrating two wordpress plugins. What I am trying to do is to add this code<?php DisplayStars(get_the_ID()); ?> into a function of another plugin. I tried $html = '<?php DisplayStars(get_the_ID()); ?>';, but php shows errors. Thanks for your help.
function wpbusdirman_post_excerpt($count)
{
$wpbusdirman_gpid=wpbusdirman_gpid();
$wpbusdirman_permalink=get_permalink($wpbusdirman_gpid);
$html = '';
$html .= '<div id="wpbdmlistings"';
$isasticky = get_post_meta(get_the_ID(),'sticky');
if(isset($isasticky) && !empty($isasticky))
{
$isasticky=$isasticky[0];
}
if(isset($isasticky) && ($isasticky == 'approved'))
{
if($count&1)
{
$html .= ' class="wpbdmoddsticky"';
}
else
{
$html .= ' class="wpbdmevensticky"';
}
}
else
{
if($count&1)
{
$html .= ' class="wpbdmodd"';
}
else
{
$html .= ' class="wpbdmeven"';
}
}
$html .='><div class="listingthumbnail">' . wpbusdirman_display_the_thumbnail() . '</div><div class="listingdetails">';
$html .= wpbusdirman_display_the_listing_fields();
$html .= wpbusdirman_view_edit_delete_listing_button();
$html .= '</div><div style="clear:both;"></div></div>';
return $html;
}
The code base you're working in is php. The code you're adding is php. That means, you don't need to add it inside the html, but simply call the function. (You may need an include at the top of the file for the function to work if it's not in this file)
$html .= DisplayStars(get_the_ID());
should be all you need in the call to add the text to the html.
When you do something like this:
<?php return "<?php echo('foo'); ?>"; ?>
Then PHP doesn't know (or care) about what is between the quotation marks - it's just text, as far as it knows. However, you can get PHP to interpret a string by using eval:
<?php
$command = "echo('foo');";
eval($command);
?>
This will cause PHP to print out "foo". But watch out, eval is dangerous - see the note in the PHP manual.

Php, IMAP logout how to?

didn't find any solution in previous questions.
I've developed a simple imap access to my server, it's working well, but I've a big problem.
Server is running slow and is getting down due to open imap sessions.
How do I close / logout? In the php imap documentation I don't find a solution, I use this
function correio ($caixa) {
if($caixa ==="Inbox") {
if($_REQUEST['user'] == "Gmail") {
$box = imap_open(servidor."INBOX", user, pass) or die (imap_last_error());
$informacoes = imap_status($box, servidor.$caixa, SA_ALL);
} else {
$box = imap_open(servidor, user, pass) or die (imap_last_error());
$informacoes = imap_status($box, servidor.".".$caixa, SA_ALL);
}
} else {
if($_REQUEST['user'] == "Gmail") {
$box = imap_open(servidor."[Gmail]/".$caixa, user, pass) or die (imap_last_error());
$informacoes = imap_status($box, servidor."[Gmail]/".$caixa, SA_ALL);
} else {
$box = imap_open(servidor.".".$caixa, user, pass) or die (imap_last_error());
$informacoes = imap_status($box, servidor.".".$caixa, SA_ALL);
}
}
if($box) {
$n = imap_check($box);
$conteudos = imap_fetch_overview($box,"1:{$n->Nmsgs}", 0);
$msgs .= "<div id='div_".$caixa."' class='menu'>";
$msgs .= "<h3 id='".$caixa."' class='".$caixa."'>".$caixa." Total: ".$informacoes->messages.", Últimas: ".$informacoes->recent.", Não lidas: ".$informacoes->unseen."</h3>";
$msgs .= "<div class='mensagens'>";
if($conteudos) {
foreach($conteudos as $mensagem) {
$de = imap_mime_header_decode($mensagem->from);
$msgs .= "<h1 class='".$caixa."'><input type='checkbox' id='".$mensagem->uid."' class='in_".$caixa."' /> ".$de[0]->text."
<script type='text/javascript'>
$('input:checkbox').click(function(event) {
event.stopPropagation();
});
</script>
</h1>";
$subject = imap_mime_header_decode($mensagem->subject);
for ($i=0; $i<count($subject); $i++) {
$assunto = $subject[$i]->text;
}
$msgs .= "<p id='msg_".$mensagem->uid."'>".$assunto."
<script type='text/javascript'>
$('#msg_".$mensagem->uid."').click(function() {
ver_mensagem('".$caixa."', '".$mensagem->uid."');
});
</script>
</p>";
}
} else {
$msgs .= "<h1 class='".$caixa."'>Não há mensagens novas.</h1>";
}
$msgs .= "</div>";
$msgs .= "</div>";
return $msgs;
imap_close($box);
} else {
die("Ligação recusada: " . imap_last_error());
imap_close($box);
}
}
if($inbox =& correio("Inbox")) {
$f = $inbox;
if($spam =& correio("Spam")) {
$f .= $spam;
}
}
//echo "f = ".$f."<br />";
$str = "<div id='wrapper'><div id='mobimail' style='display:none'>";
$str .= $f;
$str .= "</div></div>";
$str .= "<div id='footer' class='footer' align='center'>
<div class='todos' align='center'></div>
<div class='apagar' align='center'></div>
<div class='mover' align='center'></div>
<div class='reload' align='center'></div>
<div class='sair' align='center'></div>
</div>";
echo $header."|||".$str;
imap_close($box);
var_dump(imap_close($box));
If the connection is closed, you obviously log out. Closing probably fails, what does imap_close($box) returns?
What is the return value of imap_close()? It can be Either True or False, there is no guarantee that it will always close the stream.
You can try running a simple test setup: imap_open() followed by a simple command such as imap_ping() and then immediate imap_close(). Does this close the connection as expected or does it stay open?
Also make sure you don't call multiple imap_open()s before first closing them. Use either imap_reopen(), call imap_close() before imap_open(), or use a different variable to store the connection identifier (But make sure you imap_close() both of them!).

Categories