PHP. How to find the previous page? - php

I would like to know what page redirected to the current page on my system.
For example. If the system stopped in the page current.php.
How to know what page called current.php?
Is there a function to perform this?

$_SERVER['HTTP_REFERER'] can contain the URL of the page the user agent was previously on, but it can be spoofed or empty.

You don't have a reliable way of doing that.
If you're expecting the redirecting page to be on your server, you can set a $_SESSION variable to the current page on every page you visit, that way, you can check for it on the next page (before resetting it of course).

Maybe there are better solutions, but you could use a hidden field inside a form to transfer this information between pages inside your system, or use GET vars in your URL.
Rhis way you can keep track of certain states during page changes, that u are interested in.
But u would also need to update every page to handle the additional variables.

Related

php variables - best way to pass variables over to another php page

So I am aware of these two common ways of passing variables across php pages.
1. PHP SESSIONS
I understand that $_SESSION is a php global variable that can hold variables across php pages during the session of the browser.
It works well but my concern with it is if a user for what ever reasons, decides to type the url of a page or goes into their history and accesses a url page for the website, the $_SESSION variable may not be set, if it was expecting the user to get to this page from a set route/path.
In addition, if a user goes into another page, and the page sets an already defined $_SESSION to another value, and then decides to go back to the previous page, the $_SESSION variable is not correct for that page, causing many errors.
2. URL passing
This is by far the most reliable in my opinion. The only concern I have with this, is the pages can get rather messy with long URL's.
page1.php?postId={variable goes here}
passing 4,5 or 6 variables can get a bit messy, I also need to encode then or encrypt them. The URL can get rather long, and I am not sure how I feel about passing variables across the URL.
My Question:
What is the best way to pass variables from one php page to another. Are the two methods above the best way to go about it, or is there another my efficient way. Also if efficiency isn't the issue, then what is the most secure procedure/method.
Thanks for your time.
This is largely going to depend what you're trying to do? $_SESSION variables and $_GET variables largely have different purposes in web programming (although, yes, you could force some sway between the two).
The question you need to ask yourself is "is the variable storing information on the user OR directing the webserver to do something" if it's the former then use $_SESSION if it's the latter then $_GET.
You wouldn't for example want to pass loggedon=true as a GET variable (ignoring the security implications) because you would have to update every single link on the page to have the query string appended to it which, as you say, would lead to some untidy URLs.
SESSION
Is most commonly used for storing information about a user. Some examples:
Log on status
Shopping basket
Session preferences
For example when a user is successfully logged on you will want some way to remember that between page loads:
session_start();
$_SESSION["loggedon"] = true;
In every subsequent page request you can then check:
session_start();
if(!$_SESSION["loggedon"] ?? null){
echo "ERROR: You shouldn't be here!";
exit;
}
Note that $_SESSION is only accessible to the server, can't be directly accessed by the website user, and is persistent until the session closes.
GET
On the other hand is sent with every request and is typically used when you want to pass non-sensitive information from the user to the webserver. Some examples:
Language preferences
User input (e.g. a search query when using a search engine)
Forgotten password secure codes
Suppose you have a cookery website and 1000 recipes. You would likely only have one page to show the recipe and pass a GET variable in the URL to indicate which recipe should be loaded
http://www.mycookingwebsite.com/recipe.php?recipeid=477
Note that GET requests are visible to the user, can be modified, and show up in history etc. as well.
N.B. Do not pass sensitive details (e.g. username/password) over GET - not least because they would show up in the browser history!
You mention passing variables from one page to another. But I'm not quite clear on whether you mean Server->Server (SESSION) OR Client->Server(GET)?
An example of this all coming together would be in the case of a shopping cart:
At the back end you have an array stored in your session with the items in the cart, this is persistent throughout the session. On the client side you have the ability to send a GET (most people would probably POST) request to tell the server about the new product you want to add to the list.
If your primary concern is that users may find themselves at the wrong "stage" then I suggest building in some checks to make sure that they are in the right place at the right time.
For example given a quiz with 10 questions... If the user clicks a link which drops them at question 5 you check to see if they've already answered questions 1-4 and then act appropriately depending on the answer.

A way to redirect user back to specific page when URL is typed in PHP

I have a PHP website of 6 pages and I want to have a functionality such as this:
The website is a little quiz game where you need to get through 5 trivia questions per page and the final page displays the highscore. The score is based on how fast you got there as the pages have a timer.
But I found out about a cheat I want to fix. If you simply type in the URL highscore.php or question5.php, you can get there faster without having gotten through the first few pages.
Is there some way to fix this?
Track the state of the quiz on the backend, e.g. track which questions have been answered yet. When the user tries to access a page that would require a previous page to be completed first, redirect the user to that page instead.
You can achieve this with a Session.
An even better solution than having six pages would be to have one page instead, e.g. quiz.php and then funnel all access through this page. This will make it easier to track progress because you don't need to copy and paste the code to the individual pages.
On a side note: you also want to track the time the quiz was started on the backend.
It's not that hard, just a careful coding is all you require.
Firstly, start a session and set it to an initial value, say 1, that means the user is in page 1. If he submits the answer, and then the user loads any other page in your website, create a script to call the same session value and use header("Location:page2.php")to force a redirect to page 2 or the page he is supposed to be in.
If the session is removed somehow then use isset() to check if it exists, if it doesn't start from the beginning.

How to echo the last visited page in PHP?

