My website's webpages displays webpages by using GET to retrieve variables from a predefined URL.
For example the code on the first page: index.php
<p>next page</p>
The second page: blank.php?name1=value1&name2=value2
$name1 = $_GET['name1'] ;
$name2 = $_GET['name2'] ;
echo $name1 ;
echo $name2 ;
This way webpages are created on the spot and displayed kind of like a CMS and Iuse this method for all the webpages my site has, but if a user bookmarks a tab they will have out of date information for that webpage because that page content is contained in the URL.
EDIT: If I were to use post would their be a better way of conveying that information to the new webpage? instead of:
<form method="post" action="blank.php">
<input type="hidden" name="name1" value="value1">
<input type="submit">
</form>
Quick and dirty solution: Add a timestamp parameter to your urls, like:
<p>next page</p>
Then, on the page, check if the timestamp is older then a certain duration:
if(!isset($_GET['time']) || time() - intval($_GET['time']) > 60*60) {
header('Location: index.php');
}
$name1 = $_GET['name1'] ;
$name2 = $_GET['name2'] ;
echo htmlspecialchars($name1);
echo htmlspecialchars($name2);
So if a link is older than one hour (60 seconds times 60 minutes), it is redirected to the home page!
But this method is not very user friendly! You should better try to build your links so they never get old content when visiting!
You could prevent the user from using the keyboard shortcut for bookmarking, but I don't think there is anyway to prevent the user from bookmarking it in their browser (or writing down the URL for that matter).
You may want to look into generating the data on the page on each page load so if the user bookmarks the URL, they see the most recent information. Or if the user didn't follow a certain path to arrive at that path display a message telling them the data is out of date.
Using POST instead of GET Would resolve the issue for the most part, but I understand this may not be possible depending on the amount of code that you have already created. Another possible solution is to set Session variables to determine if that person should have access to this page or not. If they do not have access, than you send them back their landing page, profile, or even login page. I have done this by placing session variables that can only be set on one page, and then destroyed after the page is viewed, this way they cannot simply go back to the page because the session value is gone.
Sadly it is not possible to prevent people from creating bookmarks to your page, you simply need to filter out who can see(edit or access) it.
You are essentially talking about user sessions only during which all the variables would make sense. Even using POST doesn't solve the problem. In the extreme case one can make a POST request (or search engine may do) and misinterpret the retrieved result. I would suggest to append a sessionid as many other websites do and on the backend to control the valid timeframe. This way you have better control of your website functionality and user experience. Whether a session has expired or not should depend on your business logic, not GET/POST methods.
Related
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.
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']
Well, I just started to work on server side scripting , I chose PHP, So let me explain where Im getting troubled.
This is very a quite simple questions.See, I have some links like these on my page1.php
profile
photos
Now when user jumps to page2.php or page3.php, I also want to pass the user unique ID to the corresponding page, say his email.so that i can update the page2.php according to the username.
When I googled, I heard lots of contradictions , some people were explaining to use session_start() and some people explains cookies and some people says POST and GETmethods. Some people said its easy to hack when you use GET or POST method and some people answered Cookies are client side and it disconnects from server and after hearing all those I decided to use session_start()
But as im a newbee I dont know what to chose,which is the best way.Could anyone kindly explain me which is the best solution to use and why? and also please provide some sample example so that i can understand it much better.Any help is greatly appreciated.Thanks
In order of preference as a solution for the problem you have presented in your question.
Sessions
As this is details of the current user the easiest way to complete this is to use PHPs sessions. This will allow you to access the details in a super global array called $_SESSION DOCs from any page that calls the session_start() DOCs function. This should appear before any output is sent to the browser so it is usually put at the very top of the PHP script.
Each user has their own session on the server and session_start() automagically provides your script with the right data for the current user.
page1.php
session_start();
$users_email_address = 'example#example.org'; // source from DB or whatever
$_SESSION['email_address'] = $users_email_address;
page2.php and/or page3.php
session_start();
echo $_SESSION['email_address'];
Please see the manual documentation for session_start() for more examples.
Use HTTP GET parameters
This works best for URLs that you may want to share - so search results pages or perhaps pagination.
Passing user details in this manner is not ideal as the user can easily change the URL in the browsers address bar. So they could change their email address to someone elses and fool your script.
Using cookies
Storing user data in cookies is not a brilliant idea as a user is able to edit cookies as they are stored on their machine.
Also cookies have a size limit of 4KB and get sent with every request header to the server - thus slowing your site down.
Using HTTP POST parameters
This the very least recommended method for doing this. POST is intended for receiving data to save it on the server and not for navigation. If the user were to press back on page3.php then they would be shown a "do you want to resumbit this form" message by their browser. Pretty unintuitive for a user who thought that they had just clicked a link and not submitted a form.
Best practice is to use session variables ( such as $_SESSION['variable_name']; ).
If you involve form submission, use POST method.
If you only get simple information by setting up parameters, use GET method.
You can use either of those.
Session
This is the best as the email address is stored in the server side. There is no way someone can get hold of the value and try to do bad things with it.
GET
Although this achives what you want by appending to the URL like page2.php?email=someone#example.com, it's easily readable in the browser address bar. It's like you don't store this value anywhere, just pass it between pages.
POST
This is similar to GET but that the parameter gets passed under the hoods. The user can still find this out if he uses plugins to his browser. Like GET, here also the value isn't really stored anywhere. To do a POST, however, you'll need to have a form on your page. Think of it like a form where you ask the user to input his email address.
<form action="page2.php" method="post">
<input type="text" name="email"/>
</form>
In the above example, you can read the value of email in page2.php by doing $_POST["email"].
Note that if you change the method to get, it becomes same as a GET request.
<form action="page2.php" method="get">
<input type="text" name="email"/>
</form>
Here, you can read the value of email in page2.php by doing $_GET["email"].
COOKIES
This works by storing a value on the user's browser. The least recommended of all approaches as the user need not have his cookies feature turned on by default.
Just complementing the answer of Treffynnon:
actually page2.php should be page1.php
Manual about session:
http://www.php.net/manual/pt_BR/function.session-start.php
session_start() must come before all html code or echo in php. In other words: before everything that generate html's code.
sessions are the best choice .Because sessions were one solution invented to over come the
STATELESS nature of the web pages .
sessions are very simple to understand and use . each user will be having an session .
When the user id is set you want to add it to a session. A session is basically a variable that is available over all your pages.
When you set your sessions you want to have session_start(); at the very top of your page. It needs to be before the <html> tag.
Set your session like so $_SESSION['user_id'] = 1;
You can then recall the value of the session on any page like this echo 'User id: ' . $_SESSION['user_id'];
This will output: User id: 1
There's a lot of info in the manual - http://www.php.net/manual/en/book.session.php
I have been looking for ever for a solution to my problem - I’m not a PHP newbie but am not overly experienced in it.
My problem is this:
I have a set of sites - one being the parent site. I want to have it so that if I hit any of my child sites from the parent site only, a back to parent button appears (wrapped in a div). If I hit any of the child sites directly or from another referrer then the button doesn't appear.
I have this working using HTTP_REFERER but I would like the button to remain visible when you click the through the site (obviously the referrer changes once I start clicking through the site).
This works for the button appearing on first hitting the site:
<?php if (preg_match("~^http://www.mysite.com~i", $_SERVER['HTTP_REFERER'])) { ?>
<div>Back</div>
<?php } ?>
But as I say I would like it to remain whilst I am navigating the site - I have looked at setting up a session but I can't get this to work either - the referrer always changes once I start navigating.
I appreciate this is a little vague but I have tried so many code samples and they all seem to have the same issues.
Any help would be much appreciated.
Thanks
Well the HTTP_REFERRER is indeed the last referer of the current page, so you have to store and start a session the first time you enter the site.
Sessions are usually a very simple subject that should work out of the box:
session_start();
session_regenerate_id();
if (preg_match("~^http://www.mysite.com~i", $_SERVER['HTTP_REFERER'])) {
$_SESSION['parentsite'] = true;
}
And later in your code do:
<?php if(isset($_SESSION['parentsite']) && $_SESSION['parentsite'] == true){ ?>
<div>Back</div>
<?php } ?>
Now if your sessions still don't work with that, it could be a COOKIE problem or a server configuration problem...
<?php
session_start();
if (!isset($_SESSION["ref"])){
$_SESSION["ref"] = $_SERVER["HTTP_REFERER"]; //record first instance
} else if (isset($_SERVER["HTTP_REFERER"])){
$ref = $_SERVER["HTTP_REFERER"];
if ($ref != $_SESSION["ref"]){
$_SESSION["ref"] = $ref; // record new ref
}
}
if ($ref = $_SESSION["ref"]){
echo "Back
}
BUT I agree with Pekka, that you should use custom site_id which is passed along whilst you navigate your site. Relaying on HTTP_REFERER is generally unsafe. And using session would run you into problem if you come to your master site from two child sites, as session would hold only latest ref.
In other solution of ours, we use get param "current_ref", which contains encoded referer url, created by the source site. This param is "sticky", and is passed all along the way, so at any point of time you can return to the originating site. Probably it would be better for you to implement such approach as well.
Edit: On closer look, a session based approach might be just enough for this specific situation, if there is only one parent site and multiple children, but no multiple parents! In a more complex situation however, sessions will send you to hell, so I'll leave this answer in place.
This is not trivial -
you could use sessions to store the referrer target across pages, but that would get confused if the user opens multiple instances of the same page from different referrers, which is horrible for usability
or send a unique key along with each request that points to the correct "back" target. (It could also be the base64 or URL encoded URL itself, but that would make the URLs look long and ugly...)
The latter is a very clean approach, but a pain to implement consistently.
One other (crazy and untested) idea that comes to mind is storing a base64 encoded representation of the referrer URL using JavaScript in the window.name property. The nice thing about that is that unlike a cookie, it stores the "back" target for the current window only. I can't guarantee this will work, but it might be worth following up on if you really want to do this.
As soon as I saw your question I thought that a SESSION would be the key.
You could set a session cookie and then test to see if the cookie already exists.
session_start();
if (preg_match("~^http://www.mysite.com~i", $_SERVER['HTTP_REFERER']) ||
isset($_SESSION['show_back_button']))
{
// Set the session value
$_SESSION['show_back_button'] = true;
echo '<div>Back</div>';
}
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.