Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

You can use the number_format() function to add commas that sepa-

rate thousand values and determine the number of decimal places

to display. Even if you use the printf() or sprintf() function, you

need to use the number_format() function to add commas to sepa-

rate thousands in a number. However, you should understand that the

number_format() function also converts numeric variables to strings.

For this reason, you must use the s type specifier in a conversion

specification to refer to a numeric variable that has been converted to

a string with the number_format() function. For example, the follow-

Ing code uses the number_format() function to add comma separa-

tors and two decimal places to the $Payment variable. Because the

number_format() function converts the $Payment variable to a string,

the printf() statement uses the s type specifier in the conversion

specification. Figure C-5 shows the output.

$Payment = 1410;

$Payment = number_format($Payment, 2);

printf("<p>Pay the amount of $%s.</p>\n", $Payment);


APPENDIX C

With UNIX/

Linux

systems,

you can

use the

money_format() func-

tion to format a number

as currency. However,

the money_format()

function is not compatible

with Windows platforms.

646

Figure C-5

Using the

printf() and

number_format() functions together

Formatting Alignment

By default, strings are formatted with right alignment. However, if

you add a hyphen (-) immediately following the percent symbol in

a conversion specification, a string is formatted with left alignment.

For example, each of the printf() statements in the following code

contains two conversion specifications: one for the description of a

travel expense and one for the amount of a travel expense. The first

conversion specification for the travel expense descriptions contains

a hyphen (-) immediately following the percent symbol, which aligns

the descriptions to the left. However, the second conversion specifi-

cation for the amounts does not contain hyphens, so these descrip-

tions are right-aligned by default.

<p><strong>Expense Report</strong></p>

<pre>

<?php

$Travel = number_format(465.43, 2);

$Accommodations = number_format(276.2, 2);

$Meals = number_format(97.34, 2);

print("DescriptionAmount\n");

print("***********************************\n");

printf("%-15s %20s\n", "Travel", $Travel);

printf("%-15s %20s\n", "Accommodations",

$Accommodations);

printf("%-15s %20s\n", "Meals", $Meals);

?>

</pre>

In the preceding example, notice that the PHP script section is con-

tained within an XHTML <pre> element. This element is necessary

to instruct the Web browser to print the multiple spaces in the script.


APPENDIX C

Putting It All Together

Combining all of the elements described in the previous sec-

tions, the following code shows the general syntax for a conversion

specification:

% [+][pad][-][length][.decimal]type

647

In the preceding line of code, [+] is the optional plus sign. It indi-

cates that numeric fields should always display a plus or minus sign

before the value. Recall that the default setting is only to display the

sign if the value is negative. This option is only used for numeric type

values.

[pad] is the optional pad character to insert if the length of the argu-

ment value is less than the length specified in [length]. For zeroes or

spaces, the character ‘0’ or ‘ ’ is sufficient. All other characters must

