get current URL and previous URL when user pushes button - php

Newby here.
Could someone show me an example of the code needed to do the following:
User pushes a button on my web site (there is no information for him to input, and no form, he just clicks on a button). I have found the following code on another post, but don't know if it is correct (I am also getting a syntax error on it):
<form action="php_file.php"><input type="submit" value="Click"></form>
The author of the above code said "Insert your PHP-Code into the file php_file.php and click the button, your file will be opened. Insert header("Location: html_file.html"); at the end of your php-file to get back to the page."
This click of the button needs to instigate the programming to grab the current URL and previous URL and insert them into the mysql database on my server. I have "PHP_SELF" and "HTTP_REFERER", but still need to get the results into mysql.
I would like to do this using only html, PHP and mysql, if possible.
Thanks to everyone for any help!

if your first file happen to be a PHP one, write this HTML form there.
<form action="php_file.php" method="POST">
<input type="hidden" name="previous" value="<?=urlencode($_SERVER['REQUEST_URI'])?>">
<input type="submit" value="Click">
</form>
and then in the php_file.php
<?
$current = $_SERVER['REQUEST_URI'];
$previous = $_POST['previous'];
though both variables will contain only partial url, without host name, schema and, possible, port. it's usually enough but if you need these absent parts, you'll have to add them manually.
as for the writing info into database and particular PHP syntax rules you have to find yourself a tutorial, because this site is devoted to answering questions, not online education nor doing someone's job for free.

With PHP, you can manage it with cookie session, first thing you'll need to do is start a session and then define the space where you'll store the URL information e.g: $_SESSION["url"]
session_start();
$_SESSION["url"]=$_SERVER['REQUEST_URI'];
And whenever you want to go to that particular page, add the header:
header('location: ' .$_SESSION["url"]. '');

Current:
$currentUrl = $_SERVER["PHP_SELF"];
Previous:
$previousUrl = $_SERVER['HTTP_REFERER'];
Note that some users may have browser preferences set that keep $_SERVER['HTTP_REFERER'] from being set, so it's possible that it would come back empty.

Related

Is it because $_GET is global or the form submitting to itself or else?

I am trying to understand one simple thing in PHP form handling.I am new to it and I have a sample code:
<form name="frm" method="post" action="">
Item Name:<input type="text" name="itmName" id="itmName"/><br/><br/>
<input type="submit" name="sbmit" value="Add Record"/>
</form>
<?php
if(isset($_GET['m']))
{
echo '<script type="text/javascript">alert("'.$_GET['m'].'");</script>';
}
if(isset($_POST['sbmit']))
{
header("location:1.php?m=10");
}
?>
Irrespective of what data I send to the server, my focus is on the if(isset($_GET['m'])) part of the code. Everytime I submit the form, the 'if' is always evaluated to true and as a result the alert box appears.Is it because $_GET is holding the previous value set by header("location:1.php?m=10"); or is it because the form is submitting to itself or else?Googling didn't provide much help. I need better understanding over this.With Thanks
Since you are not specifying an action, it is going to get defaulted to the current pages url, in this case "1.php?m=10" (if that is what it was as you say). Even though the form is getting submitted via POST, the query string is still passed and still accessible.
To prevent it from being set, all you need to do is specific your form action
1°) when you submit your form, the post method send "itmName" and "sbmit" to the same page (because you didn't write anything in "action=").
2°) if the page received the post var 'sbmit', and i does, you ask to the server to redirect the page to the same page (i guess) with a get variable (m=10)
3°) you ordered your page to send an alert if it recieves something in the 'm' get variable.
So in only one shot, your sever does thoses 3 steps. That's why every time the alert is sent.
You are right, the form is client side.
When the submit button is cliked, the post datas are send to the server. Now in server side, the first thing the server see is "if(isset($_POST['sbmit']))" which orders a redirection but in php not in javascript, so we stay server side with the load of a new page that first need to be interpreted by the server because it contains a get variable.
This Get variable is detected by the server and automatically is turning "if(isset($_GET['m']))" on true. Now it writes the javascript tag that will be interpreted client side with the launch of the alert.

Use PHP to track links

I have various links in my website that point to a specific form.
Whenever someone fills out the form, I want to be able to know what link led them to the form.
I want to do this without having to create an individual line of PHP code for every link I create in the. Instead, I want to have some PHP code that picks up something from that link, and maybe inserts it into a hidden text box that gets its value or text from something that I tag in the link.
For example:
User clicks a link.
That link directs them to a form.
The link carries an identification that activates PHP code
When I recieve the form, I know what link was clicked to get to that form.
I want it to work with links in emails I send out as well.
Based on the information in your post, it sounds like you just want to send a token/ id.
Goto Form
Now on the form you can grab the token:
$token = $_GET['token']; // use proper testing first
Then use a switch or if statements to run whichever code you need.
<input type="hidden" value="<?php echo $token; ?>">
Additional:
As the //use proper testing first comment indicates, you should make sure the token being passed is valid and sanitized in case of attack. One option is to have tokens stored in a database when generated and then compared when validating. Also look into htmlspecialchars() and even strip_tags() for sanitizing.
If the token fails to validate, you should not output and should even have a warning message/redirect that there was an error.
You can use HTTP Referer to achieve this. In PHP, you can use
$referer = $_SERVER['HTTP_REFERER']
Use this for example :
if (isset($_SERVER['HTTP_REFERER']))
{
$ref = $_SERVER['HTTP_REFERER'];
}
then in your form something like:
<input type="hidden" value="<?php echo htmlspecialchars($ref, ENT_QUOTES); ?>" name="ref" />

