PHP counter file and page forwarding - php

So i'm writing this code so that you either get forwarded to a certain page if you're the first one to hit the link, or you are sent back to the original page after being displayed a message if you're not what beginner mistake am i making?
<?php
$count = file_get_contents('counter.txt');
$count = trim($count);
if ($count="0")
{
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
header("Location: newpage.html");
}
else
{
fclose($fl);
echo "Sorry but the item has already been sold out";
header("Location: oldpage.html");
}
?>

As for the delay, you can accomplish it two different ways. The first is to use PHP header (like you are currently doing), but change it to look like this:
<?php
header("refresh:5;url=oldpage.html");
echo "Sorry but the item has already been sold out";
?>
The other way is to echo out a piece of HTML code, the meta-refresh:
<?php
echo '<meta http-equiv="refresh" content="2;url=oldpage.html">';
echo "Sorry but the item has already been sold out";
?>
In both examples, 5 is the amount of seconds until the refresh. Experiment with each one to see if it will fit your needs.

This might be some sort of syntax that I'm not familiar with, but none of my scripts have ever had the
<? code
I simply use
<?
Also since you did not delay our header tag the user will not see the previously echoed statement above it. It will automatically redirect before the page has time to output fully.

Related

Meta refresh enters into infinite loop

I wrote the following code to delete entries on my SQL table:
echo "<td><a href='protected_page.php?action=delete&id=$id'>Borrar</a></td>";
}
if(($_GET['action'] == 'delete') && isset($_GET['id'])) {
$rem = "DELETE FROM busca WHERE id = '".$_GET['id']."'";
$mysqli->query($rem);
if($rem) {
echo "<meta http-equiv='refresh' content='0;URL=/protected_page.php'>";
}
}
Once I click the delete link the page enters into an infinite loop.
Look at your attribute value:
content='0;URL='/protected_page.php''
You are delimiting the value with ' but trying to use ' characters as data inside it.
This isn't possible so what you are really saying is:
content='0;URL='
The correct syntax is:
<meta http-equiv='refresh' content='0;URL=/protected_page.php'>
… without the quotes around the URL portion.
That said, meta refresh is a nasty approach to performing a redirect. An HTTP redirect is better:
<?php header("Location: /protected_page.php"); ?>
You will need to adjust your logic a little. HTTP headers have to be output before the HTTP body, and you're doing your delete & redirect logic in the middle of your HTML output.
As a rule of thumb it is better to put all your business logic (deleting things, fetching data from the database, etc) at the top of your PHP program, and then leave all the business of generating HTML and other output (using variables you populated in the business logic part at the top) at the bottom.
If you really want to use PHP for this, here you go:
//0 = is second after is refresh
<?php header("Refresh: 0; URL=http://redirect-url"); ?>
If You Want Use HTML for This, Here you Go
//0 = is second after is refresh
<meta http-equiv="refresh" content="0;http://redirect-url" />
use header instead of meta tag as below
if($rem) {
header( 'Location: protected_page.php' );
}

Last 5 Page Names User Viewed

I'm trying to code the last 5 page names the user viewed on my site and produce it into a list. I'm currently able to get the current page name, but I don't know how to get the previous pages. This is the code I'm using to get the current page name:
<?php
$pageName = basename($_SERVER['PHP_SELF']);
echo $pageName;
?>
PHP Sessions should get you going in the right direction. For example:
session_start();
if(!isset($_SESSION['pages'])) {
$_SESSION['pages'] = array();
}
if(count($_SESSION['pages']) < 5) {
$_SESSION['pages'] [] = $_SERVER['PHP_SELF'];
} else {
echo "Limit reached";
}
print_r($_SESSION['pages']);
I recommend you use PHP Sessions to accomplish this.
So, save the current page name that you want to the sessions variable like so:
<?php
$pageName = basename($_SERVER['PHP_SELF']);
$_SESSION['pageName'] = $pageName;
?>
And then continue to save these names. #Len_D just beat me to the punch with an answer that uses arrays and is likely what you need.

PHP Header relocating and $_GET

