1. Trang chủ
  2. » Công Nghệ Thông Tin

Phát triển web với PHP và MySQL - p 43 docx

10 269 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 507,92 KB

Nội dung

you can pass in 0s to the hour, minute, and second parameters. You can, however, leave out values from the right side of the parameter list. If you leave the parameters blank, they will be set to the current values. Hence a call such as $timestamp = mktime(); will return the UNIX time stamp for the current date and time. You could, of course, also get this by calling $timestamp = date(“U”); You can pass in a 2- or 4-digit year to mktime(). Two-digit values from 0 to 69 will be inter- preted as the years 2000 to 2069, and values from 70 to 99 will be interpreted as 1970 to 1999. Using the getdate() Function Another date-determining function you might find useful is the getdate() function. This func- tion has the following prototype: array getdate (int timestamp) It takes a time stamp as parameter and returns an associative array representing the parts of that date and time as shown in Table 18.2. TABLE 18.2 Associative Array Key-Value Pairs from getdate() Function Key Value seconds Seconds, numeric minutes Minutes, numeric hours Hours, numeric mday Day of the month, numeric wday Day of the week, numeric mon Month, numeric year Year, numeric yday Day of the year, numeric weekday Day of the week, full text format month Month, full text format Managing the Date and Time C HAPTER 18 18 MANAGING THE DATE AND TIME 395 23 7842 CH18 3/6/01 3:43 PM Page 395 Validating Dates You can use the checkdate() function to check whether a date is valid. This is especially use- ful for checking user input dates. The checkdate() function has the following prototype: int checkdate (int month, int day, int year) It will check whether the year is a valid integer between 0 and 32767, whether the month is an integer between 1 and 12, and whether the day given exists in that particular month. The func- tion takes leap years into consideration. For example, checkdate(9, 18, 1972); will return true while checkdate(9, 31, 2000) will not. Converting Between PHP and MySQL Date Formats Dates and times in MySQL are retrieved in a slightly different way than you might expect. Times work relatively normally, but MySQL expects dates to be entered year first. For exam- ple, the 29 th of August 2000 could be entered as either 2000-08-29 or as 00-08-29. Dates retrieved from MySQL will also be in this order by default. To communicate between PHP and MySQL then, we usually need to perform some date con- version. This can be done at either end. When putting dates into MySQL from PHP, you can easily put them into the correct format using the date() function as shown previously. One minor caution is that you should use the versions of the day and month with leading zeroes to avoid confusing MySQL. If you choose to do the conversion in MySQL, two useful functions are DATE_FORMAT() and UNIX_TIMESTAMP(). The DATE_FORMAT() function works similarly to the PHP one but uses different format codes. The most common thing we want to do is format a date in MM-DD-YYYY format rather than in the YYYY-MM-DD format native to MySQL. You can do this by writing your query as fol- lows: SELECT DATE_FORMAT(date_column, ‘%m %d %Y’) FROM tablename; Part Title P ART IV 396 23 7842 CH18 3/6/01 3:43 PM Page 396 The format code %m represents the month as a 2-digit number; %d, the day as a 2-digit number; and %Y, the year as a 4-digit number. A summary of the more useful MySQL format codes for this purpose is shown in Table 18.3. TABLE 18.3 Format Codes for MySQL’s DATE_FORMAT() Function Code Description %M Month, full text %W Weekday name, full text %D Day of month, numeric, with text suffix (for example, 1st) %Y Year, numeric, 4-digits %y Year, numeric, 2-digits %a Weekday name, 3-characters %d Day of month, numeric, leading zeroes %e Day of month, numeric, no leading zeroes %m Month, numeric, leading zeroes %c Month, numeric, no leading zeroes %b Month, text, 3-characters %j Day of year, numeric %H Hour, 24-hour clock, leading zeroes %k Hour, 24-hour clock, no leading zeroes %h or %I Hour, 12-hour clock, leading zeroes %l Hour, 12-hour clock, no leading zeroes %i Minutes, numeric, leading zeroes %r Time, 12-hour (hh:mm:ss [AM|PM]) %T Time, 24-hour (hh:mm:ss) %S or %s Seconds, numeric, leading zeroes %p AM or PM %w Day of the week, numeric, from 0 (Sunday) to 6 (Saturday) The UNIX_TIMESTAMP function works similarly, but converts a column into a UNIX time stamp. For example, SELECT UNIX_TIMESTAMP(date_column) FROM tablename; Managing the Date and Time C HAPTER 18 18 MANAGING THE DATE AND TIME 397 23 7842 CH18 3/6/01 3:43 PM Page 397 will return the date formatted as a UNIX time stamp. You can then do as you will with it in PHP. As a rule of thumb, use a UNIX timestamp for date calculations and the standard date format when you are just storing or showing dates. It is simpler to do date calculations and compar- isons with the UNIX timestamp. Date Calculations The simplest way to work out the length of time between two dates in PHP is to use the differ- ence between UNIX time stamps. We have used this approach in the script shown in Listing 18.1. LISTING 18.1 calc_age.php—Script Works Out a Person’s Age Based on His Birthdate <? // set date for calculation $day = 18; $month = 9; $year = 1972; // remember you need bday as day month and year $bdayunix = mktime (“”, “”, “”, $month, $day, $year); // get unix ts for bday $nowunix = time(); // get unix ts for today $ageunix = $nowunix - $bdayunix; // work out the difference $age = floor($ageunix / (365 * 24 * 60 * 60)); // convert from seconds to //years echo “Age is $age”; ?> In this script, we have set the date for calculating the age. In a real application it is likely that this information might come from an HTML form. We begin by calling mktime() to work out the time stamp for the birthday and for the current time: $bdayunix = mktime (“”, “”, “”, $month, $day, $year); $nowunix = mktime(); // get unix ts for today Now that these dates are in the same format, we can simply subtract them: $ageunix = $nowunix - $bdayunix; Part Title P ART IV 398 23 7842 CH18 3/6/01 3:43 PM Page 398 Now, the slightly tricky part—to convert this time period back to a more human-friendly unit of measure. This is not a time stamp but instead the age of the person measured in seconds. We can convert it back to years by dividing by the number of seconds in a year. We then round it down using the floor() function as a person is not said to be, for example 20, until the end of his twentieth year: $age = floor($ageunix / (365 * 24 * 60 * 60)); // convert from seconds to years Note, however, that this approach is somewhat flawed as it is limited by the range of UNIX time stamps (generally 32-bit integers). Using the Calendar Functions PHP has a set of functions that enables you to convert between different calendar systems. The main calendars you will work with are the Gregorian, Julian, and the Julian Day Count. The Gregorian calendar is the one most Western countries currently use. The Gregorian date October 15, 1582 is equivalent to October 5, 1582, in the Julian calendar. Prior to that date, the Julian calendar was commonly used. Different countries converted to the Gregorian calendar at different times, and some not until early in the 20th century. Although you might have heard of these two calendars, you might not have heard of the Julian Day Count. This is similar in many ways to a UNIX time stamp. It is a count of the number of days since a date around 4000 BC. In itself, it is not particularly useful, but it is useful for con- verting between formats. To convert from one format to another, you first convert to a Julian Day Count (JD) and then to the desired output calendar. To use these functions, you will need to have compiled the calendar extension into PHP. To give you a taste for these functions, consider the prototypes for the functions you would use to convert from the Gregorian calendar to the Julian calendar: int gregoriantojd (int month, int day, int year) string jdtojulian(int julianday) To convert a date, we would need to call both these functions: $jd = gregoriantojd (9, 18, 1582); echo jdtojulian($jd); This echoes the Julian date in a mm/dd/yyyy format. Variations of these functions exist for converting between the Gregorian, Julian, French, and Jewish calendars and UNIX time stamps. Managing the Date and Time C HAPTER 18 18 MANAGING THE DATE AND TIME 399 23 7842 CH18 3/6/01 3:43 PM Page 399 Further Reading If you’d like to read more about date and time functions in PHP and MySQL, you can consult the relevant sections of the manuals at http://php.net/manual/ref.datetime.php http://www.mysql.com/documentation/mysql/commented/ manual.php?section=Date_and_time_functions If you are converting between calendars, try the manual page for PHP’s calendar functions: http://php.net/manual/ref.calendar.php Or try consulting this reference: http://genealogy.org/~scottlee/cal-overview.html Next One of the unique and useful things you can do with PHP is create images on-the-fly. Chapter 19, “Generating Images,” discusses how to use the image library functions to achieve some interesting and useful effects. Part Title P ART IV 400 23 7842 CH18 3/6/01 3:43 PM Page 400 CHAPTER 19 Generating Images 24 7842 CH19 3/6/01 3:42 PM Page 401 Advanced PHP Techniques P ART IV 402 One of the useful things you can do with PHP is create images on-the-fly. PHP has some built- in image information functions, and you can also use the GD library to create new images or manipulate existing ones. This chapter discusses how to use the image functions to achieve some interesting and useful effects. We will look at • Setting up image support in PHP • Understanding image formats • Creating images • Using text and fonts to create images • Drawing figures and graphing data Specifically, we’ll look at two examples: generating Web site buttons on-the-fly, and drawing a bar chart using figures from a MySQL database. Setting Up Image Support in PHP Image support in PHP is available via the gd library, available from http://www.boutell.com/gd/ Version 1.6.2 comes bundled with PHP 4. By default, the PNG format is supported. If you also want to work with JPEGs, you will need to download jpeg-6b, and recompile gd with jpeg sup- port included. You can download this from ftp://ftp.uu.net/graphics/jpeg/ You will then need to reconfigure PHP with the with-jpeg-dir=/path/to/jpeg-6b option, and recompile it. If you want to use TrueType fonts in your images, you will also need the FreeType library. This also comes with PHP 4. Alternatively, you can download this from http://www.freetype.org/ If you want to use PostScript Type 1 fonts instead, you will need to download t1lib, available from ftp://ftp.neuroinformatik.ruhr-uni-bochum.de/pub/software/t1lib/ You will then need to run PHP’s configure program with with-t1lib[=path/to/t1lib] 24 7842 CH19 3/6/01 3:42 PM Page 402 Image Formats The GD library supports JPEG, PNG, and WBMP formats. It no longer supports the GIF for- mat. Let’s briefly look at each of these formats. JPEG JPEG (pronounced “jay-peg”) actually stands for Joint Photographic Experts Group and is the name of a standards body. The file format we mean when we refer to JPEGs is actually called JFIF, which corresponds to one of the standards issued by JPEG. In case you are not familiar with them, JPEGs are usually used to store photographic or other images with many colors or gradations of color. This format uses lossy compression, that is, in order to squeeze a photograph into a smaller file, some image quality is lost. Because JPEGs should contain what are essentially analog images, with gradations of color, the human eye can tolerate some loss of quality. This format is not suitable for line drawings, text, or solid blocks of color. You can read more about JPEG/JFIF at the official JPEG site: http://www.jpeg.org/public/jpeghomepage.htm PNG PNG (pronounced “ping”) stands for Portable Network Graphics. This file format is seen as being the replacement for GIF (Graphics Interchange Format) for reasons we’ll discuss in a minute. The PNG Web site describes it as “a turbo-studly image format with lossless compres- sion”. Because it is lossless, this image format is suitable for images that contain text, straight lines, and simple blocks of color such as headings and Web site buttons—all the same pur- poses for which you previously might have used GIFs. It offers better compression than GIF as well as variable transparency, gamma correction, and two-dimensional interlacing. It does not, however, support animations—for this you must use the extension format MNG, which is still in development. You can read more about PNG at the official PNG site: http://www.freesoftware.com/pub/png/ WBMP WBMP stands for Wireless Bitmap. It is a file format designed specifically for wireless devices. Although gd supports this format, there are no PHP functions at present that take advantage of this functionality. Generating Images C HAPTER 19 19 G ENERATING IMAGES 403 24 7842 CH19 3/6/01 3:42 PM Page 403 GIF GIF stands for Graphics Interchange Format. It is a compressed lossless format widely used on the Web for storing images containing text, straight lines, and blocks of single color. The question you are likely asking is, why doesn’t gd support GIFs? The answer is that it used to, up to version 1.3. If you want to install and use the GIF functions instead of the PNG functions, you can download gd version 1.3 from http://www.linuxguruz.org/downloads/gd1.3.tar.gz Note, however, that the makers of gd discourage you from using this version and no longer support it. This copy of the GIF version might not be available forever. There is a good reason that gd no longer supports GIFs. Standard GIFs use a form of compres- sion known as LZW (Lempel Ziv Welch), which is subject to a patent owned by UNISYS. Providers of programs that read and write GIFs must pay licensing fees to UNISYS. For exam- ple, Adobe has paid a licensing fee for products such as Photoshop that are used to create GIFs. Code libraries appear to be in the situation in which the writers of the code library must pay a fee, and, in addition, the users of the library must also pay a fee. Thus, if you use a GIF version of the GD library on your Web site, you might owe UNISYS some fairly hefty licens- ing fees. This situation is unfortunate because GIFs were in use for many years before UNISYS chose to enforce licensing. Thus, the format became one of the standards for the Web. A lot of ill feeling exists about the patent in the Web development community. You can read about this (and form your own opinion) at UNISYS’s site http://www.unisys.com/unisys/lzw/ and at Burn All Gifs, their opposition, http://burnallgifs.org/ We are not lawyers, and none of this should be interpreted as legal advice, but we think it is easier to use PNGs, regardless of the politics. Browser support for PNGs is improving; however, the LZW patent expires on June 19, 2003, so the final outcome is yet to be seen. Creating Images The four basic steps to creating an image in PHP are as follows: 1. Creating a canvas image on which to work 2. Drawing shapes or printing text on that canvas Advanced PHP Techniques P ART IV 404 24 7842 CH19 3/6/01 3:42 PM Page 404 . with jpeg sup- port included. You can download this from ftp://ftp.uu.net/graphics/jpeg/ You will then need to reconfigure PHP with the with-jpeg-dir=/path/to/jpeg-6b option, and recompile it. If. 3 :43 PM Page 400 CHAPTER 19 Generating Images 24 7842 CH19 3/6/01 3:42 PM Page 401 Advanced PHP Techniques P ART IV 402 One of the useful things you can do with PHP is create images on-the-fly two examples: generating Web site buttons on-the-fly, and drawing a bar chart using figures from a MySQL database. Setting Up Image Support in PHP Image support in PHP is available via the gd

Ngày đăng: 06/07/2014, 19:20

TỪ KHÓA LIÊN QUAN