unable to forward pages in php - php

I have a php page. when users click on edit button then my all other fields data is apperaing the respective textbox, and also if he submits the form my data is updating. But my problem is it is not forwarding to my respected page.
i denoted it like this header('Location: /profile.php'); for forwarding it in my profile page
What could be the reason?
My full code:
<?php
include '../../../include/connection.php';
$idd =$_REQUEST['id'];
$resultt = mysql_query("SELECT * FROM budget WHERE budget_id = '$idd'");
$test = mysql_fetch_array($resultt);
if (!$resultt)
{
die("Error:<font color='red'> Data not found..</font>");
}
$budget_id=$test['budget_id'];
$heads_id=$test['heads_id'];
$amount= $test['amount'];
$from_date=$test['from_date'];
$to_date= $test['to_date'];
if (isset($_POST['submit'])) {
$headsid=$_POST['headsid'] ;
$amount= $_POST['amount'] ;
$todate=$_POST['todate'] ;
$frmdate= $_POST['frmdate'] ;
mysql_query("UPDATE budget SET heads_id ='$headsid',amount ='$amount',from_date ='$frmdate' ,to_date ='$todate',updater_id ='$uid',updated_date=NOW() WHERE budget_id = '$idd'")
or die(mysql_error());
header('Location: /profile.php');// PROBLEM HERE UNABLE TO FORWARD TO THE PAGE
}
?>

header('Location: profile.php');
die;

strip or remove the backslash.
header("Location: http://example.com/path/path/profile.php");
exit;

Related

Redirect if sql column has a specific value

