How to redirect with php - php

I have a register form for member. But when member registered in my website i want automatically open wellcome.php page. I know it is header("Location: wellcome.php"); but i did it and nothing happen. What can i do? Registered is successfully But does not redirect.
<?php
include("includes/connect.php");
session_start();
if(isset($_POST['submit_bregister'])){
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$re_email = $_POST['re_email'];
$password = sha1($_POST['password']);
$vergi_num = $_POST['vergi_num'];
$sirket_kategorisi = $_POST['sirket_kategorisi'];
$is_kategorin = $_POST['is_kategorin'];
$ulke = $_POST['ulke'];
$sehir = $_POST['sehir'];
if($name==''){
echo"<div class='error_name'>Adınız alanını boş bıraktınız!</div>";
exit();
}
if($surname==''){
echo"<div class='error_name'>Soyadınız alanını boş bıraktınız!</div>";
exit();
}
if($vergi_num==''){
echo"<div class='error_name'>Vergi numaranızı girmediniz!</div>";
exit();
}
if(strlen($vergi_num)>11 || strlen($vergi_num)<0){
echo"<div class='error_name'>Vergi numaranız en az çok 11 hane olabilir!</div>";
exit();
}
if($sirket_kategorisi==''){
echo"<div class='error_name'>Şirket Kategorisi alanını boş bırakamazsınız!</div>";
exit();
}
if($is_kategorisi==''){
echo"<div class='error_name'>İş kategoriniz alanını boş bırakamazsınız!</div>";
exit();
}
if($ulke==''){
echo"<div class='error_name'>Yaşadığınız Ülkeyi boş bırakamazsınız!</div>";
exit();
}
if($sehir==''){
echo"<div class='error_name'>Yaşadığınız Şehir alanını boş bırakamazsınız!</div>";
exit();
}
if($email==''){
echo"<div class='error_name'>E-Mail alanını boş bıraktınız!</div>";
exit();
}
if($_POST['email'] !== $_POST['re_email']){
echo"<div class='error_name'>E-Mail Adresleriniz Eşleşmiyor!</div>";
exit();
}
$check_email = "SELECT * FROM users WHERE email='$email'";
$run = mysql_query($check_email);
if(mysql_num_rows($run)>0){
echo "<div class='error_name'>Bu E-Mail adresi kullanımda!</div>";
exit();
}
$sirket_kategorisi = (int)$sirket_kategorisi;
$query = "SELECT is_kategorisi FROM business_category WHERE id='$sirket_kategorisi'";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$sirket_kategorisi = $row['is_kategorisi'];
$querys ="INSERT INTO `users` (`name`,`surname`,`email`, `re_email`,`password`,`vergi_num`,`sirket_kategorisi`,`is_kategorin`,`ulke`,`sehir`)
VALUES ('$name','$surname','$email', '$re_email','$password','$vergi_num','$sirket_kategorisi','$is_kategorin','$ulke','$sehir')";
$result = mysql_query($querys) or die(mysql_error());
if($result){
header('Location: email');
exit;
}
else {
header('Location: error');
exit;
}
}
?>

The headers cannot be sent after there is any output on the page. The echo is an output, so you cannot send any new headers – in you case the Location header.
You should have the redirect before the echo.

