PHP Splash Intro Page | Cookie | Redirect

I have the following situation that I am struggling with. I need to display an intro page before the main website home page, but it should only appear once per visitor. I think the method would be this:

First Visit:
index.php loads and writes cookie

Second Visit:
index.php loads and reads cookie
     If cookie exisits, redirect to home.php

What is the best way to accomplish this? I would need to know the [PHP?] code for writing and reading cookies as well as how to redirect to another page based on the existence of the cookie.

[I understand that if the user clears their cache that the cookie goes along with it]
jsvb1977Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

yauhingCommented:
You may use Javascript to store the cookie in client browser.
<script type="text/javascript">
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
 
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
 
function eraseCookie(name) {
	createCookie(name,"",-1);
}
 
 
if (readCookie("visited") == "1"){
	// if cookie already exists, go to home.php
	document.location = "home.php";
} else {
	// if cookie not exist, create it.
	createCookie("visited","1",30);
};
</script>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jonavogtCommented:
The Snippet below does the tric. You could also leve the second redirect out and put the page there.
<?
if(isset($HTTP_COOKIE_VARS["not_first_visit"]))
	header("Location: home.php");
else
{
	setcookie("not_first_visit", true);
	header("Location: intro.php");
}

Open in new window

0
Ionut A. TudorPHP ProgrammerCommented:
For further notice try not to use the deprecated $HTTP_COOKIE_VARS because if the verification process takes place inside a function the variable won't be available. It stopped being used years ago when it was replaced with the superglobal $_COOKIE which is available through entire script no matter where it is called.
Cheers
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Ionut A. TudorPHP ProgrammerCommented:
[I understand that if the user clears their cache that the cookie goes along with it]
Yes thats true, in that case you could store the visitors ip address into database for a day and when visitor comes you check the database to see the ip and if it's there you redirect them.
0
Ray PaseurCommented:
The IP-in-the-database method assumes that the client has the same IP address assigned each time, and that only the client has this IP address.  Some ISPs dynamically reassign IP addresses, so this will play havoc with their access to the site.  Some servers give all their clients the same IP address (think office systems) so only one of them will see the splash page.

A better strategy is to accept the limitations of the cookie system and live with it.  Clients lose cookies all the time.  We just make them log in again!
0
Ray PaseurCommented:
You can handle all of this in one PHP script.  Try running this example and post back here if you have any questions.  Best regards, ~Ray
0
Ray PaseurCommented:
<?php // RAY_cookie_splash_page.php
error_reporting(E_ALL);

// SHOW A SPLASH PAGE ON FIRST ENTRY, THEN COOKIE THE BROWSER TO SKIP SPLASH PAGE
// TO SEE COOKIES IN FIREFOX, FOLLOW TOOLS => OPTIONS => PRIVACY => SHOW COOKIES
// MAN PAGE: http://us.php.net/manual/en/function.setcookie.php



// DEFINITIONS AS NEEDED HERE
define('COOKIE_LIFE', 60*60*24); // A 24-HOUR DAY IN SECONDS ( = 86,400 )



// CONSTRUCT AND SET THE COOKIE
// USE THIS TO MAKE COOKIE EXPIRE AT END OF BROWSER LIFE
$cookie_expires = 0;

// USE THIS TO MAKE A PERSISTENT COOKIE - DEFINE COOKIE_LIFE IN SECONDS - date('Z') IS UTC OFFSET IN SECONDS
$cookie_expires = time() + date('Z') + COOKIE_LIFE;

// CHOOSE THE COOKIE NAME AND VALUE
$cookie_name  = 'Fred';
$cookie_value = 'Wilma';

// MAKE THE COOKIE AVAILABLE TO ALL DIRECTORY PATHS IN THE WWW ROOT
$cookie_path      = '/';

// MAKE THE COOKIE AVAILABLE TO ALL SUBDOMAINS - DOMAIN NAME STARTS WITH DOT AND OMITS WWW (OR OTHER SUBDOMAINS).
$x = explode('.', strtolower($_SERVER["HTTP_HOST"]));
$y = count($x);
if ($y == 1) // MAYBE 'localhost'?
{
   $cookie_domain = $x[0];
} else // SOMETHING LIKE 'www2.atf70.whitehouse.gov'?
{
// USE THE LAST TWO POSITIONS TO MAKE THE HOST DOMAIN
   $cookie_domain = '.' . $x[$y-2] . '.' . $x[$y-1];
}

