I have a page which has a link to a php page which takes data from $_GET and updates a database. After that it returns the user to the homepage with:
header("Location: http://localhost/");
The thing is that this seems to "interrupt" the mysql part of the code. If I remove this redirect, everything in the database is updated, but when I put it back, nothing gets updated...
This is the database update code, I am using a class of mine as a mysql wrapper:
$conn->where('hash',$data1['hash']);
$conn->update(TABLE_ITEMS,$newData1);
$conn->where('hash',$data2['hash']);
$conn->update(TABLE_ITEMS,$newData2);
Notes:
-There is no text or echo()'s on the page and no space before the <?php tag
Order of Code:
Data received from $_SESSION and $_GET
Data processed and placed into arrays
Data placed into mysql database
header(); used to redirect page
Code
<?php
require_once('config.php');
import();
if ( isset ( $_GET['g'] ) && isset ( $_SESSION['itemA'] ) && isset ( $_SESSION['itemB'] ) ) {
$itemA = $_SESSION['gameA'];
$itemB = $_SESSION['gameB'];
$newData1 = processData($itemA);
$newData2 = processData($itemB);
$conn->update(TABLE_ITEMS,$newData1);
$conn->update(TABLE_ITEMS,$newData2);
header('Location: http://localhost/');
} else {
header('Location: http://localhost/');
}
If you send a header when previously content is outputted, you will get an error that may cause your script to stop execution. So if the header is above the update, the update may not be executed at all. It depends on your settings whether you see this error or not.
<?
echo 'yo';
header('Location: ....'); // <-- error
Update(); // Never gets executed
The output doesn't have to be an echo. It can even be a single space before the opening <?.
Without seeing much of the code, it's hard to be certain, but my guess would be that the PHP page is continuing to work exactly at it was before. What I would suggest might be happening is that the redirected page (ie your home page) is itself doing some database work which is overwriting the changes that had been done by the original page.
As I say, that's quite a wild guess in the absence of any more code (or even any detail about the data in question or what the site does), but I'd say it's worth investigating that possibility.
Try putting ob_start() at the top of the file. It sometimes helps. You can't output before calling header().
Show more code. It's to less of it to think what is wrong.
I have no idea why this worked, but it turned out that if I change this:
header("Location: http://localhost/");
to this:
header('Location: http://localhost/');
everything works. Weird!!
Related
I need on each page check if cookies are enabled.And use this code.
<?php
setcookie('COOK_CHK',uniqid(),time()+60*60*24);
if(!isset($_COOKIE['COOK_CHK'])){
echo"Cookies are disabled!";
exit;
}
session_start();
?>
However on the first check it gives me false until i don't refresh the page.I include this code in each page so can not redirect every time i load the page as it reduces performance.However i want to use it even if javascript is disabled.Any suggestions?
Can you use javascript? If so, all it takes is a check at the navigator.cookieEnabled variable.
It works in most modern browsers. You can read more about it here: http://www.w3schools.com/jsref/prop_nav_cookieenabled.asp
It's not possible because Cookies are in the browser, and PHP send them when the page has render, so will be available just in the second page.
A possible way to fix this is using javascript.
If you really should do it in PHP, for some crazy reason, send all your request to a main controller and save the state using other method, for example, write a var into a file, then redirect and in the next redirections you'll know if the cookies are enabled without needed any other redirection. Example:
$file = 'cookie_fake_'.$userIP;
if( !isset($_COOKIE['COOK_CHK']) && !file_exists($file) ){
file_put_contents($file, 'dummy');
setcookie('COOK_CHK',uniqid(),time()+60*60*24);
header('Location:/');
exit;
}
if(!isset($_COOKIE['COOK_CHK'])){
setcookie('COOK_CHK',uniqid(),time()+60*60*24);
echo"Cookies are disabled!";
exit;
}
Then you should write something to clean old files every hour or so, of course you can use a cache layer or a database or anything like that instead of writing a file.
Edit: The previous code will be really f** up if the user enables cookies and refresh the page, now I've fixed so it works at the second time it refresh. Not perfect but... You really should do this using javascript.
Cheers.
I have the following PHP script within a file named login.php
<?php
$ref = $_SERVER['HTTP_REFERER'];
if ($ref == 'http://example.com/dir/invalid.php' || $ref == 'http://www.example.com /dir/invalid.php') {
echo '
<div id="invalid">
TESTTESTTESTTESTTESTTESTTESTTEST
</div>
';
}
?>
I have deliberately went to the invalid.php page (which redirects using header() to login.php) and this div does not show up. Does it have something to do with the referrer not really being invalid.php or is there an issue with the script?
Thanks
I don't think the HTTP_REFERER is what you think it is. Namely, it is the page from which the user followed a link to the current page. However, it's very unreliable as we rely on the browser of the user to correctly report this value.
I would suggest the option I thought you needed, except that the only one I can think of you might doesn't really makes sense... (checking if the url matches a url that's not the current script)... so I do not see what you are trying to do.
As promised several ways to do what you want to achieve:
First off, I don't like this solution at all and really consider it ugly, but it's the one closest to what you where trying to do.
invalid.php
require 'login.php'; // we include the file instead of referring to it
login.php
if ($_SERVER['SCRIPT_NAME'] == 'invalid.php')
{
// do whatever
}
The main difference between what you did and what I did for the user will be that here the url bar will show that you're at invalid.php and not somewhere else. This also means that refreshing doesn't make the message go away.
A better solution in my opinion is the following:
In your script that logs a user in (checks the database and everything):
if (!valid_login()) // pseudo-code, obviously
{
$_SESSION['invalid_login'] = true;
header('Location: login.php');
// previously, we had something like this instead of the two lines above:
// header('Location: invalid.php');
}
in login.php
if (isset($_SESSION['invalid_login']) && $_SESSION['invalid_login'])
{
$_SESSION['invalid_login'] = false;
// do whatever
}
Of course, this should be done with proper session facilities like starting up the session in both those files. Instead of using session variables, you could include the file and use normal variables or send GET variables through the header request, but both those solutions share a problem: refreshing doesn't make the message disappear. However, if you were to move the code from the top file of the two above to login.php (if it's not already there, I don't know what file that actually is...) you could once again use normal variables instead of session variables and have a solution in which refreshing does make it go away. In this case, you might argue that you are cluttering your files with bussiness logic and presentation, but there are solutions to that (like keeping it in a separate file, and including it into login.php, moving the html to another file and including that one into login.php or both.
Im trying to update the contents of an element after running some php code. I realize the php is executed first, but I thought by loading the page I could then find the element? However console says cannot find element of null so I guess the page isn't loading before the innerHTML code is running.
Anyone any ideas?
else if(strlen($_POST['username']) < 6){
header("Location: http://webpage/register.html");
echo "document.getElementById('elemID').innerHTML = usename too short";
}
header() instructs your clients to go to the new location, hence outputting anything after that would make no effect to your client as the content of register.html is already handled differently by your server.
If you can change register.html to use php instead, you could pass
header("Location: http://webpage/register.php?msg=username%20too%20short");
Then in your register.php
if(!empty($_GET['msg'])) echo $_GET['msg'];
First, you shouldn't really have any logic after your header Location redirect. It is good practice to put "exit" or "die" after a redirect like that as you can't guarantee that the browser will ever see the next line before redirecting. In fact, you can pretty well guarantee that it will more often not see that code.
If you're going to redirect, put your error as an argument to your redirect URL and have logic there that shows the error like this:
header("Location: http://webpage/register.php?error=username%20too%20short");
Then in you register.php (I renamed it from .html so you can read the error argument) you can reference your error like:
$error = $_GET['error'];
if (!empty($error)) {
//write your error out in some markup or javascript...
}
So my issue is that I'm setting a message in a session var to carry over in a page redirect.
And then setting the var to an empty string so it doesn't redisplay everytime.
Like so:
if ($successMsgs || !empty($_SESSION['msg_success'])) {
$success_block[] = '<ul id="success-block">';
foreach($successMsgs as $success) {
$success_block[] = '<li>'.$success.'</li>';
}
if (!empty($_SESSION['msg_success'])) {
$success_block[]='<li>'.$_SESSION['msg_success'].'</li>';
$_SESSION['msg_success']='';
}
$success_block[] = '</ul>';
$success_block = implode('',$success_block);
}
The problem is that the clearing of the session var seems to have a retro-active effect so the message never gets displayed. It only works if I take out the line that re-sets it to an empty string. I'm thinking there's something about when session vars are evaluated that I don't understand?
Except for the freedom to define functions and classes after invoking them, there is definitely nothing retro-active in PHP. Session variables will be available after the session_start() command. Unsetting a session variable inside the block won't have an effect in the code before it occurs.
Your problem must have to do with something else - maybe the page gets called twice, or a header redirect takes place?
It turned out that the code beneath the redirect was getting run, before actually redirecting. The solution was simply to add an exit to the redirect function.
well, the only possibility i can think of is that you are calling this piece of coding twice. and in the first call it doesn't get printed. maybe you are redirecting twice for some reason...
I am making a simple Dynamic Website using PHP, where i allow the user to login and then access specific pages. So here's what i have done so far.
The logged in values are taken though $_POST variables in a php script where it fetches values from database for registered users. If the user is found i do the following:
session_register('userid');
$_SESSION['userid'] = $username;//this is taken from $_POST
$_SESSION['accesslevel'] = $access;
at the beginning of the php script i have put session_start();
Now here comes my problem.
At every page now i have to check if the user is allowed to view that page or not, if he ain't then he must be redirected to login.php, if he is then the page load must continue.
Now so far what i have learnt is that only way to maintain values across php pages is to use $_SESSION variables, and which ever page i am using Session Variables i must write session_start() on each page as the first line, else i will be getting Headers Already Sent error..
Strangely i exactly have done that but still get erros with the "headers already sent".
SO i want to what is the best way to design a website, where i have to use Session variables across most of the pages, and keep these common checks at a common place..
Can i use include() feature some how?
Are sessions only way to communicate data across php pages.
What is a better way?
I have the following code :
<?php
session_start();
if(!isset($_SESSION['user']))
{
$_SESSION['loc'] = "adminhome.php";
header("location:ettschoollogin.php");
exit();
}
?>
Which resides on top of every page which wants to check if the user has logged in.
And this is teh script to check for login
<?php
session_start();
include("connection.php");
$userid =$_POST['userid'];
$userpwd =$_POST['userpwd'];
$query="Select UNAME,UPASSWORD,SCHOOL,uaccess from schooluser where uname = '$userid'";
$result=mysql_query($query) or die("couldn't execute the query");
$row=mysql_fetch_array($result);
$useraccess = $row["uaccess"];
$school =$row[2];
if(($row[0]==$userid)&&($row[1]==$userpwd))
{
session_register('userid');
$_SESSION['userid']=$userid;
$_SESSION['school']=$school;
if($useraccess =="admin")
{
header("Location:adminhome.php");
}
if($useraccess !="admin")
{
header("Location:school_main.php");
}
}
else
{
header("Location:ettschoollogin.php?err=1");
}
?>
i was aware of the common error of having extra spaces after "?>", BUT I STILL GET IT.
Thanks guys, i missed out and the "connection.php" file actually had extra spaces after "?>" i had removed it before, but some how the file got rewritten again.Thanks a lot.
Yes, you can use include. Put all your common functions in a separate php file and "include" it at the top of each file.
You can use cookies to store information (typically just an id that you use to look up additional information in the PHP page). Normally, PHP sessions are handled using cookies though. See setcookie in the docs.
You are probably getting the error messages due to stray characters outside of a <?php ?> block. A common error is to have an extra blank line at the end of an include file, after the ?>. That blank line will be output and your headers will have been sent. If that isn't the problem, you will just need to make sure you move the session related code above any code that might generate some output (eg by using print or echo).
•Can i use include() feature some how?
Yes. You can do whatever you want before your session_start() call, only, you must not have outputted anything, not even a single space or character. Probably you have already outputted something, maybe on an automatic inclusion or apache prepend.
•Are sessions only way to communicate data across php pages.
•What is a better way?
Other ways are cookies, post and get parameters. But sessions are the only way to securely pass data among pages without sending them to the client and back (which may pose security risks)
Write ob_start(); at the top of your code and then you dont get the error of "headers already send"