98
496
Chapter 23 Other Useful Features
The same problem occurs with user input, as well as input and output to or from
other programs.
Trying to run a
mysql
query like
insert into company values (‘Bob’s Auto Parts’);
produces similar confusion in MySQL’s parser.
We have already looked at the use of
addslashes()
and
stripslashes()
that escape
out any single quotation mark,double quotation mark,backslash,and NULL characters.
PHP has a useful capability to automatically or magically add and strip slashes for
you.With two settings in your
php.ini
file,you can turn on or off magic quoting for
GET
,
POST
,cookie data,and other sources.
The value of the
magic_quotes_gpc
directive controls whether magic quoting is used
for
GET
,
POST
,and cookie operations.
With
magic_quotes_gpc
on,if somebody typed
“Bob’s Auto Parts”
into a form
on your site,your script would receive
“Bob\’s Auto Parts”
because the quote is
escaped for you.This behavior can be very handy,but you need to know that it is hap-
pening so you can remember to remove the slashes before echoing the data back to your
users.This is easy if your code runs on one server,but if you are writing code to distrib-
ute,you might want to make it work with or without magic quotes.
The function
get_magic_quotes_gpc()
returns either
1
or
0
,telling you the
current value of
magic_quotes_gpc
.This is most useful for testing if you need to use
stripslashes()
on data received from the user.
The value of
magic_quotes_runtime
controls whether magic quoting is
used by functions that get data from databases and files.To get the value of
magic_quotes_runtime
,use the function
get_magic_quotes_runtime()
.This function
returns either
1
or
0
.Magic quoting can be turned on for a particular script using the
function
set_magic_quotes_runtime()
.
By default,
magic_quotes_gpc
is on and
magic_quotes_runtime
is off.
Evaluating Strings:
eval()
The function
eval()
evaluates a string as PHP code.For example,
eval ( “echo ‘Hello World’;” );
takes the contents of the string and executes it.This line produces the same output as
echo ‘Hello World’;
The function
eval()
can be useful in a variety of cases.You might want to store blocks
of code in a database,retrieve them,and then evaluate them at a later point.You also
might want to generate code in a loop and then use
eval()
to execute it.
The most common use for
eval()
is as part of a templating system.You can load a
mixture of HTML,PHP,and plain text from a database.Your templating system can apply
formatting to this content and then run it through
eval()
to execute any PHP code.