// MAKE THE COOKIE AVAILABLE TO HTTP, NOT JUST HTTPS
$cookie_secure = FALSE;

// HIDE COOKIE FROM JAVASCRIPT TO IMPROVE SECURITY (PHP 5.2+)
$cookie_http  = TRUE;

// SET THE COOKIE (BUT DO NOT BOTHER OUTPUTTING THE DEBUGGING MESSAGES)
if (setcookie($cookie_name, $cookie_value, $cookie_expires, $cookie_path, $cookie_domain, $cookie_secure, $cookie_http))
{
// echo "<br/>SUCCESS!  THE COOKIE HAS BEEN SET AND WILL BE AVAILABLE TO THE NEXT PAGE LOAD \n";
} else {
// echo "<br/>FAILURE!  THE COOKIE WAS NOT SET AS EXPECTED \n";
}



// IF THE COOKIE IS NOT AVAILABLE IN THIS SCRIPT, SHOW THE SPLASH PAGE
if (empty($_COOKIE["Fred"]))
{
   echo "<h1>SPLASH PAGE</h1>\n";
   echo "<p><a href=\"{$_SERVER["REQUEST_URI"]}\">CONTINUE TO SITE</a></p>\n";
   echo date('c');
   die("\nSPLASH COMPLETE");
}

// SPLASH PAGE HAS ALREADY BEEN SHOWN
echo "<h1>REGULAR START PAGE - AFTER SPLASH HAS BEEN SHOWN</h1>\n";
echo "<p><a href=\"{$_SERVER["REQUEST_URI"]}\">CONTINUE TO SITE</a></p>\n";
echo date('c');
die("\nREGULAR PAGE COMPLETE");
0
Ray PaseurCommented:
Sorry - I mean to post in the code snippet and missed the box!

D'OH!
<?php // RAY_cookie_splash_page.php
error_reporting(E_ALL);
 
// SHOW A SPLASH PAGE ON FIRST ENTRY, THEN COOKIE THE BROWSER TO SKIP SPLASH PAGE
// TO SEE COOKIES IN FIREFOX, FOLLOW TOOLS => OPTIONS => PRIVACY => SHOW COOKIES
// MAN PAGE: http://us.php.net/manual/en/function.setcookie.php
 
 
 
// DEFINITIONS AS NEEDED HERE
define('COOKIE_LIFE', 60*60*24); // A 24-HOUR DAY IN SECONDS ( = 86,400 )
 
 
 
// CONSTRUCT AND SET THE COOKIE
// USE THIS TO MAKE COOKIE EXPIRE AT END OF BROWSER LIFE
$cookie_expires = 0;
 
// USE THIS TO MAKE A PERSISTENT COOKIE - DEFINE COOKIE_LIFE IN SECONDS - date('Z') IS UTC OFFSET IN SECONDS
$cookie_expires = time() + date('Z') + COOKIE_LIFE;
 
// CHOOSE THE COOKIE NAME AND VALUE
$cookie_name  = 'Fred';
$cookie_value = 'Wilma';
 
// MAKE THE COOKIE AVAILABLE TO ALL DIRECTORY PATHS IN THE WWW ROOT
$cookie_path	= '/';
 
// MAKE THE COOKIE AVAILABLE TO ALL SUBDOMAINS - DOMAIN NAME STARTS WITH DOT AND OMITS WWW (OR OTHER SUBDOMAINS).
$x = explode('.', strtolower($_SERVER["HTTP_HOST"]));
$y = count($x);
if ($y == 1) // MAYBE 'localhost'?
{
   $cookie_domain = $x[0];
} else // SOMETHING LIKE 'www2.atf70.whitehouse.gov'?
{
// USE THE LAST TWO POSITIONS TO MAKE THE HOST DOMAIN
   $cookie_domain = '.' . $x[$y-2] . '.' . $x[$y-1];
}
 
// MAKE THE COOKIE AVAILABLE TO HTTP, NOT JUST HTTPS
$cookie_secure = FALSE;
 
// HIDE COOKIE FROM JAVASCRIPT TO IMPROVE SECURITY (PHP 5.2+)
$cookie_http  = TRUE;
 
