PHP Not Echoing in the right place - php

I'm running some PHP code on my WordPress site and when the PHP runs to echo out some information it doesn't echo it in the right place. An abbreviated version of the code is:
<div class="description cms">
<div id="home_left_middle">
<h2>Search By Category</h2>
[xyz-ips snippet="Category-List"]
</div>
</div>
The shortcode is for the plugin XYZ PHP Code which is basically just a way to use 'includes' in WordPress posts. I've set up some customization in the WP database but it's just basic database calls. All the information is returned successfully from the database so there's no issue there. The PHP code I'm using there is:
$sql = "SELECT * FROM wp_categories_table";
$result = $wpdb->get_results($sql);
echo "<ul class='category_list'>";
foreach( $result as $results ) {
$category = $results->category;
$number = $results->number_of;
$category_html = htmlentities($category);
echo "<li><a href='?search-class=DB_CustomSearch_Widget-db_customsearch_widget&widget_number=preset-default&cs-all-0=&cs-post_cat-1=".$category_html."&search=Search'>".$category." (".$number.")</a></li>";
}
echo "</ul>";
What happens is that when the PHP code runs, it echoes it right after the div.description (and before the div#home_left_middle) and just the H2 remains in the home_left_middle div. That's not where the code is being run.
The curious thing about this is that I was using the exact same code on another site (I duplicated this site because we were just changing servers, exact same content though) and it works fine on the other server. This is a VPS so I'm wondering if there is some sort of PHP extension that I haven't installed on the server correctly that may be causing this? I know that's a bit of a reach but I'm confused as to why the exact same code, in the same version of WordPress and using the same theme and CSS files would cause different results on two different sites. The only difference I see is possibly the server unless I'm overlooking some small error?
EDIT
For those asking about an output buffering issue, I've recently copied the php.ini file over from the last server and the output buffering code looks like this:
; output_buffering
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
So it appears to be commented out.

Like maioran84 suggested in the comments, this is probably some issue with the output buffers. I would suggest you copy over the php.ini file from the working site to the non-working site server.
Looking inside the PHP configuration file, there are a few settings that may be causing the output to be displayed before wordpress is ready for it.
; Implicit flush tells PHP to tell the output layer to flush itself
; automatically after every output block. This is equivalent to calling the
; PHP function flush() after each and every call to print() or echo() and each
; and every HTML block. Turning this option on has serious performance
; implications and is generally recommended for debugging purposes only.
; http://php.net/implicit-flush
; Note: This directive is hardcoded to On for the CLI SAPI
implicit_flush = Off
output_buffering = 4096
Looking at the WordPress documentation for add_shortcode(), the following block of text really stood out. You can easily change all of your echo statements to append the value to a string and then return the string as a whole.
Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results. This is similar to the way filter functions should behave, in that they should not produce expected side effects from the call, since you cannot control when and where they are called from.
https://codex.wordpress.org/Function_Reference/add_shortcode
Hopefully this will help you with this issue, but I have never heard of any error like this happening before.

I know this question is old and has been resolved, but I had the same issue and managed to resolve it differently, so I thought I'd share :)
I was using the same wordpress plugin you were, XYZ php code, and it was outputting above the div it was being called in. I switched to a different plugin called 'PHP Code for posts', which works exactly the same was as XYZ, expect with a slightly nicer code editor and it outputted exactly as expected.
It's odd because I normally use XYZ in my WP builds and its always worked fine, so all I can guess is there's a bad plugin interaction. Obviously there's a difference in the way the plugins work, but I'm not feeling intrepid enough today to figure out what ;).

Related

