We help IT Professionals succeed at work.

PHP Page Counter Then Redirect User to Different URL

azlumiere asked
Medium Priority
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:


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

/*script for reading the text file*/


/*script for adding 1 to the file*/



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!!
Watch Question

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


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.


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)
Here is one more example. You can do the counter and then place this code in your script.



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


Brilliant! Worked like a charm!


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.


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.