$_GET is not working - php

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 :-( ).

Related

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.' --}';

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.

PHP: Echo Failure via $_GET

I am currently displaying errors on my website using this code:
<?php
$failure = strip_tags($_GET['failure']);
if($failure!=""){
echo '<div class="error">';
echo $failure;
echo '</div>';
}
?>
However, I am curious if this is safe. Is it?
while this solution would change a little bit your approach, why not have an errors.php file with this structure?
$error[1] = 'some error message';
$error[2] = 'some other error message';
$error[3] = '...'; // you get the point
And the just send an ID as the error:
somepage.php?failure=2
Then, include this code where you usually display your errors:
if($_GET['failure'] && array_key_exists($_GET['failure'],$error) {
echo $error[$_GET['failure']];
}
Just be sure to include errors.php in your config.php file (or whatever your main configuration's file name is).
Why?
Errors are often repeated, this way you can use them over and over again.
If you want to translate the site to another language, this system will be very helpful.
If you need to change a word on an error message, you will just have to change it once in the errors.php file.
IMHO it is much much safer to use ints than strings in this case.
You can (and of course always should, hat tip #DaveRandom) do a htmlspecialchars() after strip_tags in order to prevent some clever construction from getting past the tag stripper. I have never seen a working exploit doing that successfully but it can't hurt taking additional precautions.
If you do all that, this looks safe.
Note that there is a limit on the maximum size of a GET request - 1kb is a safe maximum amount.
Depending on what version of PHP you have, filter_input() is a decent alternative.

<iframe> instead of include

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.

Passing data from one php page to another is not working - why?

Frustrated php novice here...
I'm trying to pass a "type" value of either billto or shipto from ab.php to abp.php.
ab.php snippet:
<?php
echo '<a href="' . tep_href_link(FILENAME_ABP, 'edit=' . $bill_address['address_book_id'] . '&type=billto', 'SSL') . '">' .
tep_image_button('small_edit.gif', SMALL_IMAGE_BUTTON_EDIT) .
'</a>';
?>
This does add the &type=billto to the end of the url. It looks like this:
www.mydomain.com/abp.php?edit=408&type=billto&id=4a6524d
abp.php snippet:
if ($HTTP_GET_VARS['type'] == 'billto') {
then it does a db update...
The if returns false though (from what I can tell) because the update is not performed.
I've also tried $_GET instead of $HTTP_GET_VARS.
Because the code in abp.php isn't executed until after the user clicks a button, I can't use echos to check the value, but I can see the type in the url, so I'm not sure why it's not executing.
Could really use some direction... whether it's what I need to change, or even just suggestions on how to troubleshoot it further. I'm in the middle of a huge learning curve right now. Thanks!!!
edit:
Sorry, I just realized I left out that after the db update the user goes back to ab.php. So the whole workflow is this:
User goes to ab.php.
User clicks link to go to abp.php.
User changes data on abp.php.
User clicks button on abp.php.
Update to db is executed and user is sent back to ab.php.
Because the code in abp.php isn't executed until after the user clicks a button, I can't use echos to check the valueWhy not?
echo '<pre>Debug: $_GET=', htmlspecialchars(var_export($_GET, true)), "</pre>\n";
echo '<pre>Debug: billto===$_GET[type] = ', 'billto'===$_GET['type'] ? 'true':'false', "</pre>\n";
if ( 'billto'===$_GET['type'] ) {
...
edit: You might also be interested in netbeans and its php module:
"Debug PHP code using Xdebug: You can inspect local variables, set watches, set breakpoints, and evaluate code live. Navigate to declarations, types and files using Go To shortcuts and hypertext links."
try something like this
if ($_GET['type'] == 'billto') {
die("got to here, type must == billto");
this will prove that your if statement is working or not,
it may be that the update part is not working
Before the if statement - try
var_dump($_GET);
And make sure the 'billto' is contained within the $_GET array. Of course, if you have got the debuger setup, you should be able to watch the value of the $_GET array
or try:
var_dump($_REQUEST);
Check the URL of the second page, is it in the correct form? From the code snippet you post, I don't know if there would be a ? after the question mark. Also try to disable the redirect to see if your code is working as it should.
One other thing is you may want to put the new url in a variable first, then put that into the link HTML. It's less efficient, but makes the code easier to read and debug.
Try turning on error reporting, place this at the start of your php script
error_reporting ( E_ALL | E_STRICT)
PHP is very tolerant of typos and accessing subscripts in an array that does not exist; by enforcing strict and reporting all errors you would be able to catch those cases.
If you can't see the output, try this:
function log_error($no,$msg,$file,$line)
{
$errorMessage = "Error no $no: $msg in $file at line number $line";
file_put_contents("errors_paypal.txt",$errorMessage."\n\n",FILE_APPEND);
}
set_error_handler('log_error');
You may have to set some file permissions for the log file to be written to.
Of course, you can get Netbeans and its debugging module too.

Categories