// SET THE COOKIE (BUT DO NOT BOTHER OUTPUTTING THE DEBUGGING MESSAGES)
if (setcookie($cookie_name, $cookie_value, $cookie_expires, $cookie_path, $cookie_domain, $cookie_secure, $cookie_http))
{
// echo "<br/>SUCCESS!  THE COOKIE HAS BEEN SET AND WILL BE AVAILABLE TO THE NEXT PAGE LOAD \n";
} else {
// echo "<br/>FAILURE!  THE COOKIE WAS NOT SET AS EXPECTED \n";
}
 
 
 
// IF THE COOKIE IS NOT AVAILABLE IN THIS SCRIPT, SHOW THE SPLASH PAGE
if (empty($_COOKIE["Fred"]))
{
   echo "<h1>SPLASH PAGE</h1>\n";
   echo "<p><a href=\"{$_SERVER["REQUEST_URI"]}\">CONTINUE TO SITE</a></p>\n";
   echo date('c');
   die("\nSPLASH COMPLETE");
}
 
// SPLASH PAGE HAS ALREADY BEEN SHOWN
echo "<h1>REGULAR START PAGE - AFTER SPLASH HAS BEEN SHOWN</h1>\n";
echo "<p><a href=\"{$_SERVER["REQUEST_URI"]}\">CONTINUE TO SITE</a></p>\n";
echo date('c');
die("\nREGULAR PAGE COMPLETE");

Open in new window

0
jsvb1977Author Commented:
Thank all of you for your assistance! I have the following to report:

The JavaScript Solution worked perfectly.

When used in combination with the second [short] php script, the  splash page never loaded and I was automatically redirected to home.php.

The last [long] php script did not work at all -- all it did was echo "Splash Page" -- and after really looking at the code, I am not sure if it was written to do exactly what I needed it do.

In summary -- although I am pleased with the JavaScript solution simply because it works, i typically prefer server side scripting when possible -- so i am willing to keep trying with php ideas. Let me know your thoughts.

Jason


0
Ray PaseurCommented:
@jsvb1977: if by the "last [long] php script" you mean the one that I posted for you, I would like you to post a link to where you tested it.  There may be something wrong with the PHP configuration if it did not work.  I tested it on my web site here before I posted it:
http://www.laprbass.com/RAY_cookie_splash_page.php

I do not know why you would want to redirect, when you can simply load the page you want to show to the client.  The code above might have a PHP include() statement to load the splash page at line 60, if the page was so elaborate that you did not want to build its code right into the PHP script.  That is all you have to do - it really is very simple, and keeps all your code in one place.

As far as Javascript goes, that is one solution, but JS cookies have gotten a bit of a bad rap because JS can be used to steal cookie information, making web sites less secure.  PHP and modern browsers now include the option to hide the cookies from Javascript for exactly that reason, and I would never release a cookie to Javascript if I could avoid it.

And there is the issue that a client may have Javascript turned off, however very few people do that in practice.

Please show us the link where you tested my script and it did not work.  Also, if you want to post the phpinfo() output for that host, we may be able to tell you if there is something awry in your PHP setup.

Thanks and regards, ~Ray
0
jsvb1977Author Commented:
Ray,

yes the script operated the same way on my localhost as it did following your link above. And yes, the splash page is elaborate enough that I would prefer not to build it inside the code listed above. I am at least a day away from uploading these pages for review. I will post again at that time.

Thank you for your feedback.

Jason
0
Ray PaseurCommented:
So in addition to loading and writing a cookie, what would you have the index.php page do on the first visit?
0
jsvb1977Author Commented:
There will be essentially flash animation [or three] coupled with some simple html and css.
0
jonavogtCommented:
You said you used it the short php script in combination with the javascript. There is no need to use the javascript at all.
al3cs12 was right about the cookie var. I missed that, just took a quick search trough my code base and found the snippet above which has some years on its back.
The snipped below works the way you want it.

A redirect has the advantage that the user is able to see the intro if he wants to by just using the intro url.

Regargs
<?
if(isset($_COOKIE["not_first_visit"]))
        header("Location: home.php");
else
{
        setcookie("not_first_visit", true);
        // You could also simply insert the page below or include the page instead of the header function
        header("Location: intro.php");
}