be preceded by a single quotation mark ('). If [pad] is omitted, the

value is padded with spaces. This option is only used if [length] is

specified.

[-] is the optional hyphen that indicates the field should be left-

aligned. The default setting is right alignment. This option is only

used if [length] is specified and the length of the string is less than

the value of length.

[length] is the optional minimum number of characters to be used

when displaying the value. If a string is shorter than the number of

characters specified by length, pad characters will be added until the

string is the specified length. Pad characters are added to the begin-

ning of the string by default, but you can pad at the end of the string

by specifying [-]. Strings that are longer than the length value will

be displayed in full, not truncated.

[.decimal] is the optional number of digits to display after the deci-

mal point for numeric values. This number is included in the num-

ber of characters specified by [length]. You must put the decimal

point before the decimal value to indicate that you are specifying the

number of decimal places. For string values, [.decimal] specifies

the maximum string length. Any strings longer than decimal will be

truncated to be decimal characters long.

type is the required type specifier that indicates the data type of the

data argument. The valid type specifiers are shown in Table C-1 ear-

lier in this appendix.

APPENDIX

Secure Coding

with PHP

Understanding PHP Security Issues

Viruses, worms, data theft by hackers, and other security threats are

facts of life when it comes to Web-based applications. If you put an

application into a production environment without considering secu-

rity issues, you are asking for trouble. To combat security violations,

you need to consider both Web server security issues and secure cod-

ing issues. Web server security involves the use of technologies such

as firewalls, which employ both software and hardware to prevent

access to private networks connected to the Internet. One impor-

tant technology is the Secure Sockets Layer (SSL) protocol, which

encrypts data and transfers it across a secure connection. Although

Web server security is critical, the topic is better addressed in books

on Apache, Internet Information Services, and other types of Web

servers. Be sure to research security issues for your Web server and

operating system before activating a production Web site.

To provide even stronger software security, many technology com-

panies, including Microsoft and Oracle, require their developers and

other technical staff to adhere to secure coding practices and princi-

ples. Secure coding, or defensive coding, refers to writing code that

minimizes intentional or accidental security problems. Secure coding

has become a major goal for many information technology compa-

nies, due to the exorbitant cost of fixing security flaws in commercial

software. According to one study, it is 100 times more expensive to

D

APPENDIX D

fix security flaws in released software than to apply secure coding

techniques during the development phase. The National Institute

of Standards & Technology estimates that $60 billion a year is spent

identifying and correcting software errors. In addition, politicians

have become interested in regulating software security. Tom Ridge,

former Secretary of the U.S. Department of Homeland Security,

said, “A few lines of code can wreak more havoc than a bomb.”

Government scrutiny gives information technology companies strong

incentive to voluntarily improve the security of software products

before state and federal governments pass legislation that requires

such security.

Basically, all code is insecure unless proven otherwise. There is no

magic formula for writing secure code, although you can use vari-

ous techniques to minimize security threats in your programs. This

appendix reviews some of the secure coding techniques you have

already studied in this book.

Even if you follow the recommendations in this appendix, your code

may not be absolutely secure. This appendix does not list every secu-

rity issue with PHP, databases, and Web development. As a Web

programmer, you should continually familiarize yourself with new

threats as they appear and modify your code to avoid the threats

whenever possible.

For more

information on

PHP security,

visit the PHP

Security

Consortium (PHPSC) Web

site at http://phpsec.

org/. PHPSC is an inter-

national group of PHP

experts dedicated to

promoting secure pro-

gramming practices

within the PHP

community.

649

Using Secure Programming Techniques

This section includes a number of recommendations for making your

code more secure, including tips for securing Web forms, verifying

user identities, and securing data stored in files on the Web server.

Validating Submitted Form Data

In Chapter 4, you learned how to validate data that is submitted to

your scripts. Web developers often use JavaScript with forms to vali-

date or process form data before the data is submitted to a server-side

script. For example, customers may use an online order form to order

merchandise from your Web site. After customers click the form’s

Submit button, you can use JavaScript to ensure that customers have

entered important information, such as their name, shipping address,

and so on. The problem with using JavaScript to validate form data

is that you cannot always ensure that the data was submitted to your

PHP script from the Web page containing the JavaScript validation

code. Hackers know how to bypass JavaScript validation code in an

XHTML form by appending a query string directly to the URL of

the PHP script that processes the form. Therefore, you should always


APPENDIX D

650

include PHP code to validate any submitted data. If your PHP script

lacks such code, you cannot be sure that all of the necessary data was

submitted (such as a shipping address for an online order), nor can

you tell if a hacker is attempting to submit malicious data that might

harm your script or your Web site. Also recall that the POST method

sends form data as a transmission separate from the URL specified by

the action attribute. This is one reason to use POST rather than GET as

the method for submitting form data. However, you do not guarantee

the safety of your site by having users submit form data from a Web

page using the POST method. Anyone who thoroughly understands

HTTP headers can construct a separate transmission that contains

the form data required by your script.

To ensure that your script receives the proper data, use the isset()

and empty() functions to determine if form variables contain val-

ues. The isset() function determines whether a variable has been

declared and initialized (or “set”), whereas the empty() function

determines whether a variable is empty. You pass to both functions

the name of the variable you want to check. If a submitted form value

must be numeric data, you should use an is_numeric() function to

test the variable. This ensures that hackers cannot break your code by

sending alphabetic values to scripts that expect numeric values.

Avoiding the $_REQUEST[] Autoglobal Array

The $_REQUEST[] autoglobal array aggregates the elements of the

$_GET[], $_POST[], and $_COOKIE[] autoglobal arrays into a single

array. Many programmers use the $_REQUEST[] array for the conve-

nience of not having to determine whether a Web form was submit-

ted using the GET or POST method. However, because the $_COOKIE[]

array is added to the $_REQUEST[]array last, any $_COOKIE[] array

elements with the same associative array key as an element in the

$_GET[] or $_POST[] arrays will be overwritten with the values from

the $_COOKIES[] array. This provides hackers with a way to inject

potentially dangerous data into your system.

Using Sessions to Validate User Identities

Always use sessions to validate user identities, especially at commer-

cial sites that include shopping cart mechanisms. Because sessions

store state information on a Web server, they are much safer to use—

provided you properly secure your Web server. The randomly gener-

ated alphanumeric string that composes a session ID is extremely

difficult to guess, so hackers probably cannot use this value to imper-

sonate a user. If a hacker does obtain another user’s session ID, he can

use it to steal sensitive data, such as credit card information.

APPENDIX D

Even with sessions, however, there is a chance that a hacker can

obtain a user’s session ID. For a detailed discussion of session secu-

rity issues, refer to the PHP Security Consortium’s Security Guide at

http://phpsec.org/projects/guide/.

Storing Code in External Files

Chapter 10 discusses how to store classes in external files. However,

external files are not limited to classes; you can use them to store any

type of code. Storing code in external files helps to secure your scripts

by hiding the code from hackers. This also helps to protect your code

from other programmers who might steal your scripts and claim

them as their own.

In general, you should use the include() and include_once()

functions for XHTML code that will not prevent a script from

running if the external file is not available. For PHP code that is

required for your script to execute, you should use the require()

or require_once() functions, which halt the processing of the Web

page if the external file is not available.

You can also

use sessions

with Web

forms to

ensure that

the form data was sub-

mitted from your server

and not from a remote

site.

651

Choosing a Location for External Files

Your Web server has specific directories from which users are

allowed to retrieve files. The easiest way to ensure that a site visi-

tor cannot access a file is to store it outside those directories. As

discussed in Chapter 2, the include() family of functions can read

files stored outside of the Web structure. Files that contain secure

information or details about the underlying server should always be

stored outside the Web directory structure. This is also a good idea

for include files that do not contain sensitive information, because the

practice prevents a visitor from accessing the file directly.

For example, you could create a PHP_Includes directory at the same

level as your public_html or www directory. Within that directory,

you could include a PHP file named inc_db_info.php that assigns the

host name, user name, password, and database for a MySQL data-

base to variables named $db_host, $db_user, $db_password, and

$db_database. Then, you could add the following line of code to the

beginning of any PHP script that needs to access the database:

require_once("../PHP_Includes/inc_db_info.php"):

Because

Web site

visitors can-

not directly

access

externally placed files, it

is a good idea to store

many other types of files

outside the Web structure

as well, including log

files, data files, and

user-submitted files.

After including the inc_db_info.php file, you will need to modify your

code to use the predefined variables rather than strings. The following


APPENDIX D

code would be used to open a database connection using the mysql

package:

$DBConnect = @mysql_connect($db_host,

$db_user,

$db_password);

if ($DBConnect === FALSE)

echo "<p>Connection error: "

. mysql_error() . "</p>\n";

else {

if (@mysql_select_db($db_database, $DBConnect)

=== FALSE)

echo "<p>Could not select the \"" .

$db_database . "\" database: " .

mysql_error($DBConnect) .

"</p>\n";

...

}

652

The user

account

associated

with the Web

server

needs to have read per-

missions on the include

files for the include()

family of functions to

work.

The following code would be used to open a database connection

using the mysqli package:

$DBConnect = @new mysqli($db_host,

$db_user,

$db_password,

$db_database);

Because the file that contains the database information is not acces-

sible from a Web browser, the information is more secure than if it

was stored in the public_html or www folder, or if the information

was coded directly into each script that uses the MySQL database.

Choosing an External File Extension

You can use any file extension for include files, although many pro-

grammers use an extension of .inc for XHTML files and other types

of information that do not need to be processed by the Web server.

Although you can use the .inc extension for external files containing

PHP scripts, you should avoid doing so unless your Web server is

configured to process .inc files as PHP scripts. If it isn’t, anyone can

view the contents of the file simply by entering the full URL in a Web

browser. This creates a potential security risk, especially if the exter-

nal file contains proprietary code or sensitive information such as

passwords. Because most Web servers process the contents of a PHP

script and only return XHTML to the client, your safest bet is to use

an extension of .php for external files that contain PHP code.

Accessing Databases through a Proxy User

In Chapter 7, you learned that you should create an account that

requires a password for each user who needs to access your data-

base. For most Web sites, it’s impossible to predict how many visitors


APPENDIX D

might need to use a Web application to access a database. Therefore,

instead of creating a separate database account for each visitor, you

only need to create a single account that a PHP script uses to access

the database for a user by proxy. A proxy performs a request for

another person. In general, you should create a separate account for

each Web application that needs to access a database. You then use

PHP code, as in the following example, to access the database for the

user by proxy:

$DBConnect = @new mysqli("host", "proxy_user", "password");

if ($DBConnect->connect_errno())

echo "<p>Unable to connect to the database server.</p>"

. "<p>Error code " . $DBConnect->connect_errno()

. ": " . $DBConnect->connect_error() . "</p>";

else

...

653

Changing Settings in php.ini

Configuration settings for PHP are stored in the php.ini file on the

Web server. The default settings attempt to balance security require-

ments against convenience. To secure your Web site, check the fol-

lowing settings. If you are running your own Web server, you might

be able to edit the php.ini file directly. Otherwise, you might need to

contact the system administrator for your Web server and ask to have

the settings modified.

Handling Magic Quotes

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]