How to print to server console, not to browser or browser console [duplicate]

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');
or
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:
Output to a webpage (see dBug library for a nicer view of things).
Write to a log file
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.
Ie:
<div> some html code ....
some link to test
</div>
dump $tpl like this:
<pre><?php var_dump($tpl); ?></pre>
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.
error_reporting(E_ALL);
ini_set('display_errors', '1');
Good luck!
You can also write to a file like this:
$logFilePath = '../logs/debug.text';
ob_start();
// if you want to concatenate:
if (file_exists($logFilePath)) {
include($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());
fclose($logFile);
ob_end_flush();
Make sure the proper permissions are set so php can access and write to the file (775).
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
var_dump
You can use the php curl module to make calls to http://liveoutput.com/. 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 http://www.codeforest.net/debugging-php-in-browsers-javascript-console).
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:
<?php
echo '<script>console.log("debug log")</script>';
?>
You can use
<?php
{
AddLog("anypage.php","reason",ERR_ERROR);
}
?>
or if you want to print that statement in an log you can use
AddLog("anypage.php","string: ".$string,ERR_DEBUG_LOW);

flush functions are deleting my html temporarily

Notice: Yes I did ask this question once before but it got immediatly marked as a duplicate although the linked duplicate had almost nothing to do with my question.
I wrote a php script that is executing my application to download images from the web. And in order to show some kind of progress being made on my website I used flush to echo out some information for the User. Here is my code:
echo '<li class="list-group-item list-group-item-info">Starting to gather data!</li>';
ob_flush();
flush();
$url = $unsplash;
$cmd = $unsplash . ' - ' . $amount;
exec($cmd);
echo '<li class="list-group-item list-group-item-success">Gathering Data Completed</li>';
ob_end_flush();
The code I am using does work without any problem (besides this one) so there is no error there!
Unfortunately every kind of HTML content I write under my php script is being deleted for the duration of the script executing (which sometimes can take up to 5 minutes). But immediately after the script finished the Content beneath reappears. Another thing worth mentioning is, that when I open DevTools in Chrome (F12) during the scipt is being executed is shows nothing!
Am I doing something wrong ? I cant seem to figure it out...
Thank You
I'm not sure, exactly what you mean by "being deleted", but what you need to take into consideration is that output buffering can happen at multiple levels (PHP, Web Server, Client UA, etc..).
If the output from your script does not appear right away, it's likely that you have output_buffering enabled at a higher level (i.e. in your php.ini or other loaded configuration). Because output buffers cascade, they flush at each level. Check your phpinfo() and if you see a value other than 0 for output_buffering, then you need to edit the php.ini file showing in phpinfo() under Loaded Configuration (near the top) and change that value to 0 then restart your parent PHP process.
Another thing to consider is that some browsers won't render some HTML block-level elements like <div>, <ul>, etc... until they are closed. The content may have arrived at the client, but some browsers don't process the rendering of the content until the block level element is complete. So a better way to test that the output is being received on the client end without these variable nuances might be to send a text/plain Content-type header from your PHP to get the HTML rendering stuff out of the way. header('Content-type: text/plain'), if turning off the output_buffering in PHP still doesn't give you the desired result.

Expression engine showing garbage content while using PHP

Expressionengine is showing garbage value when I am using php for Json encode its showing this content {!-- ra:0000000019930c5000007efd6bf7e0f5 --}
here is my code :-
<?php
$entries = array();
{exp:channel:entries channel="sport" category="3536|1830|4102" site="default_site" limit="3" track_views="one" dynamic="no" status="open|featured" disable="categories|category_fields|pagination|member_data" terminate="yes"}
$entries[] = array('title' => '{title}');
{/exp:channel:entries}
header('Content-type: application/json');
echo json_encode($entries);
exit;
?>
If you see this kind of garbage value on the page that means the page has an error.
We mostly find this garbage value on PHP-enabled templates. So if we resolve the PHP errors the garbage will go.
Do not modify the ExpressionEngine core files. If you want to see the PHP errors on the page, turn on the debug mode.
If you remove the exit() function, you will get the output as you want.
The exit() function also exits the execution of ExpressionEngine code that's why you are getting the garbage value.
Even simpler - remove the exit().
As this answer explains, these are annotation tags used for debugging (so you can get a stack trace for nested templates I suppose) and they are parsed out late in the process. So if you exit() it doesn't work. Just make sure that the script ends with no unwanted output and you should be good. I had this problem (in EEv5) and this was the fix.
I've just had the same style of error codes appear, when moving an old EE 2.9.3 site to a Dev server and applying a test domain name.
There were some PHP Includes in the templates, which referenced the live site's server path. When I changed these... all fixed.
For example:
include("/home/sites/domainname.co.uk/public_html/swift/swift_required.php");
...changed to...
include("/home/domain/public_html/swift/swift_required.php");
Yeah ! finally I got the answer its so simple here is the solution :-
go to ExpressionEngine\system\EllisLab\ExpressionEngine\Library\Template\Annotation\Runtime.php
on line no. 65 comment the code return '{!-- ra:'.$key.' --}';

PHP eval code and store the result into a variable

I have continued my voyage into creating a extremely simple template engine.
Because I wanted to add logic to my template I eventually got back to the point that I allowed PHP tags into my code which I enabled by evalling the code.
Maybe not the best solution but when looking at the WordPress templates I noticed that the idea itself may not be that bad.
But now there still is one small problem left.
And that is that I want to translate the generated code.
But it has been evalled already. Hence parsed.
I thought of solving this problem by using ob_get_contents().
But this brought one more question and in case of errors it shows a white screen. (memory usage etc.)
Plus it still did not take away the problem of eval that it parsed the contents when evalled.
In short the class logic is:
Loading template files
Adding the contents
Compiling the template
Eval the code (but unfortunately also displaying the code)
Translate the code so I can translate the code parsed by a PHP script
I would love something like:
$code = eval('?>'.$tpl.'<?php');
$code = translate($code);
WriteCache($code);
SetDocumentHeader();
echo $code;
Would anyone know how to achieve this?
Thanks in advance!
$code = eval($tpl);
Check this out.

Why is javascript not able to use a javascript variable I declared in a php file?

Hey everybody, this issue has had me stumped for the last week or so, here's the situation:
I've got a site hosted using GoDaddy hosting. The three files used in this issue are index.html , milktruck.js , and xml_http_request.php all hosted in the same directory.
The index.html file makes reference to the milktruck.js file with the following code:
<script type="text/javascript" src="milktruck.js"></script>
The milktruck.js file automatically fires when the site is opened. The xml_http_request.php has not fired at this point.
On line 79 out of 2000 I'm passing the variable "simple" to a function within the milktruck.js file with:
placem('p2','pp2', simple, window['lla0_2'],window['lla1_2'],window['lla2_2']);
"simple" was never initialized within the milktruck.js file. Instead I've included the following line of code in the xml_http_request.php file:
echo "<script> var simple = 'string o text'; </script>";
At this point I have not made any reference whatsoever to the xml_http_request.php file within the milktruck.js file. I don't reference that file until line 661 of the milktruck.js file with the following line of code:
xmlhttp.open('GET',"xml_http_request.php?pid="+pid+"&unLoader=true", false);
Everything compiles (I'm assuming because my game runs) , however the placem function doesn't run properly because the string 'string o text' never shows up.
If I was to comment out the line of code within the php file initializing "simple" and include the following line of code just before I call the function placem, everything works fine and the text shows up:
var simple = 'string o text';
Where do you think the problem is here? Do I need to call the php file before I try using the "simple" variable in the javascript file? How would I do that? Or is there something wrong with my code?
So, we meet again!
Buried in the question comments is the link to the actual Javascript file. It's 2,200 lines, 73kb, and poorly formatted. It's also derived from a demo for the Google Earth API.
As noted in both the comments here and in previous questions, you may be suffering from a fundamental misunderstanding about how PHP works, and how PHP interacts with Javascript.
Let's take a look at lines 62-67 of milktruck.js:
//experiment with php and javascript interaction
//'<?php $simpleString = "i hope this works"; ?>'
//var simple = "<?php echo $simpleString; ?>";
The reason this never worked is because files with the .js extension are not processed by PHP without doing some bizarre configuration changes on your server. Being on shared hosting, you won't be able to do that. Instead, you can rename the file with the .php extension. This will allow PHP to process the file, and allow the commands you entered to actually work.
You will need to make one more change to the file. At the very top, the very very top, before anything else, you will need the following line:
<?php header('Content-Type: text/javascript'); ?>
This command will tell the browser that the file being returned is Javascript. This is needed because PHP normally outputs HTML, not Javascript. Some browsers will not recognize the script if it isn't identified as Javascript.
Now that we've got that out of the way...
Instead I've included the following line of code in the xml_http_request.php file: <a script tag>
This is very unlikely to work. If it does work, it's probably by accident. We're not dealing with a normal ajax library here. We're dealing with some wacky thing created by the Google Earth folks a very, very long time ago.
Except for one or two in that entire monolithic chunk of code, there are no ajax requests that actually process the result. This means that it's unlikely that the script tag could be processed. Further, the one or two that do process the result actually treat it as XML and return a document. It's very unlikely that the script tag is processed there either.
This is going to explain why the variable never shows up reliably in Javascript.
If you need to return executable code from your ajax calls, and do so reliably, you'll want to adopt a mature, well-tested Javascript library like jQuery. Don't worry, you can mix and match the existing code and jQuery if you really wanted to. There's an API call just to load additional scripts. If you just wanted to return data, that's what JSON is for. You can have PHP code emit JSON and have jQuery fetch it. That's a heck of a lot faster, easier, and more convenient than your current unfortunate mess.
Oh, and get Firebug or use Chrome / Safari's dev tools, they will save you a great deal of Javascript pain.
However...
I'm going to be very frank here. This is bad code. This is horrible code. It's poorly formatted, the commenting is a joke, and there are roughly one point seven billion global variables. The code scares me. It scares me deeply. I would be hesitant to touch it with a ten foot pole.
I would not wish maintenance of this code on my worst enemy, and here you are, trying to do something odd with it.
I heartily encourage you to hone your skills on a codebase that is less archaic and obtuse than this one before returning to this project. Save your sanity, get out while you still can!
perhaps init your values like this:
window.simple = 'blah blah blah'
then pass window.simple
You could try the debugger to see what is going on, eg. FireBug

Categories