Open in new window

0
Ray PaseurCommented:
@jsvb1977: "flash animation [or three] coupled with some simple html and css."

For that, I would use an include() statement to bring in the information you wanted to show the client.

If you choose to use the redirect, you need to be aware of something about the PHP header() command, that is often overlooked and almost always causes idiosyncratic problems in production sites.  The header() command is a synchronous part of your script.  It sends information to the client machine AND YOUR SCRIPT KEEPS RIGHT ON RUNNING until the browser sends back a signal to move to a new page, or take some other action.  Thus, header("Location") as shown in innumerable examples, including some on this thread, will cause your server to send the redirect command, then keep executing other code, stopping at an unpredictable time when the browser has received the redirect command and sent its request back to the server with the new URL.  Since the lag time is affected by line speed, latency, server load, etc., you almost certainly need a way to make the script stop after you have sent the redirect command.  That is shown in the code snippet.  You might also want to read up on HTTP headers so you know whether and what to send in addition to the Location statement. Learning resources are here:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
http://en.wikipedia.org/wiki/List_of_HTTP_headers
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Best regards, ~Ray

// REDIRECT BROWSER TO A NEW LOCATION AND STOP EXECUTION OF SCRIPT 
header("Location: /home.php");
exit;
 
// THIS WILL NOT GET EXECUTED BECAUSE OF THE EXIT STATEMENT
echo "XXX";

Open in new window

0
jsvb1977Author Commented:
man, there is a lot of information on this thread to consider. If I understand it all, some suggest using JS to write and read the cookie -- then based on the existence of the cookie, a redirect will occur. Others recommend not using a redirect at all and instead using php to decide which content is shown in the index.php based on the existence of the cookie.

I agree that using JS would not be best so I will try implementing a php solution. Here are my thoughts on this:

1. I normally do not recommend to my clients the use of a splash page for reasons of SEO. On this project they insisted. I also understand the repercussions of using redirects.
2. It would be ideal to have only one index.php that dynamically displayed content attached through the use of includes based on the existence of a cookie. I think I will attempt this type of implementation.

Do I need to be careful that each include will not be indexed by a search engine? Ideally, I would wish that the splash page never be indexed.

Please share your thoughts on this plan as I will be working on this over the next few days -- should have something up for review by Friday or Saturday night.

Jason

0
Ray PaseurCommented:
You can use meta tags to have some control over the indexing by the search engine.  Perhaps a better way to think about this is to load up the splash page with all the SEO keywords.  Here is why: Let's say you are selling dog ramps, and I do a search for dog ramps.  If the splash page is indexed and it is the home page of the site, I may go look at it.  One click to continue is not too much to ask of a client.  If there are direct, "deep links" into the site, so much the better, but I would not miss the chance to make the splash page a target link.

Regarding this: "Do I need to be careful that each include will not be indexed by a search engine?"  The answer is that each HTML page will be indexed.  An HTML page may be made up from lots of include() statements, but the search engines will not see the PHP behind the page - just the generated HTML.

I like to concentrate my SEO efforts on the page title, meta description, H1 tags and meta keywords, in that order.  I often use CSS to make the H1 tags invisible on the screen or printout, and just use them to contain topic words that are appropriate to the page.

Best of luck with it, ~Ray
0
jsvb1977Author Commented:
Still engaged and interested in this topic -- been busy lately and have not tested some of the other methods aside from the JavaScript one. In fact, a discussion I had with my client revealed that they actually want the splash page to play only "once per session." A session, they described, will last for one day.

 I think that making the cookie expire after a 12 hour period will be best, so i will eventually start a new thread on cookie expiration. It looks like using the JavaScript method listed above will allow me to define the expiration date of the cookie. In the code, i think it is set to 30.

I will need to investigate how to do this using PHP should that be the method I will eventually use when I go live with the site.

Thanks to all.

Jason
0
Ray PaseurCommented:
JavaScript cookies are not very secure, and you might want to know the risks before you go down that dark path - but that is a different topic entirely.  

You can use PHP setcookie() to accomplish your goals on the server side.  Please see my code and notes at # 24748580, above. That was where I showed you EXACTLY how to accomplish this, including a session duration of exactly one day.

Best regards, and good luck with the project, ~Ray
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.