Convert .NET to php. Response.Redirect

OK so my goal is to get this page:
http://www.orchidfilmcompany.co.uk/Payment.aspx
to work in my php wordpress page.
I dont really know where to start, my whole site is ready to go except for this new pay online page.
The guy who created the .NET page has provided me with the Response.Redirect code which has the merchant peoples url with instID etc. The user will be redirected to this url to complet the payment
I have been looking around online and I found the the equivelant code in php for this is:
Header("Location: $url");
My problem is I dont know what to do with that?
Thats all I need is input box where the user can enter the amount they want to pay, they press submit and it redirects them to the url that I have in the Response.Redirect code. Uses the amount that they entered in the box and they can complete the payment.
If anyone could assist I would really appreciate.
Thanks in advance.
header() function is used to redirect the browser to a specific location.
If you already have the URL where you should redirect the client and you need just to add some amount that came from an input .. you should append that amount in the redirect url
eg:
purchase.html - include this form on your page
<form method="post action="/redirect.php">
<input type="text" name="amount" value="" />
<input type="submit" name="sumbit" value="Purchase" />
</form>
redirect.php - put this file next to your html file
<?php
$amount = (int) $_POST['amount'];
$urlToRedirect = 'https://secure.wp3.rbsworldpay.com/wcc/purchase?instId=XXX&cartId=OFMaterial&currency=GBP&amount='.$amount;
header('Location: '.$urlToRedirect);
exit;
?>
The form should have an action assigned to it, which is the page that will parse the form.
On that page (or within your parsing bit of the code), make sure that the redirect happens there.
The header statement is correct, e.g.:
<?php
header('Location: http://www.example.com/');
exit;
?>
Would redirect to example.com. So, construct the URL you want to redirect to there.
Please note: header directly modifies the headers returned by your webserver and therefore it cannot be called if you already sent other (HTML) output to your browser. Also see the documentation on header here: http://php.net/manual/en/function.header.php
You could try having a form which submits to a PHP page
The PHP page could then pick up the form variables using $_POST['FORM_VAR']
Build a $url variable from the submitted variables + .net page url
Finally use the header("Location: $url"); to take in the built url and redirect.

php navigation validation

How to check if the user has entered the page by clicking on the button and not from copy pasting the URL ?
For example, if a user has clicked on Register I want him/her to go to that page only by clicking the Register button and not by copy pasting the link.
Also, is it a good practice to give the page name on the address bar or should I have to hide the page. If I am hiding the page will I be able to do that ?
For example, if localhost/projname/register.php. I don't want people to see the register or login or about or anything on the address bar except localhost/projname.
Maybe check if he used $_POST, something like:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
// do ya thing
}
else
{
?>
<form action="index.php" method="post">
are you sure? <input type="submit" value="yes">
</form>
<?php
}
?>
You can use the HTTP_REFERER data of the $_SERVER reserved variable to see where did the user come from.
if(empty($_SERVER['HTTP_REFERER'])) {
// if we are here, the user copy pasted the url.
}
As for your second question, you can't totally "hide the page" like you're suggesting. The web server must know which page to show, so the browser must know has well.
You can however obfuscate the page name. For example you can call the page "sfhjgdjkfg" so the user won't be able to know that this is the "registering" page. But I think it's really a bad idea, why in the first place want you to hide this ?
One method is to use $_SERVER['HTTP_REFERER'] to verify that they clicked a link from your site, but this method isn't fool-proof as many Firewall and Anti-virus suites will remove the Referrer information.
A better method would be to generate a temporary session token on the pages of your site, and check for that token when the Register page is opened.
If your form uses POST parameters, the browser will pass on some POST data. You could then check
if (empty($_POST)) {
//didn't click the button, just went straight to the url
}else{
//did click the button
}

Refreshing page will re-send form data, is it possible to prevent this? (PHP)

I'm creating a form and using it to get data input to send to a MySQL database via php. If someone hits refresh on the page Firefox ressends the last set of information to the php page which in turn sends it to the database. Is there anyway to prevent this?
To fix that problem, there exists Post/Redirect/Get pattern you need to follow :)
Post/Redirect/Get (PRG) is a common
design pattern for web developers to
help avoid certain duplicate form
submissions and allow user agents to
behave more intuitively with bookmarks
and the refresh button.
You need to do a redirect to the same page:
$current_url = (empty($_SERVER['HTTPS']) ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header ('Location: ' . $current_url);
exit ();
The usual way to do this is to use a redirect.
You get the request, use the data it contains to load your database or whatever, and then perform a redirect (I think you're supposed to use a 303 redirect for this, but I've heard of a lot of people using 302s to avoid certain browser glitches).
The net effect of this is that there was no POST data sent when the redirect occurred, so refreshing can't cause it to be resent and screw up your application/database.
If you don't like any of the above and are using JQUERY. You could do a simple load or ajax function to send the information to your script.
This will erase any chance of duplicate sending and you no page reload. I like this method best, it's fast and easy.
Another solution you can do is have your form send to another page, a bit like this:
<form action="chat_server.php" method="post">
Message: <input type="text" name="message" />
<input type="submit" />
</form>
On the chat_server.php file, you do what you need to do with the data and at the end, you do
echo '<meta http-equiv="REFRESH" content="0; url=chat.php" />';
Give it a try, should get rid of your problem.
Yes. After inserting data you do a redirect.
use a code in a hidden input and this code getting by a table codes for exmaple and if the code sending remove it from database and if the code not set in the table dont accept the query

Categories