foreach (array('SCRIPT_NAME', 'SERVER_ADMIN', 'SERVER_NAME',
'SERVER_PORT', 'SERVER_SOFTWARE') as $key) {
define($key, isset($_SERVER[$key]) ? $_SERVER[$key] : '');
unset(${$key}, $_SERVER[$key], $HTTP_SERVER_VARS[$key]);
}
function die_message($msg)
{
echo htmlspecialchars($msg);
die();
}
function is_url($str, $only_http = FALSE)
{
$scheme = $only_http ? 'https?' : 'https?|ftp|news';
return preg_match('/^(' . $scheme . ')(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]*)$/', $str);
}
function get_script_uri($init_uri = '')
{
global $script_directory_index;
static $script;
if ($init_uri == '') {
// Get
if (isset($script)) return $script;
// Set automatically
$msg = 'get_script_uri() failed: Please set $script at INI_FILE manually';
$script = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
$script .= SERVER_NAME; // host
$script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT); // port
// SCRIPT_NAME が'/'で始まっていない場合(cgiなど) REQUEST_URIを使ってみる
$path = SCRIPT_NAME;
if ($path{0} != '/') {
if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
die_message($msg);
// REQUEST_URIをパースし、path部分だけを取り出す
$parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
die_message($msg);
$path = $parse_url['path'];
}
$script .= $path;
if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
die_message($msg);
unset($msg);
} else {
// Set manually
if (isset($script)) die_message('$script: Already init');
if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
$script = $init_uri;
}
// Cut filename or not
if (isset($script_directory_index)) {
if (! file_exists($script_directory_index))
die_message('Directory index file not found: ' .
htmlspecialchars($script_directory_index));
$matches = array();
if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
$script, $matches)) $script = $matches[1];
}
return $script;
}
$uri = get_script_uri();
echo htmlspecialchars($uri);
exit();