<iframe> instead of include - php

I want to include multiple comments sections on one page using the Commentics php sript.
First I tried accomplishing this using include like so:
<div id="1">
<?php
include "comments_id1.php";
?>
</div>
<div id="2">
<?php
include "comments_id2.php";
?>
</div>
comments_id1.php:
<?php
session_start();
ob_start();
?>
[...]
<?php
$page_id = "1";
$reference = "Page One";
$path_to_comments_folder = "comments/";
define ('IN_COMMENTICS', 'true');
require $path_to_comments_folder . "includes/commentics.php";
?>
(comments_id2.php accordingly: $page_id = "2"; $reference = "Page Two")
Apparently (and it might be worth noting that I'm still pretty clueless when it comes to PHP), this doesn't work or at least leads to all kinds of troubles (e.g. "Warning: Cannot modify header information - headers already sent").
So the solution I came up with was using the <iframe> tag, like so:
<div id="1">
<iframe width="100%" src="comments_id1.php"></iframe>
</div>
<div id="2">
<iframe width="100%" src="comments_id2.php"></iframe>
</div>
Now here's my question:
Is this even a valid solution that anyone would recommend? And if so are there any major consequences (besides search engines) using <iframe> for that purpose?
If this is not the way to go, any suggestions?
Thanks!

Personally I deeply hate IFRAMEs for may reasons, so I'd recommend to stay away from them.
Have you read the Commentics' integration guide?
It seems you have to put
<?php
session_start();
ob_start();
?>
at the beginning of the pag, and
<?php
$page_id = "1";
$reference = "Page One";
$path_to_comments_folder = "comments/";
define ('IN_COMMENTICS', 'true'); //no need to edit this line
require $path_to_comments_folder . "includes/commentics.php"; //no need to edit this line
?>
where you want your comments. There's also an extended integration guide.

i wouldn't use iframes …
to work around the headers problem, you can buffer output (headers can only be sent before the actual content) and then send all at once:
ob_start();
// your code with includes
ob_end_flush();

I'm not familiar with the script you're using, but iframes have some significant downsides. Some downsides to that approach could be:
Iframes need their width and height defined in the HTML tag. If the dimensions inside the Iframe differ (because of an longer than usual comment, for example), you would get extra set(s) of scrollbars.
The memory usage and render times of iframes are high, especially in older Internet Explorer versions
To avoid the "Cannot modify header information" warnings, you could enable output buffering in PHP, or you could look at what headers the script you're using is actually sending. Maybe they're unnecessary?

Another consequence of using iframes is that the rendering may be out of order, since it is an independent HTTP request, and, because it is an additional request, this can add overall time to the retrieval of the data, especially in IE versions before 8 where they were limited to 2 simultaneous HTTP requests at a time--so if you have images or other scripts loading at the same time, some of these may be queued until one or both of the two slots are free. IE8 (and Firefox) boosted this to 6.
While it seems the real solution is looking into them fixing the Commentics script, or you finding another library, despite all advice you will probably find here to the contrary (albeit for good reasons of course), for beginners, I recommend focused on practicality and experimentation rather than dogma; in other words, it could work out all right for you, as long as there are no links inside the iframes which, if clicked, would lead to only the iframe being replaced with the content. Not a best practice though for reasons I and others have mentioned.
Another issue to watch for is that even the slightest whitespace before your beginning <?php is interpreted as text sent to the user, so if a script you include tries to then add headers, you could have problems. The headers being already sent message means that the script has started to send headers since it needed to send them before starting to send the content (in this case the whitespace) which you already started printing out (without buffering).
For PHP, I really recommend a templating engine like Smarty (and Smarty is nicely documented) where you get comfortable with the pattern of letting your business logic run first, and then supplying variables to the design logic for use there (currently what is your HTML + includes). When you're including others libraries which output text, you will need to still use buffering though for such reasons as you discovered.

Just remove:
<?php
session_start();
ob_start();
?>
from comments_id1.php
It will work.

Related

Are there any limitations on where PHP code can go inside a file?

Can you put PHP anywhere in a file? Inside tags and quotes? For example, is something like this guaranteed to work (even though it isn't always recognized by an IDE's syntax highlighter):
<tr><tbody <?php if(!$row) echo "style='display: none;'"; ?>>
<!-- stuff that we only want to show if $row exists -->
</tbody></tr>
Or for example:
<a href="http://www.google.com/search?q=<?= echo $searchTerm; ?>"</a>
I know I can test this sort of thing on my machine, but I'm wondering if it is guaranteed/defined behavior and if there are any edge cases that don't work that I've missed.
Also, is there good reason not to do this? Is it dangerous because the next person looking at the code might miss it? Should I put a comment in? Does having to add a comment defeat the purpose of this method - succinctness?
Yes you can put the php tags anywhere in the page (html) there is no stopping you on that.
If we go under the hood, your web server sends the code to the php interpreter via a handler and merges the output with your static html file and sends the merged file as the response.
To add to my answer, developers usually go for MVC based frameworks so that the php code inside html page is restricted to only printing the variables and the business logic is performed in the controllers. I personally prefer CakePHP. Apart from that you might not want to put code that manipulates session or performs redirection between html tags else you will recieve the headers already set error as you have already printed certain html code before modifying the headers.

$_GET is not working

Creating a rating system and the info is not being transmitted through my $_GET variable. The code is below
if (isset($_GET['item'], $_GET['rating'])){
echo 'Works!';
}
The variable is being entered in this code below
<?php echo number_format(
$article['rating'],1); ?>
<div class = "rate">
Rate:
<?php
for ($x =1; $x<= $maximum_rating; $x++){
?>
<a href="prestige.php?item=<?php echo $article['id']; ?>&rating=<?php echo $x;?>">
<?php echo $x; ?></a>
<?php
}
?>
I am fairly new to programming so any ideas or tips would be greatly appreciated.
There are a couple of things you should do.
1.
Instead of
prestige.php?item=<?php echo $article['id']; ?>&rating=<?php echo $x;?>
Use
prestige.php?<?= http_build_query(array('item' => $article['id'], 'rating' => $x), '&') ?>
This will escape the parameters. Vars $article['id'] and $x could contain characters that break the HTML or URL.
2.
Look at the Net tab in your Firebug/Chrome dev toolbar. Are there any redirects? What headers are sent?
Also look at the address bar to see if prestige.php really is loaded with the GET parameters.
3.
Use a debug tool like XDebug to step through your code. You might have some code that resets the $_GET vars. Personally I use the IDE PHPed, but it's kinda expensive.
The code you posted works. So the snag must be in the code you did not post:
maybe the prestige.php page has a PHP error that prevents it from displaying anything; start with an empty file containing just <?php echo 'OK so far'; ?>.
maybe the page contains code (security checks, frameworks...) that kills $_GET. (reduce the page to a minimum working case, without include/requires)
maybe the page does work, but the output gets snarked by an untimely ob_end_clean() that was meant to "clean the page" before the real output started; (reduce the page to a minimum working case)
maybe the page works, the string 'Works' is there, but you can't see it due to HTML markup, CSS, or other rendering problems (check the page source)
the URL might be broken because the item code contains invalid URL characters (check what appears in the browser address bar)
there might be an URL rewrite scheme that interferes (check .htaccess and the server logs)
I just remembered something like this happening with international characters in the URL. Try with an ASCII-clean item code to see what happens.
Just to be sure: verify there is no auto_prepend'ed file which might interfere.
Then, it might also be more than one of the above acting together. Often when debugging one unintentionally breaks some code, and even after fixing the first bug, the code doesn't start working again - this doesn't mean the fix was invalid.
I'm sorry -- I'm at the end of my options. I really look forward to knowing what the reason was. (Usually the more explanations I amass, the more the real answer tends to be "none of the above". When it happens to me, sometimes I wonder whether to start to believe in gremlins :-( ).

Why save output until the end?

Very quick question about programming practices here:
I've always used echo() to output HTML code to the user as soon as it was generated, and used ob_start() at the same time to be able to output headers later in the code. Recently, I was made aware that this is bad programming practice and I should be saving HTML output until the end.
Is there a reason for this? What is it, and why isn't output buffering a good alternative?
Thanks!
Some thoughts, not necessarily in order.
Using echo to output HTML is messy. PHP is a template language, you can break out of it if you need to output HTML:
<?php echo "<div id=\"foo\">" . $bar . "</div>"; ?>
vs
<div id="foo"><?php echo $bar; ?></div>
Producing HTML first and outputting headers later is messy logic. Decide what you want to send first, then send appropriate headers, then produce the content.
Buffering HTML to send headers later itself is not really a problem, but it's an indicator of badly structured flow.
Your apps could likely benefit from some compartmentalization/breaking down of logical steps.
Look into the MVC pattern.
Whenever any HTML is sent to the browser, headers are received/created. PHP can't send any more headers after this happens. So, by sending code "early", you're disabling PHP's ability to send headers, and limiting the flexibility of your code (either now or for future changes).
It is good to handle all sorts of things before you output in a view - for example, you may need to send additional headers such as Location and Set-Cookie.
Also, you never know what kind of view you will need - this response this time is HTML, but what if you want it as JSON or XML later? You'll have a difficult time restructuring.
If you had left all output to a final view, you could swap the HTML for an XML template.

What about calling aspx in php?

Here is my code
<html>
<body>
<?php
include("Default.aspx");
?>
</body>
</html>
but it keeps giving me the output of
<%# Page Language="C#"
AutoEventWireup="true"
CodeFile="Default.aspx.cs"
Inherits="_Default" %> <%
Response.Write("Hello world!"); %>
I just need to run the Hello World on the site.
If you want the output of the aspx file, you will need to request it via a web server which can understand aspx files rather than the file system, e.g.
include("http://example.com/Default.aspx");
Your PHP installation must have URL fopen wrappers enabled for this to work.
As Magnus Nordlander notes in another answer, you should only use include if you expect to find php code in the file. If you don't, you could simply use readfile to output the data verbatim:
readfile("http://example.com/Default.aspx");
You seem to be going about this in a very wrong way.
What include() (and require(), for that matter) does is that it parses the specified file with the PHP interpreter. If your aspx-code for some reason generates PHP-code, which is supposed to be parsed by the PHP interpreter, then the way Paul Dixon suggests would be the right way of going about this. However, I would strongly advice against doing this.
For one thing, it's a huge security disaster waiting to happen. It's also incredibly bad architecturally speaking.
If you want to include HTML markup etc. generated using aspx, what you should do is to use
echo file_get_contents("http://www.example.com/Default.aspx");
This way, any PHP code in the output remains unparsed, thus avoiding the aforementioned security disaster. However, if you're able to do without mixing languages like this, that's probably going to be a much better solution.

What are the advantages to putting your Javascript in a .php file?

I occasionally come across pages where some Javascript is included via a PHP file:
<html>
<head>
<script type="text/javascript" src="fake_js.php"></script>
</head>
<body onload="handleLoad();">
</body>
</html>
where the contents of fake_js.php might look something like this:
<?php header('Content-type: text/javascript') ?>
function handleLoad() {
alert('I loaded');
}
What are the advantages (or disadvantages) to including Javascript like this?
It makes it easy to set javascript variables from the server side.
var foo = <?=$foo?>
I usually have one php/javascript file in my projects that I use define any variables that need to be used in javascript. That way I can access constants used on the server-side (css colors, non-sensitive site properties, etc) easily in javascript.
Edit: For example here's a copy of my config.js.php file from the project I'm currently working on.
<?php
require_once "libs/config.php";
if (!function_exists("json_encode")) {
require_once "libs/JSON.php";
}
header("Content-type: text/javascript");
echo "var COLORS = ". json_encode($CSS_COLORS) .";\n";
echo "var DEBUG = ". ((DEBUG == true) ? "true" : "false").";";
?>
If you don't need it, don't use it:
The first thing you need to keep in
mind is YAGNI. You Ain't Gonna
Need It. Until a certain feature,
principle, or guideline becomes useful
and relevant, don't use it.
Disadvantages:
Added complexity
Slower than static files.
Caching problems (server side)
Scalability issues (load balancers offload static files from the heavy PHP/Apache etc processes)
Advantages:
User specific javascript - Can be achieved by initializing with the right variables / parameters in the <head> </head> section of the HTML
Page specific javascript - JS could also be generalized to use parameters
JSON created from database (usually requested via AJAX)
Unless the javascript is truely unique (i.e. JSON, parameters/variables) you don't gain much. But in every case you should minimize the amount of JS generated on the server side and maximize the amount of code in the static files. Don't forget that if it's dynamic, it has to be generated/downloaded again and again so it's not wanted for it to be a heavy process.
Also:
This could also be used to minimize the amount of server configuration (for example if the web server doesn't serve file.js with the correct content type)
There's no benefit for the example you gave above (beyond peculiar deployment scenarios where you have access to .php files and not .js files, which would be insane but not unheard of).
That said, this approach allows you to pass the JS through the php parser - which means you can generate your JS dynamically based on server variables.
Agree with tj111. Apart from what tj mentioned, I also found php-generated javascripts a great weapon to fight the browser's caching tricks. Not that long ago I was cursing the whole javascript for its being constantly cached by the browser. Refreshing the page helped me not, had to clear the whole cache in order to force the browser to reload the javascript files. As soon as I built a php wall in front of my javascripts:
fake_js.php:
<?php
header('Content-type: text/javascript')
include('the_real_javascript.js');
?>
A fresh new javascript would always show up at the client side. However this approach is obviously only good in the development phase, when it can save the developer quite some headache to have the correct javascript loaded in the browser. Of course when connecting to localhost, the penalty of repeatedly loading the same file is not as big.
In a live web application/site client-side caching is welcome to reduce network traffic and overall server load.
Advantage (not PHP specific - I used this technique in EmbPerl and JSP) would be the ability to dynamically generate or tweak/customize the JavaScript code on the server side.
An example usage would be population of an array based on the contents of a DB table.
Or application of localization techniques.
If you don't have full server access and can't turn on gzip encoding then it's pretty useful to put the following in your javascript file (note: will need to be renamed to file.js.php or parsed as PHP through .htaccess directive):
<?php
ob_start( 'ob_gzhandler' );
header("Content-type: text/javascript");
?>
// put all your regular javascript below...
You could also use it for better cache control, visitor tracking, etc in lieu of server-controlled solutions.
Absolutely none, IMHO. I use a js framework that I wrote to handle the setting of whatever server-side variables I need to have access to. It is essentially the same as embedding PHP in JavaScript, but much less ambiguous. Using this method allows you to also completely separate server-side logic and html away from javascript. This results in much cleaner, more organized and lowly-coupled modular code.
You could do something like this in your html:
<script type="text/javascript">
registry = {
myString : '<?php echo $somePhpString; ?>',
myInt : <?php echo $somePhpInteger; ?>
}
</script>
And then do something like this in your js:
if (registry.myInt === 1) {
alert(registry.myString);
}

Categories