I have a form that submits to the same page. Now when it gets submitted and after it's processed I need it to have a unique query string.
So for example the user inputs some info then clicks submit, then the page saves the info on the server then the server spits it back out with a unique query string for that info.
If I try to set $_SERVER['QUERY_STRING'] it just hangs. Is there another way to do this?
Is it possible with a redirect?
EDIT, I'm going from mysite.com/ and the form action is on mysite.com/ and I want the browser to go to mysite.com/?blah
OK I tried putting this on my the top of my page with no luck
<?php
if ($_POST['data']) header('location: /?' . idFromDifferentFunction() );
?>
but it just keeps loading, I'm guessing it just redirects itself to death.
I hope you now understand what I'm trying to do
Chances are that your script is continuing to run after the code that says it should redirect. You also need to be more precise with the header:
<?php
if (isset($_POST['data'])) {
header('Location: /?' . idFromDifferentFunction() );
exit;
}
?>
If you use the code above, it will make the script exit which dumps the output and the browser will see the redirect (note the capital L in Location).
The key point is the exit following the redirect header. Without it, PHP is very likely going to continue working on whatever other code you're doing in the script.
It's not entirely clear what you're after, but I think you mean you want to go to a page with a unique value in the query string (the bit after the ?) once the processing is complete. Does this unique value need to actually reference something in the system (for a newly-created DB entry does it need to reference the ID of the new entry) or does it just have to be unique?
If it's the latter, you could just generate a random unique ID do the following:
header ('location: /path/to/script?id=' . uniqid ());
If it's the former, then replace the call to uniqid with the value of the database key.
The values in $_SERVER are set at runtime by PHP and should be considered read-only. Changing their values will have no meaningful effect.
$_SERVER['QUERY_STRING'] is part of PHP's globals. You should not be setting those variables, instead set it via a session and return it after submission.
If you are trying to redirect the user to a specific URL then use:
header('Location: mysite.com/bla/bla');
Writing to $_SERVER is pointless. It doesn't affect the client browsers in any way. If you want to change the query string displayed in the client browser, you'll have to use a 301/302 redirect using a header('Location: ...') call.
Related
I'm creating a form. There is some server-side validation being executed in a php file separate from the html file containing the form. If the validation fails, I want to redirect back to the original html page with a error message saying what went wrong.
Right now, I am able to successful validate and redirect back to the html page with header(), but I'm not sure how to create and place the error message. Is it possible to check at the top of the html page with php if it's been redirected to through header()? If so, that would solve the problem...
Thanks!
there are several methods to do this i think.
1 add get parameters like:
<input type="hidden" name="formsent" value="1" />
then add method get to your <form>
when you redirect from the other page,, the get would be in the link so you could send it back
header("Location: http://localhost/yourform.php/?{$_GET['formsent']}");
or you could do the validation in the post
if (isset($_POST) && !empty($_POST)) {
do stuff here.. if all is ok go to next page otherwise show errors
}
or you could add a var into a session using $_SESSION['formsent'] = 1 after the post then u could check that also.
its up 2 u
You should set a variable using PHP sessions.
Form page
session_start();
$_SESSION["formerror"] = "Error code here";
header("Location: http://www.example.com");
Redirected to page
session_start();
$errorcode = $_SESSION["formerror"];
// Now convert the error code to something readable and print it out if needed.
IMO this is much cleaner than a GET variable.
As #Mark wrote, you can send a message in a variable by the url in your header() (I mean url + "?variable=$variable") and capture the message in your page (now php page) by $_GET. The message will depend on your validation
Of course you can check: https://stackoverflow.com/a/872522/2737474 (#Jrgns)
Different ways to pass one variable between pages.
In my opinion, you must be careful in choose one of those:
-If you would use one value for many pages (keeping in mind it would be store on server), it would be better to use SESSION.
-If you would use one value for only two pages, it would be better to use GET or POST (depending on your situation, url/form).
-If you would use one value for many pages and want to keep it between sessions (keeping in mind it would be store on client), it would be better to use COOKIE.
You can do this with using $_GET[] method
If validation is successful then redirect to url like
form.php?status=1 // 1 for success
If validation is failed then redirect to
form.php?status=0 // 0 for fail
In form.php which is your form page.
use simple if-else condition
if(isset($_GET['status']))
{
if($_GET['status']==0)
echo'something went wrong';
//else nothing
}
As many clever users wrote you have several methods how to achive this (I won't write all of these):
1st Use sessions check Daniel's answer
2nd Use GET check Sanket Shembekar's answer
3rd Use rZaaaa's answer, but you can enchant it :D
Enchant:
Page 1
header('error: true');
Page 2
print_r(headers_list()); //and find your error
Is it possible to include some message in a PHP header:
header("Location: http://somesite.com");
header("Message: hello");
then on site.com:
$message = some_function(); // "hello"
I am currently using a $_GET parameter in the URL, but looking for an alternative, maybe sending a $_POST?
I'm trying to not use $_GET, or use cookies (I know, those are the best ways..)
It sounds like you are wanting to send some extra data to the page you are redirecting to. No, this isn't possible outside of the query string. You should understand what is happening here.
When you send a 302 or 301 status code along with a Location: header, the browser sees this and then makes a separate request to the URL specified by the Location: header. The server isn't sending anything to that page. It's almost as if the user simply typed in that new URL in their browser.
I say almost because in some circumstances, there is a referrer set by the browser. This isn't guaranteed though.
What you can do is send some sort of token that contains more information. Perhaps your page saves off a message in a database or something, and then you pass the ID in the query string of the URL you're redirecting to.
Also, if you set session/cookie data and you're redirecting to something on the same domain, you can read that information on the page the user eventually lands on.
In addition to what Brad suggested, you can also send some info using # in the url without affecting the query string and then capture it with js.
header("Location: http://somesite.com#success");
in js:
if(window.location.href.indexOf('#success')>0) {
alert("operation successfully completed");
}
No headers are already sent, this is the first piece of code accessed on the page.
I am making a multilingual site and as it has very little text am trying to redirect users to different directories based on their language. I have written this in php and every time I assess the site, I receive an error and it wont load.
$lang=$_SERVER['HTTP_ACCEPT_LANGUAGE'];
$es=array("es", "es-es", "es-us", "es-mx");
if(array_key_exists($es, $lang)){
header('Location: http://www.site.com/es');
exit;
}else{
header('Location: http://www.site.com');
exit;
}
In Firefox I receive the error 'Firefox has detected that the server is redirecting the request for this address in a way that will never complete.'
And in Safari 'Too many redirects occurred trying to open "websitename". This occurs when opening a page it redirects you to another that, when opened, you are redirected to another page.'
But I have no copy of the language check script in the sub folder. When I make the if statement very simple if($lang =='es-es') it works perfectly. There must be something wrong with my syntax but I can't see what it is.
As I understood, correct me if wrong, if you are on the ELSE statement, it redirects you to the same site, where the check is performed once again, and redirects you once again, and again, causing an endless loop.
Use in_array to check instead - or turn your dictionary array into a hash:
1)
if (in_array($lang, $es)){
// ...
}
2)
$es = array_flip(array("es", "es-es", "es-us", "es-mx"));
if (isset($es[$lang])) {
// ...
}
As it stands, your $es array is an indexed one, but you're trying to search in its keys - which are simple numbers (0, 1, 2, 3...).
Yet there's another problem here. What if someone tries to access your site.com without any variation of es in HTTP_ACCEPT_LANGUAGE header? They will be redirected to it again... and again... and again, as each subsequent redirect is re-checked by that if clause.
The solution is to make some default page, which won't be checked for that language setting; thus the eternal redirection loop will be broken. )
You need to use in_array instead of array_key_exists
First, try to do this:
var_dump("<pre>", $lang); die();
and see what are you actually getting in $lang.
What every you are getting, copy past it into your $es array values.
It is saying so because you are redirecting it to the same page again and again. try redirecting to some other page if your condition gets false or simply alert a message saying language do not found or something like this.
As I Getting your Problem...
Change these two lines
$es=array("es", "es-es", "es-us", "es-mx");
if(array_key_exists($es, $lang)){
with following lines
$es=array("es"=>es, "es-es"=>es-es, "es-us"=>es-us, "es-mx"=>es-mx);
if(array_key_exists($lang, $es)){
Basically In the array_keys_exits($key, $array-name) function there are two parameter pass & it is to be first parameter is the value of (key) you want to search or Second parameter is pass the Array name.
I Think you pass the array_key_exits with null value as key & wrong syntax description.
http://php.net/manual/en/function.array-key-exists.php
Let's say a user has bookmarked "http://www.example.com/login#/settings". If that user try to access this page when he is logged out, firstly i want him to redirect to login page and then to the bookmarked page using this method
http://www.example.com/authenticate/login?continue=http://www.example.com/login#/settings
NOTE:
I'm using MVC architecture
Are there any method rather than HTTP_REFERER?
When user enter http://www.example.com/login#/settings ,i want to read whole url including # anchor in my controller file and then only i can set url to
http://www.example.com/authenticate/login?continue=http://www.example.com/login#/settings
so how do i do it??
You cannot read the part after the # from within PHP. You need to use JavaScript for that. For example, you can use
window.location.hash
To locate the hash-part, if any (it will be '' if no hash, or '#something' if there is one). You can then send this to the controller as a hidden field inside the request.
Depends on how you want to present it to your user. For a simple redirection, use header to send the HTTP Location Header
header("Location: http://www.google.com/");
If you want to give your user some time to read a short message before redirecting them, then you can use header to send HTTP Refresh Header
header( "Refresh: 5; url=newpage.php" );
Edit: In order to capture the anchor, you will need to use JavaScript. That information is not available to PHP. In that case, if you use JavaScript to capture the anchor, you might as well write your redirection in JavaScript.
Edit 2: Perhaps the other option is, when you are passing the continue to your program, also send the anchor as another GET variable. So your URI might look like this:
http://www.example.com/authenticate/login?continue=http://www.example.com/login&anchor=settings#/settings
Then use $_GET['anchor'] and concatenate it to the value of $_GET['continue'] with a #.
$uri = $_GET['continue'] . "#" . $_GET['anchor'];
I am creating a website and on one particular page, am wanting to send the user back to the previous page. I am fairly new to PHP/HTML and have been using some existing code for ideas and help.
The existing code uses the following method:
if (! empty($HTTP_REFERER))
{
header("Location: $HTTP_REFERER");
} else
{
header("Location: $CFG->wwwroot");
}
However, when I use this code the HTTP_referer is always treated as empty and the user redirected to the root page. Any obvious flaws in this code?
Don't rely on the HTTP Referrer being a valid or even non-empty field. People can choose to not have this set leaving any checks for that variable going to the empty side of the IF-ELSE clause.
You can guard against this by sending along a parameter in either the URL or POST parameters that would hold a value that you can use to redirect the user back to.
You need to use:
$_SERVER['HTTP_REFERER']
isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
If you wanted to send the person back to the previous page and have it work regardless of the referrer being set correctly, you can append a GET parameter to the URL (or POST).. you will need to encode the URL.. Something like
http://www.domain.com.au/script.php?return=http%3a%2f%2fwww.domain.com.au%2fthis-is-where-i-was%2f
You can use PHP's urlencode() function.
Also note that the referer header might be empty or missing anyway, so you shouldn't rely on it at all..
You should use
$_SERVER['HTTP_REFERER']
However look at the register_globals configuration in php.ini, it should be turned off due to security reasons. You can read more on PHP Manual site.