I've been wrestling with some complication with sessions and domains names recently, so
this thread on comp.lang.php caught my attention. It says basically, if you're not careful, you could have a user on your site lose their session if they were to somehow move from say http://yourdomain.com to http://www.yourdomain.com, your user will lose their session.
I offer my solution to this problem
here (I think this is the same concept used by most popular applications such as Joomla). The functions below may also be useful. The first has evolved over a long period of time. It hasn't failed me yet, though I don't know that it is the optimal solution to this particular challenge.
// filepath_to_url
/*____________________________________________________________________________*/
function amvc_filepath_to_url($filepath)
{
// *** DATA
// internal
$_slash = '/';
$_url_rel = '';
// paths
$PATH = array();
$PATH['file'] = amvc_normalize_path($filepath, $_slash);
$PATH['www'] = 'http://' . $_SERVER['HTTP_HOST'] . $_slash;
// directory arrays
$_DIRS = array();
$_DIRS['filepath'] = explode($_slash, $PATH['file']);
$_DIRS['doc_root'] = explode($_slash, amvc_normalize_path($_SERVER['DOCUMENT_ROOT'],$_slash));
$_DIRS['diff'] = '';
// return
$url = '';
// *** MANIPULATE
// * DEBUG
#trigger_notice($filepath);
#trigger_notice($_DIRS);
// path is url
if ( preg_match('%^(http)s?://%i', $PATH['file']) ) return $PATH['file'];
// compute path differences
$_DIRS['diff'] = array_values(array_diff($_DIRS['filepath'], $_DIRS['doc_root']));
// DEBUG
#trigger_notice($_DIRS);
// shift empty cells
if ( empty($_DIRS['diff'][0]) ) array_shift($_DIRS['diff']);
// get URL relative path
$_url_rel = implode('/', $_DIRS['diff']);
// build URL
$url = $PATH['www'] . $_url_rel;
// *** RETURN
return $url;
}
/*____________________________________________________________________________*/
// amvc_normalize_path
/*____________________________________________________________________________*/
function amvc_normalize_path($path, $slash)
{
// *** DATA
// internal
$_ds = DIRECTORY_SEPARATOR;
// return var
$new_path = '';
// *** MANIPULATE
// replace forward slashes
$new_path = str_replace('/', $slash, $path);
// replace backslashes
$new_path = str_replace('\\', $slash, $new_path);
// *** RETURN
return $new_path;
}
/*____________________________________________________________________________*/