Refresh Page after update php - php

i need a javascript to help me refresh my page after i update the data. i have coded out t
he update function all i need to refresh the page after the data is updated how do i do that.
This is what i have done so far
<?php
mysql_connect("localhost","fbappsadmin","dbP#ssw0rd") or die(mysql_error()) ;
mysql_select_db("jetstardatabase") or die(mysql_error()) ;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$options = array(
'1' => 1,
'2' => 2,
);
if (isset($_POST['list'])) {
$value = (int)$_POST['list'];
} else {
$value = 0; // default value;
}
$cmeter = $cmeter - $value;
mysql_query("INSERT orders SET quantity='$value',fbId='$fbme',fbName='$fbName', email ='$fbEmail', dealName='$dealName'" );
mysql_query("UPDATE stardeal SET cmeter='$cmeter'WHERE dealId='$dealId'");
}
?>

Just put this PHP at the end of your update logic, it must be before any HTML output;
header("Location: /mypage.html");

Web pages work like this:
page (client) -> request (made in url) (server) -> new page (client)
By sending a request to the server, the server generates the new page and serves it back to the browser. You have the middle part, you need the entry and exit pages.

Like blake said, ajax or PHP would probably be prefered. Otherwise, to answer your question, you can use:
document.location = window.location.href

If you need javascript, then use this code:
<script>window.top.location='mypage.html'</script>

You cannot refresh your browser page using PHP. You have to use either META or Javascript.
Using Meta tag inside <HEAD> and </HEAD>:
<meta http-equiv="refresh" content="0; url=http://example.com/">
Using Javascript:
location.reload(true)

Related

Meta refresh enters into infinite loop

I wrote the following code to delete entries on my SQL table:
echo "<td><a href='protected_page.php?action=delete&id=$id'>Borrar</a></td>";
}
if(($_GET['action'] == 'delete') && isset($_GET['id'])) {
$rem = "DELETE FROM busca WHERE id = '".$_GET['id']."'";
$mysqli->query($rem);
if($rem) {
echo "<meta http-equiv='refresh' content='0;URL=/protected_page.php'>";
}
}
Once I click the delete link the page enters into an infinite loop.
Look at your attribute value:
content='0;URL='/protected_page.php''
You are delimiting the value with ' but trying to use ' characters as data inside it.
This isn't possible so what you are really saying is:
content='0;URL='
The correct syntax is:
<meta http-equiv='refresh' content='0;URL=/protected_page.php'>
… without the quotes around the URL portion.
That said, meta refresh is a nasty approach to performing a redirect. An HTTP redirect is better:
<?php header("Location: /protected_page.php"); ?>
You will need to adjust your logic a little. HTTP headers have to be output before the HTTP body, and you're doing your delete & redirect logic in the middle of your HTML output.
As a rule of thumb it is better to put all your business logic (deleting things, fetching data from the database, etc) at the top of your PHP program, and then leave all the business of generating HTML and other output (using variables you populated in the business logic part at the top) at the bottom.
If you really want to use PHP for this, here you go:
//0 = is second after is refresh
<?php header("Refresh: 0; URL=http://redirect-url"); ?>
If You Want Use HTML for This, Here you Go
//0 = is second after is refresh
<meta http-equiv="refresh" content="0;http://redirect-url" />
use header instead of meta tag as below
if($rem) {
header( 'Location: protected_page.php' );
}

Continuously updating php page

I have created a php page to display a image from a set of five images. The image is displayed based on the data read from a text file.Another application is continuously updating data in that text file.So my php page need to read data from that file whenever the file is updated and display image based on that data. I created a infinite loop to read data. But when i tried to access the php page from a browser , it is not loading because of the infinite loop.
$myfile1 = fopen("readfile.txt", "r") or die("Unable to open file!");
$readJsonData = fread($myfile1,filesize("readfile.txt"));
fclose($myfile1);
$obj = json_decode($readJsonData);
$urllogo = 'tatalogo.png';
if(($obj->{"FrontLeft"}) == "TRUE")
{
$url = 'images/FrontLeft.png';
}
else if(($obj->{"FrontRight"}) == "TRUE")
{
$url = 'images/FrontRight.png';
}
else if(($obj->{"RearLeft"}) == "TRUE")
{
$url = 'images/RearLeft.png';
}
else if(($obj->{"RearRight"}) == "TRUE")
{
$url = 'images/RearRight.png';
}
else
{
$url = 'images/Normal.png';
}
// infinite loop
while(1)
{
//reading from the file and refreshing the page.
}
In PHP Set header like this to refresh the php page
header("Refresh: 5;url='pagename.php'");
In HTML Head tag
<html>
<head>
<meta http-equiv="refresh" content="5;URL='pagename.php'">
</head>
</html>
<?php
Your php script here..
?>
Using Javascript
<script type="text/javascript>
window.setInterval(function(){
reload_page();
}, 5000);
//Here 5000 in miliseconds so for 5 seconds use 5000
function reload_page()
{
window.location = 'pagename.php';
}
The most reasonable way to do it would be to use the client side to refresh the page.
Get rid of all that infinite loop stuff on the PHP side. PHP will only output the image as it stands at the moment it was generated.
On the client side you could do something as simple as:
<META http-equiv="refresh" content="5;"> to force a refresh every 5 seconds.
If you only want to update when the file is updated you have to get more advanced. You could do an ajax call that checks if the file has changed and if so it refreshes. Websockets would be another option.
You could possibly do some nasty hack on the PHP side to make it work using ob_flush and sleep and header within a loop that checks to see if the file has changed but this will cause you to lose sleep once you realize what you've done. As pointed out below, this would never work.

