PHP Redirect Within website - php

I've been trying this code since 3 days in a row until a certain time (minutes or seconds) but unable to solve the problem.
My target is to redirect visitor to 10 random URLs which are being selected from a text file. The user will see a certain page for a certain time and then redirect to another page again, the number of pages he will be redirected to is complete RANDOM.
PROBLEM:
The problem is the visitor is not being redirected to any other page which is randomly selected from a text file, instead it is just refreshing the page... But I want to redirect him to other pages from the text file.. Hope you guys understood me by now.
EDIT: Found the problem. Actually the $rand_link is having NULL as it's value.. { [0]=> NULL } Don't know why.... ANy solution? Checked the 'BBnormalLinks.txt' file for it's permissions and that file is having some links in it for sure because I just checked it..
Thanks,
Here is the CODE:
<?php // Generate Random Nubmers.. 2 ********
$numbers2 = range(13,70);
shuffle($numbers2);
for ($j=0;$j<1;$j++)
{
$numbers2[$j];
}
$seconds = numbers2[0];
//////// For Random URL of Site
$links = file('BBnormalLinks.txt');
$rand_link = $links[ mt_rand(0, count($links) - 1) ];
header("refresh:". $seconds .";url=". $rand_link); ?>

The syntax is correct but some pointers that can cause this are
Some text have been outputted before the header is passed.
The random page, is not being generated, thus ending up refreshing the same page again and again.
I have a very strong feeling, that your $rand_link is returning blank or null.
Update:
After a few discussion, the problem was the evil path again.
$links = file('patotofile\BBnormalLinks.txt');
As baburao113, quoted
I had to move that file to wordpress theme folder lol! Problem resolved :)

Without knowing the contents of 'BBnormalLinks.txt' or the final value of $rand_link, it is difficult to say precisely what is going wrong.
Your usage of file() and mt_rand() appear to be correct, though you aren't doing anything to ensure that you are getting a valid URL.
This is purely conjecture, but I suspect that you don't have PHP properly configured to display errors. If the file fails to load, $links will have a null value going into your penultimate line. You will then try to access element 0 of a null array and receive an empty value. This will result in header('refresh:2;url=') and your page will simply refresh itself every 2 seconds.

