I have a question, i want to make some search page, and it needs a get variable to sort the results. So if someone enters the page without that GET variable, reload the page and make it appear, for example you enter www.myweb.com/search and automatically reloads and changes to www.myweb.com/search/?sort=ascending (because that variable is necessary) .
I hope you understand me, good bye
I think this will work for what you're looking to do:
if (empty($_GET['sort'])) {
header('Location: ' . $_SERVER['REQUEST_URI'] . '?sort=ascending');
exit();
}
From within the file executed when www.myweb.com/search is requested, you should have a default setting when $_GET['sort'] isn't available. For this Answer, I'll be using PHP for my examples since you didn't specify.
<?php
if (empty($_GET['sort'])) {
$sort = 'ascending';
}
// the rest of your code
Alternatively, you could force a redirect, but the previous example is more elegant.
<?php
if (empty($_GET['sort'])) {
header('Location: www.myweb.com/search/?sort=ascending');
exit;
}
Keep in mind, the second solution would throw away anything else, i.e., other $_GET's, like item=widget or color=blue
Note to others posting !isset as an answer. That will not work! Example:
www.myweb.com/search/?sort=&foo=bar
!isset($_GET['sort']) === false!
empty($_GET['sort']) is the proper route to take in this circumstance.
It is better to define the variable by yourself rather then redirecting. Just check with isset if the variable is defined or not. It it has not been defined you can set it yourself as below.
if(!isset($_GET['sort']))
{
$_GET['sort']='ascending";
}
Related
I am trying to make a simple redirect php plugin, and i cant get to the bottom, i would really appreciate some help.
Inside a folder i have the php script that will handle the redirect, for ex: /redirect/a.php
Scenario 1:
call /redirect/a.php?key=firstkey the redirect to http://www.url1.com
Scenario 2:
call redirect/a.php?key=secondkey then redirect to http://www.url2.com
General rule:
If a.php is called without key, or with wrong key then display Error.
Thank you!
Use global variable $_GET["key"] to get value of "?key=value", then use header() to redirect.
Note that there cannot be any output before calling header(), that applies even for whitespaces (such as space, or tab).
It could look something like this:
// checking whether the key is sent by user who visits the page
if(!isset($_GET["key]))
{
die("Key is required");
}
// checking whether the key is empty
if(empty($key)
{
die("Key shouldn't be empty");
}
if($_GET["key"] == "firstkey")
{
header("location: http://www.url1.com");
}
It would be better to use array() to list keys that should be accepted by script, you could easily look for them by using in_array().
I have the following PHP script within a file named login.php
<?php
$ref = $_SERVER['HTTP_REFERER'];
if ($ref == 'http://example.com/dir/invalid.php' || $ref == 'http://www.example.com /dir/invalid.php') {
echo '
<div id="invalid">
TESTTESTTESTTESTTESTTESTTESTTEST
</div>
';
}
?>
I have deliberately went to the invalid.php page (which redirects using header() to login.php) and this div does not show up. Does it have something to do with the referrer not really being invalid.php or is there an issue with the script?
Thanks
I don't think the HTTP_REFERER is what you think it is. Namely, it is the page from which the user followed a link to the current page. However, it's very unreliable as we rely on the browser of the user to correctly report this value.
I would suggest the option I thought you needed, except that the only one I can think of you might doesn't really makes sense... (checking if the url matches a url that's not the current script)... so I do not see what you are trying to do.
As promised several ways to do what you want to achieve:
First off, I don't like this solution at all and really consider it ugly, but it's the one closest to what you where trying to do.
invalid.php
require 'login.php'; // we include the file instead of referring to it
login.php
if ($_SERVER['SCRIPT_NAME'] == 'invalid.php')
{
// do whatever
}
The main difference between what you did and what I did for the user will be that here the url bar will show that you're at invalid.php and not somewhere else. This also means that refreshing doesn't make the message go away.
A better solution in my opinion is the following:
In your script that logs a user in (checks the database and everything):
if (!valid_login()) // pseudo-code, obviously
{
$_SESSION['invalid_login'] = true;
header('Location: login.php');
// previously, we had something like this instead of the two lines above:
// header('Location: invalid.php');
}
in login.php
if (isset($_SESSION['invalid_login']) && $_SESSION['invalid_login'])
{
$_SESSION['invalid_login'] = false;
// do whatever
}
Of course, this should be done with proper session facilities like starting up the session in both those files. Instead of using session variables, you could include the file and use normal variables or send GET variables through the header request, but both those solutions share a problem: refreshing doesn't make the message disappear. However, if you were to move the code from the top file of the two above to login.php (if it's not already there, I don't know what file that actually is...) you could once again use normal variables instead of session variables and have a solution in which refreshing does make it go away. In this case, you might argue that you are cluttering your files with bussiness logic and presentation, but there are solutions to that (like keeping it in a separate file, and including it into login.php, moving the html to another file and including that one into login.php or both.
What I am try to do is use $_SESSION['user_id'] to check if 'user_id' is = to "number", say 56 for example, if so load page, if not redirect user to "billing/".$_SESSION['user_id'].".php";
So far I have this
<?php
if ($_SESSION['user_id']) === 56) {
//do nothing
} else {
header("Location: billing/".$_SESSION['user_id'].".php");
exit();
}
?>
I know this code is wrong but hopefully it conveys what I am trying to accomplish.
Thanks in advance for your help and code snippets.
do not edit the code in your question based on the answers. You are making it impossible to understand what are you talking about.
If you want to add something - ADD it below the original text.
Ask clear, certain question. Describe the problem you face and what kind of solution you need.
Separate matters. As a matter of fact, sessions has nothing to do with redirects. If you want to know how to use sessions - ask how to use sessions. If you already have valid and verified session variable but have no idea of redirects - ask about redirects. If you don't know how to compare values - ask it. If you know everything but not certain about some bells and whistles of the code styling - ask this particular question.
Now, what is your question?
You're pretty close, but you could use the php function http_redirect instead for the redirect, to be more concise (requires the PECL library):
<?php
if ($_SESSION['user_id'] == 56) {
//do nothing
} else {
http_redirect("billing/".$_SESSION['user_id'].".php", array(), true, HTTP_REDIRECT_PERM);
}
?>
The PHP Doc for header() gives a lot of info about how to use the header function. The most important is:
Make sure no html or text has been echoed or sent to the browser before you call header().
You need an exit(); after header() since you're done rendering the page and some browsers prefer it.
HTTP/1.1 requires an absolute URI as argument to » Location: including the scheme, hostname and absolute path so you'll want to put the full URL after 'Location:'. See php doc for example.
Why not check the opposite? And for readability it is wise to use {} not "." (as long as your editor highlights this)
<?php
if($_SESSION["user_id"] != 56) {
header("location: billing/{$_SESSION['user_id']}.php");
die();
}
?>
I have a website authored in PHP where any time a user receives an error I will redirect them to a another page (using header(Location:...)) and put the error ID in the URL so that I know which error to display.
E.g. If the user tries to access a product page but that item is no longer available I will redirect back to the category of items they were previously looking at and display an error based on the error ID I have specified in the URL.
www.example.com/view_category.php?product_category_id=4&error_id=5
There are two things I don't like about this approach:
It displays the error_id in the URL.
if the page is refreshed, the error will still display.
Is there a way to cleanly remove a specific $_GET variable from a URL while leaving the rest of the variables intact AFTER the page is loaded?
I'm thinking maybe it's using modRewrite or a redirect back to the page itself but removing the error_id from the URL or using a $_SESSION variable and avoiding putting the error_id in the URL. Your thoughts?
I really am learning a lot from this community and thought if I posed the question I might be able to learn something new or to get some varied ideas as I'm fairly new to scripting.
No, there's no way to do that explicitly - at least not without a page refresh but then you'd lose the data anyway.
You're better off using a temporary session variable.
if ( /* error condition */ )
{
$_SESSION['last_error_id'] = 5;
header( 'Location: http://www.example.com/view_category.php?product_category_id=4' );
}
Then, in view_category.php
if ( isset( $_SESSION['last_error_id'] ) )
{
$errorId = $_SESSION['last_error_id'];
unset( $_SESSION['last_error_id'] );
// show error #5
}
Yes, there is a way to remove especific $_GET from PHP...
varToRemove = "anyVariable";
foreach($_GET as $variable => $value){
if($variable != varToRemove){
$newurl .= $variable.'='.$value.'&';
}
}
$newurl = rtrim($newurl,'&');
Then, put the $newurl in the link.. like this:
pageurl?something=something&<? echo $newurl; ?>
I know it´s an old post, but, other programers may be search for it!
First, log the error in your database :)
After that, set a cookie or session variable and then redirect the user to safe page. When that page is loaded, have it check for the variable, display the error, and then delete variable from the cookie or session array.
One way is to compare the HTTP_REFERER with the SCRIPT_NAME. They'll be the same if the user has hit Refresh.
Quick Hack: You could have also imploded()'d on "&" in the the $_SERVER['QUERY_STRING'] variable to manipulate that string and then explode()'d it back.
Wouldn't this approach work?
<?php
$params = array_diff($_GET, array("variable_name" => $value));
$new_query_string = http_build_query($params);
?>
<script>window.history.pushState('verify_email', 'Verify Email', '?<?php echo $new_query_string; ?>');</script>
i had same problem
try : http://www.azazia.com/kb/entry/26/
if (!empty($_GET['passvar'])) {
unset($_GET['passvar']);
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"0; URL=".$_SERVER['PHP_SELF']."\" >";
}
work perfectly for me.
How do I make it so that I can make a thing at the end of the address where the .php is and then tell it to do certain things. For example pull up a page like this:
sampardee.com/index.php?page=whatever
Help?
Anything else I could do with this?
This is generally achieved with the global php array $_GET. You can use it as an associative array to 'get' whatever variable you name in the url. For example your url above:
//this gives the $page variable the value 'whatever'
$page = $_GET['page'];
if($page == 'whatever'){
//do whatever
}
elseif($page == 'somethingelse'){
//do something else
}
Check out the php documentation for more information:
$_GET documentation
and there's a tutorial here:
Tutorial using QUERY_STRING and _GET
A small improvement over Brett's code:
if (array_key_exists('page', $_GET) === false)
{
$_GET['page'] = 'defaultPage';
}
$page = $_GET['page'];
// ... Brett Bender's code here
$_GET is usually used if you are sending the information to another page using the URL.
$_POST is usually used if you are sending the information from a form.
If you ever need to write your code so that it can accept information sent using both methods, you can use $_REQUEST. Make sure you check what information is being sent though, especially if you are using it with a database.
From your question it looks like you are using this to display different content on the page?
Perhaps you want to use something like a switch to allow only certain page names to be used?
i.e.
$pageName=$_REQUEST['page'];
switch($pageName){
case 'home':$include='home.php';break;
case 'about':$include='about.php';break;
case default:$include='error.php';break;
}
include($include);
This is a really simplified example, but unless the $page variable is either home or about, the website will display an error page.
Hope it helps!
I'm not quite sure what you're asking, but I think you're asking how to use GET requests.
Make GET requests against any PHP page as follows:
www.mysite.com/page.php?key1=value1&key2=value2
Now, from within PHP, you'll be able to see key1 -> value1, key2 -> value2.
Access the GET hash from within PHP as follows:
$myVal1 = $_GET['key1'] #resolves to "value1"
$myVal2 = $_GET['key2'] #resolves to "value2"
From here, play with your GET variables as you see fit.
The system of adding page parameters to a URL is know as HTTP GET (as distinct from HTTP POST, and some others less commonly used).
Take a look at this W3 schools page about GET in PHP and ahve a play about in getting parameters and using them in your PHP code.
Have fun!