Are you sure this header("Location: wellcome.php"); is at the end of your code?
What i mean with that is for example if you have an if what waits for the Get argument, something like:
if(isset($_GET['register']){
//... code for registration
}
please make sure that the header("Location: wellcome.php"); is at the end of if but inside of the bracket, and its good to use exit(); after the header.
Also you cant echo something before the header();, you should have an error when you do that, check if you are getting one.
Some of your code will help a lot to figure whats wrong.

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.
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>
Normally something like this will result in a Cannot modify header information - headers already warning unless you don't have error/warning reporting turned on.

PHP doesn't allow output before header becuase it will redirect to the page straight away using header(), so there is no point outputting a message before you use it. If you try it will cause an error.
You could, however, add in the header of that page
<meta http-equiv="refresh" content="5;url='http://www.your-website.com/welcome.php'" />
The content attr is broken down into 2 sections time(sec) and url i.e.
content="(time in seconds) ; url='(url)'"
You can change either of these, however, make sure you keep them both inside content=""

Related

PHP Unable to handle request

Here is my code, not too sure why it doesn't work but it cannot be processed. I can process phpinfo() correctly.
<?php
include("tools.php");
$username = $_POST["uname"];
$email = $_POST["email"];
$pasword = $_POST["pword"];
if(isset($username) and isset($email) and isset($password)){
if(add_user_database($username, $email, $password) == TRUE){
echo "You've been added!!!";
header("location:login.php");
}else{
echo "<script>alert('Error has occurd please contact " .
"support or try again later');</script>";
header("location:register.php");
}
}else{
echo "<script>alert('Please fill in all forms');</script>";
header("location:register.php");
}
?>
From the php docs,
"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."
You shouldn't need the echo things there, if you really wanted those messages, you could set them as $_SESSION('statusMessage'); and then on the redirect page check if it is set, echo out something to show it, and set them to undefined.
Also, please please please make sure that input gets sanitised in add_user_database()!!
EDIT:
Helpful hints
In the check login script:
if(add_user_database()){
$_SESSION['addUserStatus'] = "Success, you have been added, woo!";
header("Location: someOtherPage.php");
}else{
$_SESSION['addUserStatus'] = "Error! Please contact support for assistance!");
header("Location: someOtherPage.php");
}
In the some other page:
if(isset($_SESSION['addUserStatus']){
echo "<script>showLoginMessage('" . $_SESSION['addUserStatus'] . "')</script>";
$_SESSION['addUserStatus'] = undefined;
}
Header already sent error
look at
http://php.net/manual/en/function.header.php
Remember that header() must be called before any actual output is sent

Write text with echo() after reloading page with header()

I have page called account_settings.php and it's consist of change password, change profile pic, change user details (name, bio etc.). My question is how to write message with echo() after redirecting page with header().
Something like this:
if (true)
{
Do_Some_MySQL();
header("Location: account_settings.php");
echo "Success!";
}
else
{
echo "Error!";
}
Thank you for all replies. ;-)
You can't actually do something after sending a Location header - it is impossible.
Instead, you could use $_SESSION array value to perform your task. Like:
if (true)
{
Do_Some_MySQL();
$_SESSION['message'] = 'Error!';
header("Location: account_settings.php");
}
else
{
echo "Error!";
}
And then on your account_setting.php:
<?php echo $_SESSION['message'] ?>
This would be nice if the account_settings.php is not the same page as you currently are. Otherwise, you could use the following code:
if (true)
{
Do_Some_MySQL();
$error = 'Success!';
header("Location: account_settings.php");
}
else
{
$error = "Error!";
}
And on the same page:
<?php if($error) echo $error; ?>
Also don't forget to include session_start() on both pages if you didn't it yet.
I would use a SESSION variable:
on redirect-page:
<?php
#session_start();
if(true){
$_SESSION['success'] = 1;
header("Location: account-settings.php");
}
?>
and on account-settings.php:
<?php
#session_start();
if(isset($_SESSION['success'])){
echo "Success!";
unset($_SESSION['success']);
}
You cannot echo anything after you just redirected. The browser is already processing the request to redirect to another page, so it doesn't bother about displaying the message anymore. What you seem to be looking for is something called flash message. You can set a temporary message in the session and have it display on the new page. For example, in your account_settings.php page:
// Make sure you have an actual session
if (!session_id()) {
session_start();
}
if (true) {
Do_Some_MySQL();
$_SESSION['flashMessage'] = 'Success!';
header('Location: account_settings.php');
}
Then in your template file for account_settings, check if there is any flash message and display it accordingly (and unset it to avoid a loop):
if (isset($_SESSION['flashMessage'])) {
echo $_SESSION['flashMessage'];
unset($_SESSION['flashMessage']);
}
These people are correct...you can't send headers after a redirect. Although I think this would be a beneficial alternative. To send a GET request in your header and process it on the receiving page. They are suggesting to use $_SESSION vars, but you can use GET vars. Ex:
if (true)
{
//Do_Some_MySQL();
header("Location: account_settings.php?message=success");
//above has GET var message = Success
}
else
{
header("Location: account_settings.php?message=error");
}
On your account_settings.php page have this code:
if (isset($_GET['message'])) {
$message = $_GET['message'];
if ($message == "success") {
echo "Success";
} else {
echo "Error";
}
}
This removes the need of CONSTANT SESSION vars. and gives you plenty of flexibility.
header("Location: account_settings.php?message=No%20results%20found");
//%20 are URL spaces. I don't know if these are necessary.
If you need you can add more then one.
header("Location: account_settings.php?message=error&reason=No%20Results&timestamp=" . Date());
then account_settings.php can be:
if (isset($_GET['message'])) {
$message = $_GET['message'];
$reason = $_GET['reason'];
$time = $_GET['timestamp'];
if ($message == "success") {
echo "Success";
} else {
echo "Error: <br/>";
echo "Reason: $reason";
}
}
But remember GET exposes your messages in the browsers URL. So DON'T send sensitive information unless you secure it. Hope this helps.

php redirect_to() function undefined