Am new to php, so any help would be greatly appreciated. I have a page to create account for users, and while creating account, there is a select field which has three specific value to select from "notfcode" "tfail" **"tfcode".
There is another page check.php which allows the user check his ttype. What i want to do is make the page try to read the sql table row which is ttype and if the value present on the user's account is "notfcode" it redirects to notfcode.php page, if its "tfail" it redirects to tfail.php and if its "tfcode" it stays on the page. below is the code i have been battling with without success.
<?php session_start();
include_once ('session.php');
require_once 'class.user.php';
if(!isset($_SESSION['acc_no'])){
header("Location: login.php");
exit();
}
$reg_user = new USER();
$stmt = $reg_user->runQuery("SELECT * FROM account WHERE acc_no=:acc_no");
$stmt->execute(array(":acc_no"=>$_SESSION['acc_no']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$email = $row['email'];
$temp = $reg_user->runQuery("SELECT * FROM transfer WHERE email = '$email' ORDER BY id DESC LIMIT 1");
$temp->execute(array(":acc_no"=>$_SESSION['acc_no']));
$rows = $temp->fetch(PDO::FETCH_ASSOC);
$transfertype = $row['ttype'];
if(isset($_SESSION['acc_no'])){
$transfertype = $row['ttype'];
if($transfertype == nocodetf){
header("Location: nocodetf.php");
}
elseif($transfertype == tfail){
header("Location: nocodetf.php");
}
else {
header("Location: check.php");
}
}
include_once ('counter.php');
?>
When the page loads up, it does nothing, no redirects which is what i intend. A pointer in the right direction will be appreciated.
This are strings.
if($transfertype == "nocodetf"){
or
if($transfertype == 'nocodetf'){
Activate PHP error reporting than PHP shows you this.
error_reporting(E_ALL);
ini_set('display_errors', 1);
$transfertype = "foo";
if ($transfertype == nocodetf) { # <-- as you did it
//...
}
// <b>Warning</b>: Use of undefined constant nocodetf - assumed 'nocodetf' (this will throw an Error in a future version of PHP) in ...
I was finally able to resolve it using this code
<?php
$transfertype = $row['ttype'];
if($transfertype == 'nocodetf'){
header('Location: nocodetf.php'); }
else if($transfertype == 'failtf'){
header('Location: failtf.php');
exit();
}
?>
The problem seemed to be in the fact that i wasn't quoting the value which php should try to get from the sql column.

Redirect after executing code

I want this PHP code to redirect to the previous page and refresh automatically...
I understand that with JavaScript I can go history back but it won't refresh.
Please help.
My code:
<?php
$con=mysqli_connect("host","user","pass","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//post result to db
$result_set = mysqli_query($con,"SELECT points FROM total WHERE id = 1");
$row = mysqli_fetch_assoc($result_set);
$old_total = $row['points'];
$new_total = $old_total + $_REQUEST['total'];
mysqli_query($con,"UPDATE total SET points = $new_total WHERE id = 1");
mysqli_close($con);
?>
Get the url in a session, when you want to redirect, just use that url and redirect the user and unset the session var
//Track this on the page you want to redirect your code
$_SESSION['prev_url'] = $_SERVER['REQUEST_URI'];
On the next page use this
//When you want to redirect to previous page
header('Location: '.$_SESSION['prev_url']);
exit;
Be sure you are declaring session_start() at the top of the page
To redirect with php:
<? header("location: http://.........."); ?>
Please note that before this instruction you mustn't print html, if some html is printed your header will not be sent
add
header("Location: " . $_SERVER['HTTP_REFERER']);
exit;
you can use javascript code :
forward: window.history.go(+1)
backward: window.history.go(-1)
or jquery code:
forward: history.go(1);
backward: history.go(-1);

echo out message after redirect?

I have a button on users profiles that allows another user to add a user to their favorites.
Once this button is clicked they are linked to the sql process file favorite.php.
Once the sql script has run it links the user back to the original profile page which is profile.php.
now what i want to do is find out how i can echo a message on the page profile.php after the sql has completed. I've tried the following but nothing happens.
can someone please show me what i'd need to do to get this working? thank you
favorite.php:
<?php
require_once('includes/session.php');
require_once('includes/functions.php');
require('includes/_config/connection.php');
session_start();
confirm_logged_in();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
if (!isset($_GET['to']))
exit('No user specified.');
$user_id = $_GET['to'];
$result = mysql_query("INSERT INTO ptb_favorites (user_id, favorite_id) VALUES (".$_SESSION['user_id'].", ".$user_to_id.")")
or die(mysql_error());
header("Location: profile.php?id=" . $user_to_id['user_id'] . "added=1");
?>
profile.php:
<?
if (isset($_GET['added']) && $_GET['added'] == 1) {
$message = "<div class=\"infobox\">This user was successfully added to your favorites.</div>"; ?>
<? } ?>
Your redirected URL will look like this:
profile.php?id=123456added=1
# ^
Notice the missing & in the parameters. Adapt your header() call and include it before the "added=1" concat.
header("Location: profile.php?id=" . $user_to_id['user_id'] . "&added=1");
# ^
On a related note, you would have found out earlier if it wasn't for that isset:
if (isset($_GET['added']) && $_GET['added'] == 1) {
Leave it out, as this is a required param and you want to get a note for such occassions. Instead just turn of notices/warnings on your production server.

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 .

Refresh button on Browser

I have a simple coding problem. I try to create a page with a textbox and a share button.
When the user clicks the share button the text in the textbox get inserted as string into the database table named "posts".
I use the following code.
<?php
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
else
echo "<script type='text/javascript'>alert('some error')</script>";
}
else
{
?>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
Status : <input type = "text" name ="status">
<input type = "submit" name ="share">
</form>
<?php
}
This solution works fine but there is a problem when the user refreshes the page. The browser will show a message window asking for resend the information, which will submit the post to the table again. Then the same entry is in the table twice.
I want the user to stay on the same page after submitting. But a page refresh should not show the message window or send the information again.
Thanks in advance!
Redirect the user after he shares, use redirect
header('Location: whatever.php');
exit;
Use this :
<?php
if(isset($_POST['share'])) {
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res) {
?>
<script type='text/javascript'>alert('Posted successfully')</script>
<?php
header('Location: whatever.php');
exit;
} else {
?>
<script type='text/javascript'>alert('some error')</script>
<?php
header('Location: whatever.php');
exit;
}
}
?>
And btw better don't alert the users using javascript
AND DO USE BRACES AROUND IF ELSE
P.S : You Can Also Redirect An User Using JavaScript window.location
Header Reference
It's called "redirect-after-post": After you received the post request and did something useful with it, you redirect the user (usually) back to theire own post, or whatever.
You can try doing redirect just after your logic saving the post is done.
header("location: $my_page");
exit();
Set variable $your_page with the name of page which contains your code
$my_page = 'yourpage.php';
This should work:
$my_page = 'your_page.php'
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
{
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
header("location: $my_page");
exit();
}
else
{
echo "<script type='text/javascript'>alert('some error')</script>";
header("location: $my_page");
exit();
}
}
Right after you have finished inserting your query and everything, change to another page using:
<?php
header('Location: /path/to/yourotherpage.php');
exit();
?>
What this does, is it is a redirect to another page, which removes all POST data from the browser's 'memory' of the page.
On that page, you write something like 'Your stuff has been submitted and recorded', whatever you want, your choice.
If your user refreshes on that page, nothing will be inserted at all.
That should work.

Categories