View full site with cookies, javascript and mobile redirect

I have a website(www.website.com) and a mobile site (m.website.com) and I'm trying to allow users to "View Full Site" if they want from mobile. Currently I am using some Javascript to check screen width on full site then redirecting to mobile.
if (screen.width <= 699) {
document.location = "http://m.website.com";
}
This works fine. On the mobile site there is a "View Full Site" button. When you click this it redirects you to my script "force_desktop.php" which sets a cookie and then sends you to the main site.
<?php
setcookie("force_desktop", "1");
header("Location: http://www.mywebsite.com");
?>
Now that we set a cookie and redirected to the main website we need to check for the cookie instead of just checking for the screen width.
Logic
If Cookie force_desktop is found
Then exit
Else
run screen size test
Here is the code I attempted to use but doesn't work. This code is placed in my head.php file which will be run on every page and is placed between the script opening and closing tags.
Attempt 1
if($_COOKIE['force_desktop'] == '1' {
exit;
} else if($_COOKIE['force_desktop'] != '1' {
if (screen.width <= 699) {
document.location = "http://m.website.com";
}
};
Attempt 2
if(isset ($_COOKIE["force_desktop"])){
exit;
else
if (screen.width <= 699) {
document.location = "http://m.mywebsite.com";
};
Alternative logic that could work
IF Cookie force_desktop is not found AND screen.width <= 699
Then redirect to m.myseite.com
Else
Exit
Note
I have run the following script to make sure a cookie is being placed, and it is.
<?php
print_r($_COOKIE);
?>
I've run out of ideas and know my coding isn't correct, especially the If/Else statement within the If/Else statement. I also am not sure if it is better to use the "isset" to see if the cookie is being used or ($_COOKIES['variable'] == "#"). I'd really appreciate some good feedback on this one.
Thanks in advance for your help and suggestions,
Matt
You're mixing JavaScript and PHP. You're trying to use screen.width in your PHP script, which doesn't make sense. You need to use an echo statement to output the JavaScript into the page. It'll then check the user's screen resolution and do the redirect.
Try this:
if(isset ($_COOKIE["force_desktop"])){
exit;
}
else
{
echo '<script>
if (screen.width <= 699) {
document.location = "http://m.mywebsite.com";}
</script>';
};
you should do this test at the top of the php page, and for sure you cannot mix php and java script like this
u can alter this code like
<?php
$flag = 0;
if(isset($_COOKIE['force_desktop']))$flag++;
?>
later in the page use the code as soon as <head> tag starts
..
..
<head>
<?php
if(!$flag){
echo '<script>
if (screen.width <= 699) {
document.location = "http://m.mywebsite.com";
</script>';
}
?>
You cannot mix javascript and PHP, javascript is front end and PHP is back end. Try something like this:
if( $something ){
Header("Location: somewhere.php");
}

Remove querystring value on page refresh

I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!

Help with PHP if / else statement

On my site, forms are brought in via AJAX and checked against a sessionid. I know this is not optimal, but it's working for us. If the referrer doesn't have the session ID they are redirected back to "anotherpage". I need to allow some outside URL's access the form directly.
we set the sessionid on the page with the link to the form.
Here is what we have now on the form page:
<?php
$code = $_GET['sessionid'];
if(strcmp( $code , 'XXXXX' ) != 0) {
header("Location: http://www.domain.com/anotherpage.php");
}
?>
I need to allow some outside domains direct access to the form page and am having issues with this:
(I'm putting it above the head tag on the form page)
<?php
$code = $_GET['sessionid'];
$referrer = $_SERVER['HTTP_REFERER'];
if(strcmp( $code , 'XXXXX' ) !=0) {
header("Location: http://www.domain.com/anotherpage.php");
} else {
if (preg_match("/site1.com/",$referrer)) {
header('Location: http://www.domain.com/desiredpage.php');
}
}
?>
this still bounces me back to "anotherpage.php" any ideas?
********EDIT*******
thx for the help, it works ad I requested. Now I see what I asked wasn't entirely correct. This appends the URL with =sessionid?=XXXXX. This isn't an issue on my site because I'm loading the content with .jquery .load so the URL doesn't change. I don't want the sessionid to be visible, and now it is. Can I either a) "trim" the url somehow or b) separate the two functions so they are exclusive?
if(strcmp( $code , 'XXXXX' ) !=0) {
if (preg_match("/site1.com/",$referrer)) {
header('Location: http://www.domain.com/desiredpage.php');
} else {
header("Location: http://www.domain.com/anotherpage.php");
}
}
As I read your post, you want anyone from the preg_match to get the desired page regardless of sessionID status, so you don't want to test sessionID first.
Start the if block with the preg_match test.
Your first if is checking to see if they don't have the $code and redirecting them. This will always be the case. You should probably check the $referrer first and then do the $code check.
Try reverse if with else
<?php
$code = $_GET['sessionid'];
$referrer = $_SERVER['HTTP_REFERER'];
if (preg_match("/site1.com/", $referrer)) {
header('Location: http://www.domain.com/desiredpage.php');
} else if (strcmp( $code , 'XXXXX' ) != 0) {
header("Location: http://www.domain.com/anotherpage.php");
}
?>
If I'm not misunderstanding this, the problem is in the order in which you are checking things.
If you want to allow some referrers to access the site even if they don't have the session id, you have to check for that before checking for the session id. Otherwise, they will end up being treated just like everyone else.
You can either switch the order of the conditions (first check for the referrer and then check fo the session id) or check for the referrer inside the branch in which you already know the session id is not valid.
The issue could be in your regex, it should be:
if (preg_match("/site1\.com/",$referrer))
notice escaping the dot (.)

Categories