if (!defined("X")) {
echo "You Cannot Access This Script Directly, Have a Nice Day.";
exit();
}
This one is nice, actually for half an hour I was searching for an idea or a tip how to protect some files that must be accessed only if are included in another file ( that would admin.php). This one would perfectly do the trick.
Thanks a lot!
defined
(PHP 4, PHP 5)
defined — 指定した名前の定数が存在するかどうかを調べる
説明
bool defined
( string $name
)
指定した定数が存在し、定義されているかどうかを調べます。
注意: 変数が存在するかどうかを知りたければ、isset() を利用してください。defined() は 定数にしか適用できません。 関数が存在するかどうかを知りたければ、 function_exists() を利用してください。
パラメータ
- name
-
定数名。
返り値
name で指定した名前の定数が定義されている 場合に TRUE、その他の場合にFALSEを返します。
例
例1 定数のチェック
<?php
/* 引用符の使い方に注意してください。これは重要です。この例では
* 文字列 'CONSTANT' が、定数 CONSTANT の名前かどうかを調べています。*/
if (defined('CONSTANT')) {
echo CONSTANT;
}
?>
defined
admin at baceto dot com
18-Apr-2008 06:57
18-Apr-2008 06:57
Shaun H
29-Mar-2008 04:30
29-Mar-2008 04:30
I saw that PHP doesn't have an enum function so I created my own. It's not necessary, but can come in handy from time to time.
<?php
function enum()
{
$args = func_get_args();
foreach($args as $key=>$arg)
{
if(defined($arg))
{
die('Redefinition of defined constant ' . $arg);
}
define($arg, $key);
}
}
enum('ONE','TWO','THREE');
echo ONE, ' ', TWO, ' ', THREE;
?>
Joel
20-Aug-2007 09:35
20-Aug-2007 09:35
If your constants don't show up in your included or required files, then you probably have php safe mode turned on!
I ran into this problem, I forgot to turn of safe mode when I was creating a new site.
Harald Ponce de Leon
19-May-2006 12:24
19-May-2006 12:24
Beware that some PHP versions return an integer (1 or 0) instead of a boolean.
Confirmed PHP versions that return an integer are 4.3.2 and 4.3.4.
Relevant bug report:
http://bugs.php.net/bug.php?id=27443
This make it impossible to use the following, when the PHP version is not known:
if (defined('CONSTANT') === true) {
}
Relevant commit for PHP 4.3.5 (thanks to Pollita at #php.thinktank):
http://cvs.php.net/viewcvs.cgi/Zend/zend_builtin_functions.c?
r1=1.124.2.13&r2=1.124.2.14
ndove at cox dot net
28-Jan-2005 12:20
28-Jan-2005 12:20
In PHP5, you can actually use defined() to see if an object constant has been defined, like so:
<?php
class Generic
{
const WhatAmI = 'Generic';
}
if (defined('Generic::WhatAmI'))
{
echo Generic::WhatAmI;
}
?>
Thought it may be useful to note.
-Nick
Craig at chatspike dot net
01-Dec-2003 04:57
01-Dec-2003 04:57
This can be useful if you want to protect pages which get included from outsiders eyes, on your mail page (the page viewable by people) put define("X", null); then on all your other pages, you can then do something like:
if (!defined("X")) {
echo "You Cannot Access This Script Directly, Have a Nice Day.";
exit();
}
And your page is a good as protected :)