We help IT Professionals succeed at work.

PHP Page Counter Then Redirect User to Different URL

azlumiere
azlumiere asked
on
Medium Priority
481 Views
Last Modified: 2012-08-13
Hi All,

I need to run some tests to make sure a banner ad is tracking properly. I'd like to set up a page that, if visited, writes to a file and then redirects the user to a new URL (without the user noticing anything). I have this php file:

counter.php

<?
header( "HTTP/1.1 301 Moved Permanently" );
header( "Status: 301 Moved Permanently" );
header( "Location: http://www.domain.com/" );
exit(0); // This is Optional but suggested, to avoid any accidental output
?>
<?php
$filename='count.txt';

/*script for reading the text file*/

$line=file($filename);

/*script for adding 1 to the file*/

$fp=fopen($filename,'w+');
fwrite($fp,($line[0]+1));
fclose($fp);
?>

------------------------------

And a file called "count.txt" to write to in the same directory as the count.php file (with permissions set properly). When I type in the URL of count.php it redirects properly to domain.com, but the text file always shows "1". It doesn't seem to increase the count. This has to be something terribly stupid on my part.

Might anyone have an idea on how I can remedy this and get it to work right?  I just need to see a simple page view count in the text file for comparison purposes.

Many thanks!!
Comment
Watch Question

Do the redirection after you add the counter to the txt file.

Author

Commented:
Hi PranjalShah,

I thought of that too, and tried moving the redirect down, but then I get an error on the page:  Warning: Cannot modify header information - headers already sent by

Is there another way to do a redirect that won't break the page? This is the only way I know to set it up.

Thank you for responding!!
Other way is you can do the counter on the http://www.domain.com page itself. You can check the referrer for that page. If the $_SERVER['HTTP_REFERER'] is your first page than do the counter.

Author

Commented:
Well, unfortunately in my case domain.com is the advertiser's website, so I have no control over it. I have to try and get it to work before I get the user to the advertisers site.
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Here is one more example. You can do the counter and then place this code in your script.

http://www.web-source.net/javascript_redirect.htm

Author

Commented:
Ah, very cool. I will take a look at this...

Author

Commented:
Brilliant! Worked like a charm!

Author

Commented:
Thanks for your help!!
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.