I have looked at some of the other posts made on similar topics but I cannot follow what they are instructing.
Basically my problem is this, I want to redirect to the main log in page of my website after a successful password reset has happened.
Here is what I have so far:
if (isset($_POST['Resetpw'])) {
if ($query == $_GET['token'] & $_POST['password'] == $_POST['confirmed_password']) {
$passwordTest = $_POST['password'];
$result = mysql_query("SELECT `tempTicket` FROM users WHERE `username` = '" . $_POST['username'] . "'limit 1;");
$query = mysql_fetch_array($result);
mysql_query("UPDATE users SET `tempPass` = '$passwordTest' WHERE `username` = '" . $_POST['username'] . "' ");
echo '<div class="success">Password successfully changed!</div> ';
//header("Location: www.google.com");
//exit;
This is all within a function, the commented out part is where I want to redirect to my webpage.
So to wrap it up, can I force the function to redirect to the start page after a function finishes. I am using KISSMVC framework for this project if that matters.
You should remove the echo before the redirect.
What you have commented out should work if you use the full path, e.g.: http://google.com.
Another thing: you should really drop the use of mysql_* functions (it will be deprecated in the future) and use either mysqli_* or PDO.
Yet another thing: you're application is vulnerable to SQL injection.
First, I hope I don't need to go into depth about sanitizing your inputs before accessing the database with them.
I am unaware of the KISSMVC. But I am aware of how PHP and browser-server interactions happen. So I'll approach your question from that format.
I see two things here. One is that you want to give the user an alert when a transaction has successfully happened. That can be done dynamically with a redirect, but it depends on where you send them. If you send the user to a location that you have no control over (your example cited google.com) then you will have to deliver your alert (and your input) with javascript and ajax. The reason for this is because header redirects won't function if you sent some output to the user's browser already. So, you will need to implement some .js into your code that makes an AJAX call to a script that executes your code and returns a success/failure flag, which then triggers a message (of success/failure).
If you do have control of the content you are redirecting to, and you do not wish to touch any .js, you can redirect to an intermediary page that uses a variable that you created to hold the success/failure message, output it to the browser and a button that links to your next page after that with the data appended to the query string. All that can be done in php/MySQL.
Yes, just get rid of the echo statement before it. You cannot echo anything to the screen before a header call.
You might also want to add some error handling so that you are really sure it was successful and switch to prepared statements to avoid sql injection.
Output Buffering
Everyone else here has said you can't echo anything before the header call (including whitespace). But that is fact incorrect. If you use output buffering in the php.ini file for example to output buffer the entire page - then you are free to use header() ANYWHERE in the script (so long as the code does not manually flush it). http://php.net/manual/en/outcontrol.configuration.php
You want to set this in php.ini
output_buffering = On;
And then you can use header() anywhere in your code. Just remember that after a redirect, to use die() or exit() to prevent the PHP page carrying on execution after the redirect.
Without Output Buffering
You must NOT print anything to the browser including whitespace otherwise the headers have already been sent and can no longer be modified by PHP. Output buffering stops this as the entire generated page is sent in one go at the end of the script meaning headers are free to be changed anywhere in the script.
P.S.
As others have mentioned, your SQL is vulnerable to SQL injection and you should no longer be using mysql_* but instead switch to pdo or mysqli_* due to mysql_* being depretiated.
Related
I have created a HTML login form which checks for email and password authentication and then redirects to the user account.
My PHP code is as below:
<?php
require('connect.php');//for connection to the database.
$email = $_POST['email'];
$password = $_POST['password'];
$query = "SELECT * FROM `account` WHERE pemail='$email' and password='$password'";
$result1 = mysql_query($query) or die(mysql_error());
$usercount = mysql_num_rows($result1);
if ($usercount == 1){
include 'myaccount.php';
}
else{
echo "Invalid Details.";
echo "<a href='login.php'>Back to Login</a>";
}
Here, I have tried include to redirect to the user account...and it works fine.
Though my instructor says me that it is wrong to use include and you should implement it in another ways.
Why it is wrong to use include to redirect to the user account? I searched for it but I didn't found the answer.
plz do not discourage...thanks in advance.
Yes, your instructor is correct. include() is for including PHP code, not for redirecting. header() function does that, so use it. Using include() works, but that doesn't mean you should use it.
Why shouldn't you use include?
include() is a function for "including" code from a different file. It loads and executes the code from the file and is not exclusively built for redirecting. On the other hand, the sole purpose of header() is to send raw HTTP headers, i.e. perform redirects and the like. Use that instead.
If you have multiple lines of code in the file you're using for the redirect, include() will execute it completely, every time you perform a redirect. If your application uses redirects heavily, this would mean a performance loss and would result in a laggy application. Moreover, you'll be needlessly executing several lines of code if you're using include(). If you were to use header(), you could avoid this problem. (By calling exit() right after header().)
More problems in your code:
You're using mysql_* functions. The ext/mysql extension is deprecated and shouldn't be used. Use MySQLi or PDO instead.
You're blindly injecting user input into your database query, thereby making it vulnerable to SQL injection. A user with malicious intent could technically cause troubles, or even delete your database entirely. Use PDO / MySQLi with prepared statements to prevent this from happening. See this question for more details on how.
Try this
if ($usercount == 1) {
$redirect_url = "";//here goes your url where you want to redirect the user to
header("Location: " . $redirect);
exit();
}
You should also look into MySqli or PDO
Most of my pages use Sessions, but I'm switching to PDO and calling session_start() at the start of every page is causing problems with passing headers. I've done several hours of research and am still unclear what to do about it.
Edit - What I've been doing: The 1rst line of the sign up/sign in documents as well as auth.php is session_start();, and the 1rst line of all pages the user visits subsequent to sign up/sign is require_once('auth.php');
I'm currently passing the user id to every page with $_SESSION['SESS_USER_ID']
When they sign up/sign in I connect it like this:
$member = $stmt_user->fetch();
$_SESSION['SESS_USER_ID'] = $member['user_id'];
And on every subsequent page I call it like this:
$user_id = $_SESSION['SESS_USER_ID'];
As per the manual
As of PHP 4.3.3, calling session_start() after the session was
previously started will result in an error of level E_NOTICE. Also,
the second session start will simply be ignored.
Does this mean that I no longer need to call it on every page and can just call it once when the user commences a session?
If not, what is the simplest way to do deal with this issue?
If you are using a framework, you likely just need to call it once in that framework. If each of your requests go to different php pages, then you need to make sure it gets called at least once per request (preferably as soon as possible).
You need to make yourself a bootstrap file.
A file with all common operations performed on the every page - session start, connect to database, set global variables, etc.
And then include this file into every script called.
So, you'll be sure that you have everything you need, yet called everything once.
Though I don't understand what does this question to do with PDO (as well as a previous one).
PDO is just a database driver and have not a slightest relation to headers, sessions and the like.
You can use ob_start and ob_end_flush to buffer your outputs, so you can actually do this:
<?php
ob_start();
echo '42';
session_start(); // still works because output is buffered
ob_end_flush();
?>
I have a form that submits to the same page. Now when it gets submitted and after it's processed I need it to have a unique query string.
So for example the user inputs some info then clicks submit, then the page saves the info on the server then the server spits it back out with a unique query string for that info.
If I try to set $_SERVER['QUERY_STRING'] it just hangs. Is there another way to do this?
Is it possible with a redirect?
EDIT, I'm going from mysite.com/ and the form action is on mysite.com/ and I want the browser to go to mysite.com/?blah
OK I tried putting this on my the top of my page with no luck
<?php
if ($_POST['data']) header('location: /?' . idFromDifferentFunction() );
?>
but it just keeps loading, I'm guessing it just redirects itself to death.
I hope you now understand what I'm trying to do
Chances are that your script is continuing to run after the code that says it should redirect. You also need to be more precise with the header:
<?php
if (isset($_POST['data'])) {
header('Location: /?' . idFromDifferentFunction() );
exit;
}
?>
If you use the code above, it will make the script exit which dumps the output and the browser will see the redirect (note the capital L in Location).
The key point is the exit following the redirect header. Without it, PHP is very likely going to continue working on whatever other code you're doing in the script.
It's not entirely clear what you're after, but I think you mean you want to go to a page with a unique value in the query string (the bit after the ?) once the processing is complete. Does this unique value need to actually reference something in the system (for a newly-created DB entry does it need to reference the ID of the new entry) or does it just have to be unique?
If it's the latter, you could just generate a random unique ID do the following:
header ('location: /path/to/script?id=' . uniqid ());
If it's the former, then replace the call to uniqid with the value of the database key.
The values in $_SERVER are set at runtime by PHP and should be considered read-only. Changing their values will have no meaningful effect.
$_SERVER['QUERY_STRING'] is part of PHP's globals. You should not be setting those variables, instead set it via a session and return it after submission.
If you are trying to redirect the user to a specific URL then use:
header('Location: mysite.com/bla/bla');
Writing to $_SERVER is pointless. It doesn't affect the client browsers in any way. If you want to change the query string displayed in the client browser, you'll have to use a 301/302 redirect using a header('Location: ...') call.
Hey, I am trying to make an if statement that redirects them to a different page if true, simple right?
I am not sure why this is not working but I am using:
if ($_POST['accounttype']=='Paid User - £2 p/m'){
$userid = strtolower($_SESSION['X2X2']);
$getuser = mysql_query("SELECT * FROM XXXXXX WHERE X2X2 = '$userid'");
$info = mysql_fetch_array($getuser);
$id = $info['X3X3'];
mysql_query("UPDATE members SET payment = '" . mysql_real_escape_string("XXXXXXXX"). "' WHERE X3X3 = $id");
header('Location: http://beta.XXXXX.co.uk/purchase.php');
mysql_close($con);
}
When I put
<?
echo $_POST['accounttype'];
?>
And I get back
Paid User - £2 p/m
Which is correct?
Any help would be appreciated,
Thanks.
Looks like you want to call exit() before the close brace on your if statement.
The documentation for header has example code like this:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
The end bit of your if statement really ought to be:
mysql_query("UPDATE members SET payment = '" . mysql_real_escape_string("XXXXXXXX"). "' WHERE X3X3 = $id");
mysql_close($con); // do this before sending a redirect header
header('Location: http://beta.XXXXX.co.uk/purchase.php');
exit();
Also, header doesn't work if you've already sent any output, per this warning from the documentation for header:
Remember that header() must be called
before any actual output is sent,
either by normal HTML tags, blank
lines in a file, or from PHP. It is a
very common error to read code with
include(), or require(), functions, or
another file access function, and have
spaces or empty lines that are output
before header() is called. The same
problem exists when using a single
PHP/HTML file.
As it seems to depend on £, you have several possibilities depending on which values $_POST['accounttype'] can have.
First I suggest you try:
if ($_POST['accounttype']=='Paid User - £2 p/m'){
(as £ is £ in HTML).
If this doesn't work, what is the part of the string, that makes it unique? Paid User or 2 p/m? If any of these, it is sufficient to check against a substring like:
if (substr($_POST['accounttype'],-5)=='2 p/m'){
or
if (substr($_POST['accounttype'],0,9)=='Paid User'){
or any combination (avoiding £).
You haven't by any chance already output something to the browser have you? If you modify the location header after using the echo or print statements, it will issue a warning which you probably won't see unless you have verbose errors or logging turned on.
I know this can happen with UTF-8 files in some versions of PHP - the byte order mark (BOM) of the UTF-8 file are output before the PHP script starts execution, which prevents the location header from being sent.
Altering the HTTP header with header requires that the HTTP header has not been sent yet. This can be one reason for why it doesn’t work for you as the HTTP header is sent together with the first output of your script (any output including text before <?php).
When you set error_reporting to E_ALL and display_errors to true, PHP will display you all errors immediately. This can help you to determine the cause of you error.
My first inclination would be to check if there are any extra characters on your POST data by trying the following:
if (trim($_POST['accounttype']) == 'Paid User - £2 p/m') {
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"