I have a website that allows users to upload a picture, but I don't want any nudity in the photos. I found a scan written in php that I have succesfully implemented. The file and record are deleted if nudity is found to be in the file. I am just having trouble alerting the user as to why there pic wasn't kept. It just reloads the page. What could be the problem?
This code is the beginning of non commented code in my new2.php file:
if (isset($_GET['error'])) {
echo "Nudity found. Please try again with a more appropriate picture.";
sleep(5);
header("Location: new2.php");
}
This code is the code that scans the pic for nudity:
if($quant->isPorn()) {
$q = "delete from $table where id='$id'";
$result = mysql_query($q);
unlink("pics/".$picfile);
header('Location: new2.php?error=1');
} else {
header("Location: index.php?id=$id");
}
Any help would be greatly appreciated!
Your echo output won't be seen by the user. Output hasn't been sent to the browser yet, that happens at the end of your script. You redirect before that happens.
If you want to send a message, wait 5 seconds, and then redirect, do it client side.
<?php if (isset($_GET['error'])) { ?>
<p>Nudity found. Please try again with a more appropriate picture.</p>
<script>
setTimeout("self.location='new2.php'",5000);
</script>
<?php } ?>
Javascript is not needed. Just output the page containing your error, but change
sleep(5);
header("Location: new2.php");
to
header("Refresh: 5; url=new2.php");
This has the same effect as a <meta http-equiv="refresh">.
Don't do it from header. Use this instead:
<script> location="whatever.php?a=1"; </script>

Not displaying cookie count correctly

I have one file basket.php that displays the count perfectly, but in the other php file product.php it always displays 0 the codings are below:
basket.php
<?php
//include(dirname(__FILE__)."/../config.php");
if (isset($_COOKIE["products"])) {
//Count of all products in basket
$BasketCount = count($_COOKIE['products']);
//Loop through and get each cookie
foreach ($_COOKIE['products'] as $name) {
$name = htmlspecialchars($name);
echo "$name <a href='remove.php?remove=$name'>Click here to remove from basket</a> <br />\n";
}
echo "Basket Count: $BasketCount";
}else{
echo "Basket is empty";
}
?>
product.php
(just the line that gets the basket count)
$basketcount = count($_COOKIE['products']);
Here is how i set the cookies
addtobasket.php
<?php
include(dirname(__FILE__)."/../config.php");
$product = $_GET['p'];
setcookie("products[$product]", $product);
echo "$product added to basket";
//Show current basket products
?>
May be issue with path - http://www.php.net/manual/en/function.setcookie.php, $path parameter. Or domain.
Not the actual answer, but nevertheless related:
Assuming you're making a commercial website with a basket/shopping cart system, I would advice this:
DO NOT RELY ON COOKIES, never. It's stored on client side and can be modified easily. Moreover some browser simply refuses them, and thus your basket won't work.
Use $_SESSION[] instead, they only store the identifier client side. Safer, both against hacking code flaws and anything.
may be you are running product.php before cookie is set..
other than that code is fine to me.
or you can check cookie is set or not by this code..
if(isset($_COOKIE['products'][$product])){
echo "cookie is set..";
}
so that you will have exact idea..

php outbuffering and header

I am using php 5.3.6 and below is my code and it is producing an error
Warning: Cannot modify header information - headers already sent by (output started at ............
<?php
ob_implicit_flush(true);
print "<pre>";
$loop = true;
$counter = 0;
while ($loop) {
$counter++;
// some code
print "some output of code. \n";
if ($elapsedTime > 300) {
$loop = false;
print "5 minute passed and loop ended. \n";
}
}
print "</pre>";
ob_end_flush();
header("refresh:5;url=test.php" );
?>
what I wanted to do is displays contents from each loop while the loop is active.
then when the loop is ended I need to flush all the previous output or header and send a new header to refresh the current page.
The short version is, you can't. You can not send headers after the content.
You could print out a link at the end, that the user can click on to refresh the page. Or if the generation will take a fixed amount of time (say 5 minutes) you could put an HTML meta refresh tag on the page that goes after 5 minutes and 1 second.
http://en.wikipedia.org/wiki/Meta_refresh
Header redirects generally take the form Location: ?test.php, if there's a new format that looks just like the meta refresh format, I'm not aware of it, and it would seem to violate how the other headers work (namely key: value). Short version: I don't think that header will work even if it does go first.
As suggested by preinheimer the header must be sended before each page ouput. Without using the headers you can use one row of javascript code for a simple redirect. This may be a solution for you:
<?php
print "<pre>";
$loop = true;
$counter = 0;
while ($loop) {
$counter++;
// some code
print "some output of code. \n";
if ($elapsedTime > 300) {
$loop = false;
print "5 minute passed and loop ended. \n";
}
}
print "</pre>";
# The php code has ended and the javascript code is ready for redirecting... (external to php tags)
?>
<script type="text/javascript">
window.location="http://www.example.com/";
</script>

Categories