When a user does a search on my website, and there is only one entry, then I want to redirect the user to the search result. The current way that I am doing this is poor. Here is how I am currently doing this:
If there is only one search result on the search result page, then I render a hidden input with an ID of "redirect" and a value of the link to redirect to. In the javascript, if the hidden input with ID "redirect" exists, then the user is redirected to the value of the element.
It's a poor way to do this because the single search result is loaded first, so the user actually sees that there is one search result. Then, it loads after, say, 3 seconds.
Is there a better way to do this?
You could use the header() PHP function to redirect if there is only 1 result.
header("Location: http://www.example.com/");
You should use PHP to determine if there is only one result, then do a server-side redirect like so:
header( 'Location: http://www.yoursite.com/redirect_page.html' );
exit;
Before printing anything to the page, check to see if there is only one result, and if so, render that script and exit so that nothing else gets processed.
<?php
//Query & other stuff
$num_of_results=mysql_num_rows($result);
if($num_of_results==0){
//no results
}elseif($num_of_results==1){
//only 1 result
//pseudo-code
//get id or controller ect from result set
header('Location: ./page/'.$id);
die();
}else{
//normal display of search results
while($row=.......){
}
}
?>
The issue with your logic is that you're waiting for something in the page to load THEN redirecting. I think a more elegant solution is to change the flow of things to give you a little more flexibility.
First, you're going to want to preprocess your query and check for the pertinent information; if there is one result, use the header(); redirects as mentioned. You may need to add some more information to the result set (database table) to make this possible.
I think taking this a step further, however, would be to redirect certain terms automatically as well. You'll kill two birds with one stone.
Let's say you have a database that is term and url - you could add certain terms to the list that also serve as a redirect. This is great for certain keywords that there are variations of. Use this sparingly though - it is great to use in conjunction with your site statistics. It may help you in instances where 0 records are shown.
Related
I'm trying to use header() in PHP so it will send a GET request, and also redirect the user to a certain div ID, and originally the code I came up with was this:
header("Location: ?load=10#divName");
However, that gave a 500 error code, due to "redirecting me too many times".
I then tried doing something like this:
header("Location: #divName?load=10");
However, this just completely ignored the GET request, which makes sense, since it thinks it's part of the div ID.
Should I just give up and try using a POST request instead, or is there a way around this? Thanks!
Note: I only am using header() for tests, otherwise, it is connected to an <a> tag.
P.S. If you are wondering what I'm trying to do over here, when you click a button, it sends a request to load more blog posts, and then it directs the user to the last blog post in the list that was just loaded. I changed the div ID for less confusion. Please let me know if there is a better way around this, I'm sure there is!
First using a header tag, you need to use the full URI if you want to redirect to somewhere. I recommend using the global $_SERVER for it. documentation
Second, the thing that you want to do is achievable using javascript and ajax, instead of php. I recommend you research the ajax documentation to see some examples.
But mainly to fix the main problem of "redirecting me too many times", check if you are looping something that can callback the header function more than once.
I have a search page that outputs search results. You can filter results based on on the following criteria before running the search.
1. status
2. order by
3. record type
Viewing a record redirects the user to the edit form page and if they click the cancel button they redirect back to the search results.
Here's what I've done:
I stored the GET parameters (status,order_by and record_type) in session variables
When the user clicks cancel on the edit form, I use the session variables to redirect back to the search results as follows:
if (#$_POST['cancelbtn']){
if (isset($_SESSION['searchForm'])){
header("location:searchForm.php?products=".$_SESSION['product']."&ticket_status=".$_SESSION['status']."&order_by=".$_SESSION['order_by']."&record_type=".$_SESSION['record_type']."&searchbtn=Go!");
}
}
The above works for me but I'd like to know if this is the best way to do it? Thanks.
It's not a bad way of doing it, but I would try and future proof it a bit. Instead of storing each individual variable in the session, try storing the URL. That way, if you change your search form to have some additional parameters, you won't need to change much of your code.
//Your search results page
$_SESSION['searchResults'] = $_SERVER['REQUEST_URI'];
//Your form page
if (array_key_exists('cancelButton', $_POST) {
header('Location: '.$_SESSION['searchResults']);
exit;
}
Hope this helps
I have a form which sends data to a proccess page. Is it possible when the code in the process page is executed for the browser to jump back to the previous page?
EDIT
The reason i want this, is because i have a set of parameters which contains checkboxes. These parameters are echoed out via a while loop. I have a table where it shows which of those parameters are active. I would like to check the checkboxes by defualt where the corresponding parameter is in the table.
|||||||||||||||||||||||||||||||| Example ||||||||||||||||||||||||||||||
PARAMETERS:
T-Shirt: checked
Distance: checked
Race: unchecked
TABLE (parameters)
• T-Shirt
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||the example above checks the box if it already exists in the parameters table. When the user clicks back after the process page, the boxes he selected is checked.
Hope i am clear enough
Regards
I think a nice solution might be to implement a front controller for your webbage, a central script to include the appropirate page. Using a system like that, the user stays on the same page all the time even when other pages are loaded.
I haven't used a front controller in quite some time, so I won't write examples due to potential errors and poor coding. You can probably find some examples using google though, I wouldn't be surprised if the subject has been brought up here on Stackoverflow before either.
Even though I'll have to point out Griffin's solution is the best, if you're dead set on a redirect, simply have your PHP script execute the following lines:
echo '<script>document.history.go(-1);</script>';
die();
Or even
die('<script>document.history.go(-1);</script>');
It's a dirty solution, so I must advise against it.
I was wondering, how is it possible to get example the last X number of pages a user came from on my site?
I am creating a navigation, so the user easily can see the X number of previuos pages he visited on my site only.
I just don't know how to do this. Is there any function in PHP to obtain this?
Thanks in advance.
I'm assuming you mean the last X pages on your site only, and that you know how to use sessions and arrays.
In this case you could initialize a session for the user, then every time the user visits a page, append the URL or some identified of that page to the array. If there's more than X pages in the array, additionally remove the first one.
Then you could just get the contents of the array, parse them into a bunch of links and show them on your site.
In case you meant the pages before entering your site, you can only get the latest one via the referer header. Some browsers might be configured to not send the referer header, however, so there really isn't a way of accomplishing this properly.
<?php
session_start();
/*
Put here any logic that could result in a redirect, to avoid useless records
...
*/
$_SESSION['history'][] = $_SERVER['REQUEST_URI'];
$_SESSION['history'] is now an indexed array with all of the user's history on your website.
My site has a library full of games, nations, game scenarios, etc.
library.php is given a type=___ & id=___
for example library.php?type=scenario&id=ABCD001
library.php saves the id to a session variable and loads an include appropriate for the type
This all works just dandy. Now, I wanted to give my users the option of pulling up a random scenario. To do that, I added a special id to the logic within lib-scenario.php (the include) such that if given library.php?type=scenario&id=random the include knows to run an alternate query for a random record rather than for the actual id
This also works just dandy... unless someone hits the Random Scenario button two+ times in a row, and decides that the previous random scenario was way cooler, I want to go back to that.
Because the http address is always directory/library.php?type=scenario&id=random no matter how many times you click Random Scenario, as soon as you click back you'll be taken to the last page with an alternate address you visited.
So, if you start at the Home page, and hit Random Scenario 35 times, then decide the 34th one was what you wanted and click BACK, you'll be put back onto the Home page.
I must admit this was not a problem I had anticipated. One of my testers was the first to have the urge to back-up in the random scenario stream and here we are.
How can I add back-up functionality to my script?
Make the 'Random Scenario' button simply link to an actual (but random) scenario id. You'll probably have to construct this with an SQL query to get all the id's of your scenarios.
$result = mysql_query("SELECT id FROM scenarios");
while ($row = mysql_fetch_row($result)) {
$ids[] = $row[0];
}
$randomid = array_rand($ids);
Button:
<a href="directory/library.php?type=scenario&id=<?php echo $randomid; ?>Random Scenario</a>
If your scenario id's are all consecutive numbers you can simply use this instead:
$randomid = rand($min, $max);
you can resolve this by redirecting to the canonical url for the scenario, i.e.: id=random redirects to id=A92831 or whatever was selected. the final url will be stored in the history, rather than the id=random url.