I don't know is there is a PHP function like the ones that start with $_SERVER['']
That tell user which page he came from, on his current page.
ex. If I was browsing foo.com?id=abc then went to foo.com?id=efg, I need the current page to tell me that I came directly from foo.com?id=abc
I need this code badly, so any help is appreciated.
It is $_SERVER['HTTP_REFERER']. But it is filled only if browser did so. Otherwise you need to track user yourself (i.e. by storing last page in session)
The $_SERVER variables should not be relied upon to provide accurate answers. You should use PHP Sessions to track what page they come from, and simply update it everytime they go to a new page. Something along the lines of:
session_start();
if(!empty($_SESSION['visited_pages'])) {
$_SESSION['visited_pages']['prev'] = $_SESSION['visited_pages']['current'];
}else {
$_SESSION['visited_pages']['prev'] = 'No previous page';
}
$_SESSION['visited_pages']['current'] = $_SERVER['REQUEST_URI'];
Then to access the previous page, access the: $_SESSION['visited_pages']['prev']
The HTTP_REFERRER gives address of the page that requested the file. For example an image on a page is a separate request, and this request has a $_SERVER['HTTP_REFERRER'] set to the page.
I don't think browsers allow servers to access history. It can be done with JavaScript, though only a back button can be provided, the url cannot be accessed easily. Though it can be achieved using a simple css and javascript trick by accessing the computed color to a link.
Yes, and this is not only in PHP, this is a part of the HTTP protocol specification, Use:
$_SERVER['HTTP_REFERRER']

How can I pass variables in PHP from the same page?....logical thinking puzzle

so I've hit a potential problem in my site....it's a post-based system, with the posts being in text files. Uses some Javascript and a lot of PHP.
When you make a submission on the form on the homepage, you are sent to a page where data is posted and processed, but you don't see it because you get redirected back. Then the homepage is changed based on what the post you made says. All that was working fine.
But now I'm trying to add a new feature that modifies the post you made, based on a button you hit which submits a hidden form using javascript, and sends to another process and redirect page you don't see, and it works fine until the block that I realized today. I don't know how to specify that the post being altered is the right one.
I anticipate a good amount of users of this site, so my concern is what if user X makes a post while user Y is making a post, and the post of user X becomes the top post, so user Y's options actually change user X's post.....
I was thinking of adding to the main processing page (the one that happens when you first submit) a COOKIE or something that would make note of the number of the line that post will become, by counting the number of the lines in that file at the time and adding 1 to it. Then checking it against the user's number (each user has a number) to see if it's that user's most recent post....but the problem is I don't know how I would pass that value around to be read in the next page.
Setting a COOKIE is out I think because the page both redirects, AND reads and writes to files. The only output to the page though are currently var_dumps.
POST/GET is out because to my knowledge the user would have to do SOMETHING to submit it, and the user's not even going to see the page.
Writing to a file would be messy if lots of users are trying to get their own data.
I think what I may be looking for is SESSION variables...but I don't know anything about those except that they're used to login to pages, and this site has no login.
To make things more fun, when a user posts the same content within a minute of another user, the first user's post is replaced and it gets a little +1 next to it...which makes it harder to check it against the user's number....
AND in the end I'm trying to use AJAX (which I dont know yet) to make the updates in real-time...now THAT is going to suck. But for now I'm worried about my static little site.
Baby steps.
Any ideas how to go about this??
Use Session variables, just as you have alluded. They aren't just used by login pages, they are used by everything. Sessions are the equivalent of server-side cookies / server-side storage, so you don't have to worry (as much) about your users tampering with them.
If you want to make life more difficult for yourself, you can json encode your variables and store them as an object in a database or even flat text file. But really, read up on sessions.
All you need to know is session_start(); before anything else then $_SESSION['var']=$yourvar; to save data and $_SESSION['yourvar'] to retrieve it later (such as on another page).

Implementing a 'Email to a friend' functionality. How to pass variables to the next page without using form, session and cookies?

I'm trying to create a "Email to friend" page using php. The objective of this page is that users can share the page that they are viewing with their friends.
When a user clicks on the 'share' link, it'll redirect user to a page that asks a user to input their own email address and a recipient email address. The subject will be the previous page title and the email body will be the URL of the previous page plus whatever a user may want to include.
I've got the whole concept here but I'm stuck on the implementation stage. I can't seem to figure the best way to pass the previous page title and the page URL to the share page.
Here's what I have thought of so far.
Using POST and GET method doesn't
seem to fit in because there is no
forms involved when a user clicks on
the share link.
Using session and cookies would be
very tedious as it requires assigning
and modifying the cookie / session
each time a user views a page.
Passing variables in URL would make
simply make the URL long and somewhat
undesirable.
Is there any other way that I could use to pass the page title and page url to the next page? I'm open for other suggestions on how I could implement this idea differently. Thanks in advance.
As far as I can see, passing the URL as a GET parameter is indeed the ideal solution.
http://example.com/share.php?url=http%3a%2f%2fwww.example.com
note that
You need to URL-encode the URL you are passing using urlencode()
the total resulting URL should not be longer than 2-4 kilobytes due to restrictions in some browsers.
I don't understand why POST and GET are not an option. Just because there isn't a form on the page doesn't mean you can't put one there. Can the link be turned into a button? If you don't like the look of a button, use CSS. Putting a form on the page would only take a few lines.
I would go for the session approach, even though you consider it tedious. This is called "flash messages" and it's quite commonspread. Zend Framework has these out of the box, CodeIgniter has a neat contributed library for it... Basically, you just need to write a few helper functions and you're set. To get the barebones functionality, you need:
adding a new message
retrieving a message/all messages
clearing messages (could be called after fetching messages)
The messages stored in the session will persist until you clear them, they are immune to redirecting and once you write your helper functions, it'll be as easy as:
//before redirect:
setFlash('You have successfully logged in!');
//after redirect
echo fetchFlash();
clearFlash(); //if fetchFlash doesn't call it automatically
So I wouldn't call it tedious, really. Rather a butt-saver.

Categories