Redirect after executing code - php

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);

Related

how to save variables after using header function php

After i submit a form and save the info to a database i use the header function to redirect to a more user friendly url but the variable $checkError is not saving, it gets reset after the header redirect. How can i save the variable even if the page gets refreshed?
if(isset($_GET['submit'])){
// get the post records <<
$id = '2';
$title = $_GET['title'];
$link = $_GET['link'];
// database connection
$con = mysqli_connect("localhost", "user", "password", "db_test");
$sql = "INSERT INTO test (id, title, link)
VALUES ($id, '$title', '$link')";
$rs = mysqli_query($con, $sql);
if($rs){
$checkError = '<div class="success">Success!</div>';
}else{
$checkError = '<div class="error">Not working!</div>';
}
mysqli_close($con);
//redirect to user friendly url
header("Location: /index.php?id={$id}");
}
You can write this to session data and recall it later, as one potential solution.
Modify/add in your example code block:
session_start();
if($rs){
$_SESSION['checkData'] = '<div class="success">Success!</div>';
}else{
$_SESSION['checkData'] = '<div class="error">Not working!</div>';
}
header("Location: /index.php?id={$id}");
And back on index.php, you would need to add/modify:
session_start();
if( isset( $_SESSION['checkData'] ) ){ // check whether it's set
echo $_SESSION['checkData']; // output variable
unset( $_SESSION['checkData']; // reset variable
}
You can use $GLOBALS OR $_SESSION as an array for $GLOBALS more details click here
you can use it as the below code in your header file
set value in $GLOBALS
$GLOBALS['checkError'] = '<div class="success">Success!</div>';
get value from $GLOBALS
echo $GLOBALS['checkError'];
Another way, very easy to implement is to skip $checkError variable and redirect user to a specific page:
// ...
$rs = mysqli_query($con, $sql);
mysqli_close($con);
$page = $rs ? 'success' : 'failure';
header("Location: /{$page}.php?id={$id}");
You have to store your data in cookies or sessions before the redirect.
A session is also used to store data, but I suggest you store data in cookies because the session stores data on the server-side, creating performance issues, whereas cookie stores data on the client-side.
You can check the critical difference of Cookie and Session
first.php
<?php
if($rs){
setcookie('checkError', '<div class="success">Success!</div>');
}else{
setcookie('checkError', '<div class="error">Not working!</div>');
}
?>
second.php
<?php
if(!isset($_COOKIE['checkError'])) {
echo $_COOKIE['checkError'];
}
?>
I hope this is helpful to you.

redirect if session doen't exist

i m trying to redirect to attempt page if user fills incorrect information...
on the other hand if attempt page got refreshed want it to be redirected on login page...
i m using session for that...
if (isset($c))
{
$q = mysql_query("select * from registeration where email='$a' and password='$b'");
$r = mysql_num_rows($q);
if($r)
{
$_SESSION["Authenticated"] = 1;
$_SESSION['id'] = $a;
}
else
{
$_SESSION["Authenticated"] = 0;
$_SESSION["att"] = 1;
}
if(isset($_SESSION["att"]))
{
header("location:attempt1.php");
}
else
{
session_write_close();
header('location:profile.php');
}
}
the above mentioned code is redirecting on attempt1.php
but code on attempt1.php redirecting back to index.php
session_start();
if (!isset($_SESSION["att"]))
{
echo "<meta http-equiv=\"refresh\" content=\"0; url=index.php\">";
}
i want attempt1.php code to redirect on user on index.php if session is not set..
and destroy session on refresh or direct page load...
so that direct access to this page results in redirection to index page
please help friends..
ANSWER ANSWER ANSWER
all the questions i asked i made silly mistakes...
here in this question i had not started session wile storing session variables....
add the below code in first line of login script
session_start();
//try this code
<?php
session_start();
if (!isset($_SESSION["att"]))
{
header("location: index.php");
}
?>
I think your asking to redirect if a session doesn't exist, since a session requires an ID you should be able to check against that:
if(!(session_id()) header("Location: /mypage.php");
Try this:
if(empty($_SESSION))
{
header("Location: /mypage.php");
}
else
{
// do something ....
}
-
Thanks

unable to forward pages in 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;

Make a div visible from an outside php

I'm working on a log in session, and I want to display errors on the same page, for example - "Invalid Password" or "User does not exist".
Heres my code:
<?php
session_start();
mysql_connect('mysql.database.com','user','database')or die ('Connection Failed: '.mysql_error());
mysql_select_db('database')or die ('Error when selecting Database: '.mysql_error());
function remove($mensaje)
{
$nopermitidos = array("'",'\\','<','>',"\"");
$mensaje = str_replace($nopermitidos, "", $mensaje);
return $mensaje;
}
if(trim($_POST["usuario"]) != "" && trim($_POST["password"]) != "")
{
$usuario = strtolower(htmlentities($_POST["usuario"], ENT_QUOTES));
$password = $_POST["password"];
$result = mysql_query('SELECT password, usuario FROM usuarios WHERE usuario=\''.$usuario.'\'');
if($row = mysql_fetch_array($result)){
if($row["password"] == $password){
$_SESSION["k_username"] = $row['usuario'];
header( 'Location: diseno.php' ) ;
}else{
echo '<p class="message2">Invalid password</p>';
}
}else{
echo '<p class="message2"User does not exist</p>';
}
mysql_free_result($result);
}else{
echo '<p class="message2">Must enter a user and password</p>';
}
mysql_close();
?>
<SCRIPT LANGUAGE="javascript">
location.href = "index.php";
</SCRIPT>
As you can see that's my validation and action for the log in form. Instead of echoing errors in a new page I want to display it in the same page. I tried with javascript and it didn't work I used.
var page = document.URL = "http://www.mysite.com/login.php"
page.getElementById( 'wrongpassword' ).style.display = 'block';
All divs I want to display are set as none in the login.php file.
Anyone could help me?
The easiest way to accomplish this is to process the login and then include the PHP code which displays the normal page. I'm not sure how you've designed your site, but including index.php at the end might do the trick. Right now, you are using a JS redirect, which won't give you the result that you want.
Instead of echoing the message, I like to set a $message variable which includes the message. When you render the main page, simply echo this variable in the appropriate place if it is set.
For doing it simply you can make use of JQuery. I have done it on my website so I can say it really works.
Start your session, checking the values and either assign the value in global variables of javascript or print it there only
eg.
<?php
session_start();
//checking ur values
echo "<script src=\"js/jquery-1.8.3.min.js\"></script>
<script type=\"text/javascript\">
$(document).ready(function(){
//you can assign values here or print error messages to any div
('.div_class').html("unuthorised user");
});
</script>";
?>
Here I have used a downloaded JQuery file from
http://jquery.com/download/
You can choose other wise to use the online version of this JQuery file. The syntax for that is
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
Feel free to get back in case of any further query/issues regarding the above code.

PHP header(Location: ...): Force URL change in address bar

I'm currently working on a mobile site with authentication using PHP sessions with a database.
I have a login page with a form that goes to server_login.php on submit. The php file then creates some session data (store in $_SESSION), and redirects the user back to the index page:
header("location:../../index.php");
The new web page (index.php) loads correctly; however, when the header redirects the page, the URL at the address bar is not changed; it stays at *http://localhost/php/server/server_login.php* instead of http://localhost/index.php and thus all my other resources that makes use of relative pathing could not be loaded. It's as if the web page still thinks that it resides at /php/server instead of /.
Strangely, my other use of header("location: ...") at logout.php works and redirects the page successfully with a URL change.
I've made sure that there are no outputs in my *server_login.php* before the header redirect (above it are just mysql calls to check) and I've used ob_start() and ob_end_flush() too.
Are there any methods of forcing the URL on the address bar to change (and thus hopefully fix the relative path problem)? Or am I doing something wrong?
P/S: I am using jQuery Mobile.
EDIT: Here's my code for the redirection that doesn't change the URL:
// some other stuff not shown
$sql = "SELECT * FROM $user_table WHERE email = '$myemail' AND password = '$mypassword'";
$login_result = mysql_query($sql, $connection);
$count = mysql_num_rows($login_result);
if ($count == 1) {
// Successfully verified login information
session_start();
if (!isset($_SESSION['is_logged_in'])) {
$_SESSION['is_logged_in'] = 1;
}
if (!isset($_SESSION['email'])) {
$_SESSION['email'] = $myemail;
}
if (!isset($_SESSION['password'])) {
$_SESSION['password'] = $mypassword;
}
// Register user's name and ID
if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id']))) {
$row = mysql_fetch_assoc($login_result);
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
}
header("Location: http://localhost:8080/meet2eat/index.php");
} else {
// Not logged in. Redirect back to login page
header("Location: http://localhost:8080/meet2eat/php/login.php?err=1");
}
Try changing:
header("Location : blabla")
^
|
(whitespace)
To
header("Location: blabla")
Well, if the server sends a correct redirection header, the browser redirects and therefore "changes the url". It might be a browser issue, then.
I don't know if it has anything to do with it, but you should not send a relative url in the location header ("HTTP/1.1 requires an absolute URI as argument to ยป Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. ", http://php.net/manual/en/function.header.php), and "location" must be capitalized, like:
header('Location: http://myhost.com/mypage.php');
In your form element add data-ajax="false". I had the same problem using jquery mobile.
Do not use any white space. I had the same issue. Then I removed white space like:
header("location:index.php"); or header('location:index.php');
Then it worked.
you may want to put a break; after your location:
header("HTTP/1.1 301 Moved Permanently");
header('Location: '. $YourArrayName["YourURL"] );
break;
I had the same problem with posting a form. What I did was that turning off the data-ajax.
Are you sure the page you are redirecting too doesn't have a redirection within that if no session data is found? That could be your problem
Also yes always add whitespace like #Peter O suggested.
I got a solution for you, Why dont you rather use Explode if your url is something like
Url-> website.com/test/blog.php
$StringExplo=explode("/",$_SERVER['REQUEST_URI']);
$HeadTo=$StringExplo[0]."/Index.php";
Header("Location: ".$HeadTo);
Just change home to your liking
$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/home';
header('Location: ' . $home_url);
// Register user's name and ID
if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id']))) {
$row = mysql_fetch_assoc($login_result);
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
}
header("Location: http://localhost:8080/meet2eat/index.php");
change to
// Register user's name and ID
if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id']))) {
$row = mysql_fetch_assoc($login_result);
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
header("Location: http://localhost:8080/meet2eat/index.php");
}
As "cfphpflex" suggested you can add break; after setting the header. You can also echo something, such as echo 'test';.
Add exit at the end of header then it will work
header("location:index.php"); or header('location:index.php'); exit;
You are suppose to use it like header(Location:../index.php) if it in another folder
use
header("Location: index.php"); //this work in my site
read more on header() at php documentation.
why all of this location url?
http://localhost:8080/meet2eat/index.php
you can just use
index.php
if the php files are in the same folder and this is better because if you want to host the files
or change the port you will have no problem reaching this URL.

Categories