From the little I know about the refresh header, it does not seem to be the most reliable thing to count on. (I'd guess not all browsers respond to it.) Since you are showing content, at least for a few seconds, you could try using window.location in a window.setTimeout in JavaScript instead. So something like:
$content = '<script type="text/javascript">window.setTimeout("window.location=\''.$rand_link.'\';", '.($seconds*1000).');</script>';

Related

how to redirect wrong entered url

My current url is http://domain.com/example.php/link=eg But if someone plays with url and puts url as http://domain.com/example.php/abcdefgh97654 - anything, my all functions all links from that page become inactive.
I tried using <?=HTTP_SERVER;?> before all links in my php files but as my website has user registration and sign in, when user signs in and clicks on any menu (link from php script). It throws on index.php page. But if user logs in again it works perfectly. In short user needs to log in twice to work everything perfect.
Basically I want two solutions one I want to redirect www dot
domain dot com/example dot php/abcdefgh97654 - anything (wrong url
page) to errorpage (I already done this in htaccess) but does not
work for above type.
List item
And want to solve two time log in problem.
If anyone has solution for this will be appreciated.
For you to do this, you have to know what values are supposed to be passed via $_GET variable to your page. Then you can create filter for the values and user header(); function.
Here is my suggestion:
<?php
$var=$_GET['val']
//get expected length if you need.
if(strlen($var)>9 or strlen($var)) {
$redirect=true;
}
//if you know what you are expecting
$vals=array('val1', 'val2, 'val3');
if(!in_array($var, $vals)){
$redirect=true;
}
//continue or replace your filters in this manner and asign your value to $redirect
if($redirect==true) {
header("Location:url"); // do this before anything else is printed to the page or else it will say headers already sent.
}
?>

problems using 'header' in php to redirect on load

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

Naming a $_SESSION var from $_SERVER['REQUEST_URI'] keeps mysteriously naming the page "blank.gif"

Seems like such a simple problem but I'm out of options here...
So I want to set up a session variable that tells me the last page visited. I thought I could do this by declaring 2 session variables in a php include at the top of every page.
session_start();
if(!$_SESSION['this_url']){
// will only be declared once
$_SESSION['this_url'] = $_SERVER['REQUEST_URI'];
}
if($_SERVER['REQUEST_URI'] != $_SESSION['this_url']){ //dont update var on page refresh
$_SESSION['last_url'] = $_SESSION['this_url'];
$_SESSION['this_url'] = $_SERVER['REQUEST_URI'];
}
Simple enough right? But for an output it gives me this:
$_SESSION['this_url'] = /support/interactive.php (correct)
$_SESSION['last_url'] = /products/compatibility/blank.gif (right path, but blank.gif? wtf?)
it SHOULD be outputting "/products/compatibility/somepage.php" but it always replaces the page name with blank.gif.
I did a sitewide search on my site and nothing else is using my variable names. I even changed the var names and still same result. blank.gif is found in some jQuery scripts - so I suspect this may be where its coming from. But still... I'm declaring these things as the first piece of script on the page and outputting them immediately after declaring them. Is my Apache server messed up or what? this doesnt make sense.
Any ideas would be greatly appreciated, thanks!
Hmm, I remember trying to do something like this a while back, and I was having odd ghost problems much like you. What I ended up doing was using hidden inputs and assigning the variables to them.
I'm not saying use hidden form elements for production, I'm just making a suggestion in case the feature you are creating is a "need now" kind of feature.
I'm still looking as to why that may happen though, what version of Apache/PHP are you running?

PHP: Redirect to the same page, changing $_GET

I have this PHP piece of code that gets $_GET['id'] (a number) and do some stuff with this.
When its finished I need to increase that number ($_GET['id']) and redirect to the same page but with the new number (also using $_GET['id']).
I am doing something like this:
$ID = $_GET['id'];
// Some stuff here
// and then:
$newID = $ID++;
header('Location: http://localhost/something/something.php?id='.$newID);
exit;
The problem here is that the browser stop me from doing it and I get this error from the browser (Firefox) : "The page isn't redirecting properly. Firefox has detected that the server is redirecting the request for this address in a way that will never complete."
Some help here please!
NOTE: Some people suggested to do an internal loop, I mean a simple 'for' loop, but when i do this I get a time limit error (60 seconds) because the loop will take more time to finish..
It's an endless loop, each time the page loads, it changes the $_GET['id'] and redirects to itself again. You need a way to detect that the value is how you want it (final) and skip the redirect.
I suggest you add a second parameter after incrementing id, such as final so that when the page loads the second time, it skips the redirect because final was set.
i.e.:
if ($_GET['final'] != 1)
{
header('Location: http://localhost/something/something.php?id=' . $newID . '&final=1');
}
I think because the browser is in an endless loop.
If that code you posted is also on the something.php then it will always increment the number.
Also, there is no reason to do $newID = $ID++ because the ++ operator will increment that operand ($ID) automatically.
What you want is some form of logic to stop the loop. Perhaps...
if ($ID > 3) {
// don't redirect
}
However I can't really see how redirecting as a loop is ever a good idea, unless you are trying to do something that may be better achieved by a background process or cron job.
I would suggest that you redesign what you are doing. Redirecting back to self should never happen more than once, without a user input required to continue a loop.
As soon as the browser see's even the slightest possibility of and endless loop it will crash it. Even if you have if ($ID == 100) {..STOP..} by the time you reach 100 the browser will have already broken your loop, simply because by industry standards, that is immediately considered bad design and that is why your browser is already programmed to stop such a thing to begin with.
Can you share what it is you are actually trying to do with this loop. I am sure someone has a way to achieve what you want without doing it that way.
UPDATE TO COMMENT
Then you may want to look into AJAX or PHP API. I see what you mean, and want to do, that needs to be done in a controlled environment as opposed to a loop. The browser will never allow that kind of loop. So, there are a few ways to do that. You can do it with a client-side method where php delivers you a page to ajaxify the content from one source to another source. Or strictly php using php API methods to fetch the content and bring it directly back to the server. However, neither case is a beginners concept. :) if you know what I mean.
ob_start();
session_start();
if ( $_SESSION["id_old"] == $_GET['id']){ return false;}
$ID = $_GET['id'];
$newID = ++$ID;
$_SESSION["id_old"]= $newID;
header('Location: http://localhost/something/something.php?id='.$newID);
exit;
test localhost/something/something.php?id=22 -> localhost/something/something.php?id=23 return false;
It looks like you're trying to scrape a large amount of data from an external source. Why don't you run it as a local script on your own computer instead of through the browser? Then you don't have to worry about your script timing out or the browser detecting infinite redirects.
Well the answer is to do it locally in my localhost, using a 'for' loop and set_time_limit(0) to set the deafult 60 second limit of PHP to 0 (infinite) and not redirecting to the same page over and over again.

Stop people from refreshing the page

Is there anyway for me to make it work so anyone who presses F5 or any refresh button will be moved to a different page, instead of it refreshing the page the user wants?
Something like :
If (refresh){
goto "link to hopme page"
}
If not is there anyway for me to not allow refreshing on a certain page?
I have some people that are are just refreshing non stop and it is killing my bandwidth. It is a game site so I don't want to ban the ip's.
Perhaps you should be focusing your effort instead on reducing the bandwidth your page is using. Explore the areas of image compression, page optimization and caching.
session_start();
if($_SESSION['hasbeenhere'] == 1)
{
// Page refreshed
}
else
{
$_SESSION['hasbeenhere'] = 1;
}
If the person doesn't have cookies enabled, this will fail. If someone goes to another page and comes back, it will shown as refreshed.
Overall, you can't do this in a way that is surefire, but this is 1 way to prevent someone from seeing the same page twice.
Because of your comment, if you want to stop people from pressing F5 200 times, try this.
$page = $_SERVER['REQUEST_URI'];
// Defaults
if(!isset($_SESSION[$page]['count']))
{
$_SESSION[$page]['count'] = 1;
$_SESSION[$page]['first_hit'] = time();
$_SESSION[$page]['banned'] = false;
}
else
{
$_SESSION[$page]['count']++; // Increase the counter
}
// If person is banned, end script
if($_SESSION[$page]['banned'] == true)
{
die();
}
if($_SESSION[$page]['first_hit'] < time() - 30)
{
$_SESSION[$page]['count'] = 1; // Reset every 30 seconds
}
if($_SESSION[$page]['count'] > 100)
{
$_SESSION[$page]['banned'] = true;
// Ban if they hit over 100 times in 30 seconds.
}
Why would you want to?
But no, there's no way that'll work consistently that can stop this.
In your PHP code, do the following:
if(isset($_SESSION["pagename-LAST_VIEWED"])) {
v = $_SESSION["pagename-LAST_VIEWED"])
if(time() - v < 15) {
// user is refreshing more than once per 15 seconds
// send them something else and die
}
}
$_SESSION["pagename-LAST_VIEWED"] = time();
Please ignore my crummy pseudo-PHP, it's not my daily language.
This will prevent both a page refresh (F5) and the user just clicking the bookmark again or pressing Enter in the address bar again.
You could also enable some aggressive caching meta tags and HTTP headers, which will prevent some refreshes from ever hitting your server, but the above code should be pretty scalable.
Another thing to consider: the root problem is your other code, not your users. Consider rewriting your page so it auto-updates the part they want to see via AJAX on a timed delay. This will give them incentive not to use Refresh, and will help your server cope by only having to refresh the small bit of data they want to see updated.
I have no idea if this would work, but could you listen for keystrokes with javascript, and on F5 keypress, do what you want.
I guess you could do this:
session_start();
if (isset($_SESSION['visited'])) {
header("Location: http://the.page/you/want");
} else {
$_SESSION['visited'] = true;
}
In order to stop F5 from refreshing, you'd have to not allow refreshing of any type. As a hack, you could try putting a timestamp in the querystring. On load, you can check the value of the timestamp and if it is in the past, redirect to another page. This would work if cookies are disabled.
The site itself does this with Javascript, so when you're editing something, you don't loose it by refreshing, going back, etc. There's probably some event defined by JQuery that lets you do this, so look into that, and on that event, redirect to the page you want (probably has to be within the same domain).
It seems to me that there is no good technical solution to this problem (the other answers covered that pretty well). If the users are constantly hitting refresh on this page, I'm guessing it's because they expect the page to change and they want up-to-the-second information. Perhaps you should take away their reason for wanting to refresh the page. The easiest way to do this would probably be making the page update itself (likely via AJAX). Thus the user can sit there and updates will just roll in -- no more hammering F5, which will cut down on your bandwidth, not to mention be a better user experience.
I just find out a very simple solution.
For me after i process all the $_POST information and save the ones i need into a $_SESSION var i do this:
$_SESSION['admin']['PID']=session_id();
$_SESSION['admin']['user_user']=$_POST['user'];
$_SESSION['admin']['user_pass']=$_POST['pass'];
$_SESSION['admin']['last_access_time']=time();
if($_SERVER['REQUEST_METHOD']==="POST")
{
header("LOCATION:".$_SERVER['PHP_SELF']."?p=redirected");
}
In my case i was trying to validate the user, and i have the problem that when someone logout and and go back and refresh the site load again, and with this simple if i finally solved it.
PD: ."?p=redirected" is only for testing porpouse
It's not answering your question directly but you can probably solve your issue with caching can't you?
If you send a header
Cache-Control: public,max-age=120
That should instruct the browser that it doesn't need to request the page again for 2 minutes and can just use the copy from it's cache. If course they can use control-f5 to force a refresh but it ought to help a lot?

Categories