I am working on a database and I need to redirect the user to another page after the login process.
I am using the redirect_to() function. After the code executes it gives me the error
Fatal error: Call to undefined function redirect_to()
Here is what I tried
if($result){
$num_rows = mysqli_num_rows($result);
if($num_rows == 1){
$found_user=mysqli_fetch_array($result);
redirect_to("main.php");
}
else{
redirect_to("index.php");
}
}
You have to define the redirect_to function before calling it. Try this code
<?php
if($result){
$num_rows = mysqli_num_rows($result);
if($num_rows == 1){
$found_user=mysqli_fetch_array($result);
redirect_to("main.php");
}
else{
redirect_to("index.php");
}
}
function redirect_to($location){
header('Location:'.$location);
}
?>
Try to use header :
<?php
/* Redirection vers une page différente du même dossier */
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>
redirect_to() isn't a function. You want to use header("Location: main.php");
As this is adding header information, it needs to be loaded before anything is passed to the page (I believe), so don't attempt to print anything out to the page before header() is called.
If you want to do something like that, I suggest using javascript.
redirect_to doesn't exist, or if it does, it's not been included/required correctly.
Add this;
if( function_exists('redirect_to') == FALSE ) { //Future proofing...
function redirect_to($where) {
header('Location: '. $where);
exit;
}
}
If you already have output, I would advise you looking at using output buffering.
You can easily redirect using following header("Location: ....) syntax:
header("Location: main.php");
exit;
You should equip your project with this function first as others have pointed. Alternatively refactor your code to use the builtin php function -> http://php.net/manual/en/function.http-redirect.php

php header() function won't redirect

I'm trying to post data from a form with insert.php as the action. However, I cannot redirect back to the index.php once the data has posted to the database.
I've searched through the following sites to find the answer:
Trip Wire Magazine
Daniweb
as well as ten stackoverflow questions on the subject.
Here is the code for the insert.php file:
<?php
include 'connect.php';
$id = $_POST['id'];
$idea = mysql_real_escape_string($_POST['new_idea']);
if(!$_POST['submit']) {
echo "Please fill out the form!";
header('Location: index.php');
} else {
mysql_query("INSERT INTO user_idea (`id`, `idea`, `time_created`) VALUES(NULL, '$idea', NULL)") or die(mysql_error());
echo "Idea has been added!";
header('Location: index.php');
}?>
From what I've gathered, the header() function won't execute if there's text output before it. I've tried this function without the echo "Idea has been added!"; and echo "Please fill out the form!";, but I still don't get a redirect.
Thanks in advance for your advice.
-MF
From PHP documentation :
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
And in your case, you are using echo before header()
work around method : use ob_start() at the top of the page
other method : Please omit any white space before starting <?php or after ?> in the page
and also use exit() just after header()
Try this
<?php
include 'connect.php';
$id = $_POST['id'];
$idea = mysql_real_escape_string($_POST['new_idea']);
if(!$_POST['submit']) {
$message = "Please fill out the form!";
header('Location: index.php?message='.$message); exit;
} else {
mysql_query("INSERT INTO user_idea (`id`, `idea`, `time_created`) VALUES(NULL, '$idea', NULL)") or die(mysql_error());
$message = "Idea has been added!";
header('Location: index.php?message='.$message); exit;
}?>
Pass the error message to index.php and display it there.
Don't print your output before header(). Store your data into session or pass it through URL.
Try this will surely help you .

About header error in PHP

I am working on a PHP project where I am trying to redirect from one page to another, using header (Location:something.php). It's working fine on the local machine but when uploaded to the server, the following error occurs:
Warning: Cannot modify header information - headers already sent by (output started at /homepages/4/d404449574/htdocs/yellowandred_in/newTest/editHome.php:15) in /homepages/4/d404449574/htdocs/yellowandred_in/newTest/editHome.php on line 43
I already tried with include, include_once, require and require_once but it's giving other errors like:
Cannot redeclare logged_in() (previously declared in C:\wamp\www\ynrNewVersion-1\editHome.php:3) in C:\wamp\www\ynrNewVersion-1\adminIndex.php on line 5
My code
<?php
session_start();
function logged_in() {
return isset($_SESSION['username']);
}
function confirm_logged_in() {
if (!logged_in()) {
include "error404.php";
exit;
}
}
confirm_logged_in();
require_once("connection.php");
$query="select * from home";
$homeInfo = mysql_query($query, $connection);
$result = mysql_fetch_array($homeInfo);
$content = $result['content'];
$rssFeeds = $result['rssFeeds'];
$message = "";
if(isset($_POST['submit'])){
$content = $_POST['content'];
$rssFeeds = $_POST['rssFeeds'];
if($content == "" || $rssFeeds == ""){
$message = "Please enter into all the fields";
} else {
$query = "UPDATE home SET content='$content',rssFeeds='$rssFeeds' WHERE id=1 LIMIT 1";
$result = mysql_query($query,$connection);
if(!$result){
echo "error".mysql_error();
}
if ($result == 1) {
header("Location:adminIndex.php");
} else {
$message = "Error Occurred";
}
}
}
if(isset($_POST['cancel'])){
header("Location:adminIndex.php");
}
?>
Use ob_start() at the top of PHP page;
you need to put an exit() or die() after the header function - otherwise the rest of the script will continue to execute.
The redirection can take a relative or absolute URL. The problem is with the space BEFORE the colon. Try it like this:
header("Location: adminIndex.php");
die();
The problem is that you have echo before your header function.
if(!$result){
echo "error".mysql_error();
}
before your two header("Location:adminIndex.php"), your can't echo anything.

Categories