1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML> <HEAD>
<!-- $Id -->
<TITLE>CGI.pm - a Perl5 CGI Library</TITLE>
</HEAD>
<BODY bgcolor="#FFFFFF">
<H1><IMG SRC="examples/dna.small.gif" ALT="[logo]">
CGI.pm - a Perl5 CGI Library</H1>
<p>
<h1>AS OF 10 FEBRUARY 2005 (CGI.pm VERSION 3.06) THIS DOCUMENT IS NO
LONGER BEING MAINTAINED. PLEASE CONSULT THE CGI POD DOCUMENTATION
USING "perldoc CGI"</h1>
<H2>Abstract</H2> This perl 5 library uses objects to create Web
fill-out forms on the fly and to parse their contents. It provides a
simple interface for parsing and interpreting query strings passed to
CGI scripts. However, it also offers a rich set of functions for
creating fill-out forms. Instead of remembering the syntax for HTML
form elements, you just make a series of perl function calls. An
important fringe benefit of this is that the value of the previous
query is used to initialize the form, so that the state of the form is
preserved from invocation to invocation.
<P>Everything is done through a ``CGI'' object. When you create one
of these objects it examines the environment for a query string,
parses it, and stores the results. You can then ask the CGI object to
return or modify the query values. CGI objects handle POST and GET
methods correctly, and correctly distinguish between scripts called
from <ISINDEX> documents and form-based documents. In fact you
can debug your script from the command line without worrying about
setting up environment variables.
<P>A script to create a fill-out form that remembers its state each
time it's invoked is very easy to write with CGI.pm:
<PRE>
#!/usr/local/bin/perl
use CGI qw(:standard);
print header;
print start_html('A Simple Example'),
h1('A Simple Example'),
start_form,
"What's your name? ",textfield('name'),
p,
"What's the combination?",
p,
checkbox_group(-name=>'words',
-values=>['eenie','meenie','minie','moe'],
-defaults=>['eenie','minie']),
p,
"What's your favorite color? ",
popup_menu(-name=>'color',
-values=>['red','green','blue','chartreuse']),
p,
submit,
end_form,
hr;
if (param()) {
print
"Your name is",em(param('name')),
p,
"The keywords are: ",em(join(", ",param('words'))),
p,
"Your favorite color is ",em(param('color')),
hr;
}
print end_html;
</PRE>
<A HREF="examples/tryit.cgi">Select this link to try the script</A>
<BR>
<A HREF="examples/">More scripting examples</A>
<BR>
<a href="http://www.wiley.com/compbooks/stein/source.html">Source code
examples from <cite>The Official Guide to CGI.pm</cite></a>
<p>
<H2><A NAME="contents">Contents</A></H2>
<MENU>
<LI><A HREF="#download">Downloading</A>
<LI><A HREF="#installation">Installation</A>
<LI><a href="#functionvsoo">Function-Oriented vs Object-Oriented Use</a>
<LI><A HREF="#query">Creating a new CGI query object</A>
<LI><A HREF="#saving">Saving the state of the form</A>
<LI><A HREF="#named_param">CGI Functions that Take Multiple Arguments</A>
<LI><A HREF="#header">Creating the HTTP header</A>
<LI><A HREF="#html">HTML shortcuts</A>
<LI><A HREF="#forms">Creating forms</A>
<LI><A HREF="#import">Importing CGI methods</A>
<LI><A HREF="#errors">Retrieving CGI.pm errors</A>
<LI><A HREF="#debugging">Debugging</A>
<LI><A HREF="#environment">HTTP session variables</A>
<LI><A HREF="#cookies">HTTP Cookies</A>
<li><a href="#frames">Support for frames</a>
<li><a href="#javascripting">Support for JavaScript</a>
<li><a href="#stylesheets">Limited Support for Cascading Style Sheets</a>
<LI><A HREF="#nph">Using NPH Scripts</A>
<LI><A HREF="#advanced">Advanced techniques</A>
<LI><A HREF="#subclassing">Subclassing CGI.pm</A>
<LI><A HREF="#mod_perl">Using CGI.pm with mod_perl and FastCGI</A>
<LI><A HREF="#migrating">Migrating from cgi-lib.pl</A>
<LI><a href="#upload_caveats">Using the File Upload Feature</a>
<LI><a href="#push">Server Push</a>
<LI><A HREF="#dos">Avoiding Denial of Service Attacks</A>
<LI><A HREF="#non_unix">Using CGI.pm on non-Unix Platforms</A>
<LI><A HREF="#future">The Relationship of CGI.pm to the CGI::* Modules</A>
<LI><A HREF="#distribution">Distribution information</A>
<LI><A HREF="#book">The CGI.pm Book</A>
<LI><A HREF="#y2000">CGI.pm and the Year 2000 Problem</A>
<LI><A HREF="#bugs">Bug Reporting and Support</A>
<LI><A HREF="#new">What's new?</A>
</MENU>
<HR>
<h2><a name="download">Downloads</a></h2>
<ul>
<li><STRONG><A HREF="CGI.pm.tar.gz">Download gzip tar archive (Unix)</A></STRONG>
<li><STRONG><A HREF="CGI.pm.zip">Download pkzip archive (Windows)</A></STRONG>
<li><STRONG><A HREF="CGI.pm.sit">Download sit archive (Macintosh)</A></STRONG>
<li><strong><A HREF="CGI.pm">Download just the CGI module (uncompressed)</a></strong>
<li><strong><a href="old">Archive of Old Versions</a></strong>
</ul>
<p>
<H2><A NAME="installation">Installation</A></H2>
<ul>
<li><STRONG><A HREF="CGI.pm.tar.gz">Download gzip tar archive (Unix)</A></STRONG>
<li><STRONG><A HREF="CGI.pm.zip">Download pkzip archive (Windows)</A></STRONG>
<li><STRONG><A HREF="CGI.pm.sit">Download sit archive (Macintosh)</A></STRONG>
<li><strong><A HREF="CGI.pm">Download just the CGI module (uncompressed)</a></strong>
</ul>
<p>
The current version of the software can always be downloaded from the
master copy of this document maintained at <a
href="http://stein.cshl.org/WWW/software/CGI/">http://stein.cshl.org/WWW/software/CGI/</a>.
<P>
This package requires perl 5.004 or higher. Earlier versions of Perl
may work, but CGI.pm has not been tested with them. If you're really
stuck, edit the source code to remove the line that says "require
5.004", but don't be surprised if you run into problems.
<p>
If you are using a Unix system, you should have perl do the
installation for you. Move to the directory containing CGI.pm and
type the following commands:
<PRE>
% perl Makefile.PL
% make
% make install
</PRE>
You may need to be root to do the last step.
<p>
This will create two new files in your Perl library. <b>CGI.pm</b> is the
main library file. <b>Carp.pm</b> (in the subdirectory "CGI") contains
some optional utility
routines for writing nicely formatted error messages into your
server logs. See the Carp.pm man page for more details.
<p>
<strong>If you get error messages when you try to install</strong>,
then you are either:
<ol>
<li> Running a Windows NT or Macintosh port of Perl that
doesn't have make or the MakeMaker program built into it.
<li> Have an old version of Perl. Upgrade to 5.004 or higher.
</ol>
In the former case don't panic. Here's a recipe that will work
(commands are given in MS-DOS/Windows form):
<pre>
> cd CGI.pm-2.73
> copy CGI.pm C:\Perl\lib
> mkdir C:\Perl\lib\CGI
> copy CGI\*.pm C:\Perl\lib\CGI
</pre>
Modify this recipe if your Perl library has a different location.
<p>
For Macintosh users, just drag the file named CGI.pm into the folder
where your other Perl .pm files are stored. Also drag the subfolder
named "CGI".
<p>
<STRONG>If you do not have sufficient privileges to install into
/usr/local/lib/perl5</STRONG>, you can still use CGI.pm. Modify the
installation recipe as follows:
<PRE>
% perl Makefile.PL INSTALLDIRS=site INSTALLSITELIB=/home/your/private/dir
% make
% make install
</PRE>
Replace <cite>/home/your/private/dir</cite> with the full path to the
directory you want the library placed in. Now preface your CGI
scripts with a preamble something like the following:
<blockquote><pre>
use lib '/home/your/private/dir';
use CGI;
</pre></blockquote>
Be sure to replace /home/your/private/dir with the true location of
CGI.pm.
<P>
<A HREF="#non_unix">Notes on using CGI.pm in NT and other non-Unix platforms</A>
<hr>
<h2><a name="functionvsoo">Function-Oriented vs Object-Oriented Use</a></h2>
CGI.pm can be used in two distinct modes called
<cite>function-oriented</cite> and <cite>object-oriented</cite>. In
the function-oriented mode, you first import CGI functions into your
script's namespace, then call these functions directly. A simple
function-oriented script looks like this:
<blockquote><pre>
#!/usr/local/bin/perl
use CGI qw/:standard/;
print header(),
start_html(-title=>'Wow!'),
h1('Wow!'),
'Look Ma, no hands!',
end_html();
</pre></blockquote>
The <cite>use</cite> operator loads the CGI.pm definitions and imports
the ":standard" set of function definitions. We then make calls to
various functions such as <cite>header()</cite>, to generate the HTTP
header, <cite>start_html()</cite>, to produce the top part of an HTML
document, <cite>h1()</cite> to produce a level one header, and so
forth.
<p>
In addition to the standard set, there are many optional sets of less
frequently used CGI functions. See <a href="#import">Importing CGI
Methods</a> for full details.
<p>
In the object-oriented mode, you <cite>use CGI;</cite> without
specifying any functions or function sets to import. In this case,
you communicate with CGI.pm via a CGI object. The object is created
by a call to <cite>CGI::new()</cite> and encapsulates all the state
information about the current CGI transaction, such as values of the
CGI parameters passed to your script. Although more verbose, this
coding style has the advantage of allowing you to create multiple CGI
objects, save their state to disk or to a database, and otherwise
manipulate them to achieve neat effects.
<p>
The same script written using the object-oriented style looks like
this:
<blockquote><pre>
#!/usr/local/bin/perl
use CGI;
$q = new CGI;
print $q->header(),
$q->start_html(-title=>'Wow!'),
$q->h1('Wow!'),
'Look Ma, no hands!',
$q->end_html();
</pre></blockquote>
The object-oriented mode also has the advantage of consuming somewhat
less memory than the function-oriented coding style. This may be of
value to users of persistent Perl interpreters such as <a
href="http://perl.apache.org">mod_perl</a>.
<p>
Many of the code examples below show the object-oriented coding
style. Mentally translate them into the function-oriented style if
you prefer.
<H2><A NAME="query">Creating a new CGI object</A></H2>
The most basic use of CGI.pm is to get at the query parameters
submitted to your script. To create a new CGI object that
contains the parameters passed to your script, put the following
at the top of your perl CGI programs:
<PRE>
use CGI;
$query = new CGI;
</PRE>
In the object-oriented world of Perl 5, this code calls the new()
method of the CGI class and stores a new CGI object into the variable
named $query. The new() method does all the dirty work of parsing
the script parameters and environment variables and stores its results
in the new object. You'll now make method calls with this object to
get at the parameters, generate form elements, and do other useful things.
<P>
An alternative form of the new() method allows you to read
script parameters from a previously-opened file handle:
<PRE>
$query = new CGI(FILEHANDLE)
</PRE>
The filehandle can contain a URL-encoded query string, or can be a
series of newline delimited TAG=VALUE pairs. This is compatible with
the save() method. This lets you save the state of a CGI script to a
file and reload it later. It's also possible to save the contents of
several query objects to the same file, either within a single script
or over a period of time. You can then reload the multiple records
into an array of query objects with something like this:
<blockquote><pre>
open (IN,"test.in") || die;
while (!eof(IN)) {
my $q = new CGI(IN);
push(@queries,$q);
}
</pre></blockquote>
You can make simple databases this way, or create a guestbook. If
you're a Perl purist, you can pass a reference to the filehandle glob
instead of the filehandle name. This is the "official" way to pass
filehandles in Perl5:
<blockquote><pre>
my $q = new CGI(\*IN);
</pre></blockquote>
(If you don't know what I'm talking about, then you're not a Perl
purist and you needn't worry about it.)
<p>
If you are using the function-oriented interface and want to
initialize CGI state from a file handle, the way to do this is with
<cite>restore_parameters()</cite>. This will (re)initialize the
default CGI object from the indicated file handle.
<blockquote><pre>
open (IN,"test.in") || die;
restore_parameters(IN);
close IN;
</pre></blockquote>
<p>
You can initialize a CGI object from an associative-array reference.
Values can be either single- or multivalued:
<blockquote><pre>
$query = new CGI({'dinosaur'=>'barney',
'song'=>'I love you',
'friends'=>[qw/Jessica George Nancy/]});
</pre></blockquote>
You can initialize a CGI object by passing a URL-style query string to
the new() method like this:
<blockquote><pre>
$query = new CGI('dinosaur=barney&color=purple');
</pre></blockquote>
Or you can clone a CGI object from an existing one. The parameter
lists of the clone will be identical, but other fields, such as
autoescaping, are not:
<blockquote><pre>
$old_query = new CGI;
$new_query = new CGI($old_query);
</pre></blockquote>
<p>
This form also allows you to create a CGI object that is initially empty:
<blockquote><pre>
$empty_query = new CGI('');
</pre></blockquote>
<p>
If you are using mod_perl, you can initialize a CGI object at any
stage of the request by passing the request object to CGI->new:
<blockquote><pre>
$q = CGI->new($r);
</pre></blockquote>
<p>
To do this with the function-oriented interface, set
Apache->request($r) before calling the first CGI function.
<p>
Finally, you can pass code reference to new() in order to install an
upload_hook function that will be called regularly while a long file
is being uploaded. See <a href="#upload">Creating a File Upload Field</a>
for details.
<p>
See <A HREF="#advanced">advanced techniques</A> for more information.
<H3><A NAME="keywords">Fetching A List Of Keywords From The Query</A></H3>
<PRE>
@keywords = $query->keywords
</PRE>
If the script was invoked as the result of an <ISINDEX> search, the
parsed keywords can be obtained with the keywords() method. This method
will return the keywords as a perl array.
<H3><A NAME="parameters">Fetching The Names Of All The Parameters Passed To Your
Script</A></H3>
<PRE>
@names = $query->param </PRE> If the script was invoked with a
parameter list
(e.g. "name1=value1&name2=value2&name3=value3"), the param()
method will return the parameter names as a list. For backwards
compatibility if the script was invoked as an <ISINDEX> script
and contains a string without ampersands (e.g. "value1+value2+value3")
, there will be a single parameter named "keywords" containing the
"+"-delimited keywords.
<H3><A NAME="values">Fetching The Value(s) Of A Named Parameter</A></H3>
<PRE>
@values = $query->param('foo');
-or-
$value = $query->param('foo');
</PRE>
Pass the param() method a single argument to fetch the value of the
named parameter. If the parameter is multivalued (e.g. from multiple
selections in a scrolling list), you can ask to receive an array. Otherwise
the method will return a single value.
<P>
If a value is not given in the query string, as in the queries
"name1=&name2=" or "name1&name2", it will be returned as an
empty string (not undef). This feature is new in 2.63, and was
introduced to avoid multiple "undefined value" warnings when running
with the -w switch.
<p>
If the parameter does not exist at all, then param() will return undef
in a scalar context, and the empty list in a list context.
<H3><A NAME="setting">Setting The Value(s) Of A Named Parameter</A></H3>
<PRE>
$query->param('foo','an','array','of','values');
-or-
$query->param(-name=>'foo',-values=>['an','array','of','values']);
</PRE>
This sets the value for the named parameter 'foo' to one or more
values. These values will be used to initialize form elements, if
you so desire. Note that this is the one way to forcibly change the value
of a form field after it has previously been set.
<p>
The second example shows an alternative "named parameter" style of function
call that is accepted by most of the CGI methods. See <a href="#named_param">
Calling CGI functions that Take Multiple Arguments</a> for an explanation of
this style.
<H3><A NAME="append">Appending a Parameter</A></H3>
<PRE>
$query->append(-name=>'foo',-values=>['yet','more','values']);
</PRE>
This adds a value or list of values to the named parameter. The
values are appended to the end of the parameter if it already exists.
Otherwise the parameter is created.
<H3><A NAME="deleting">Deleting a Named Parameter Entirely</A></H3>
<PRE>
$query->delete('foo');
</PRE>
This deletes a named parameter entirely. This is useful when you
want to reset the value of the parameter so that it isn't passed
down between invocations of the script.
<H3><A NAME="deleting_all">Deleting all Parameters</A></H3>
<PRE>
$query->delete_all();
</PRE>
This deletes all the parameters and leaves you with an empty CGI
object. This may be useful to restore all the defaults produced by
the form element generating methods.
<H3><A NAME="postdata">Handling non-URLencoded Arguments</A></H3>
<p>
If POSTed data is not of type application/x-www-form-urlencoded or
multipart/form-data, then the POSTed data will not be processed, but
instead be returned as-is in a parameter named POSTDATA. To retrieve
it, use code like this:
<PRE>
my $data = $query->param('POSTDATA');
</PRE>
(If you don't know what the preceding means, don't worry about it. It
only affects people trying to use CGI for XML processing and other
specialized tasks.)
<H3><A NAME="importing">Importing parameters into a namespace</A></H3>
<PRE>
$query->import_names('R');
print "Your name is $R::name\n"
print "Your favorite colors are @R::colors\n";
</PRE>
This imports all parameters into the given name space. For example,
if there were parameters named 'foo1', 'foo2' and 'foo3', after
executing <CODE>$query->import_names('R')</CODE>, the variables
<CODE>@R::foo1, $R::foo1, @R::foo2, $R::foo2,</CODE> etc. would
conveniently spring into existence. Since CGI has no way of
knowing whether you expect a multi- or single-valued parameter,
it creates two variables for each parameter. One is an array,
and contains all the values, and the other is a scalar containing
the first member of the array. Use whichever one is appropriate.
For keyword (a+b+c+d) lists, the variable @R::keywords will be
created.
<P>
If you don't specify a name space, this method assumes namespace "Q".
<p>
An optional second argument to <b>import_names</b>, if present and
non-zero, will delete the contents of the namespace before loading
it. This may be useful for environments like mod_perl in which the
script does not exit after processing a request.
<P><STRONG>Warning</STRONG>: do not import into namespace 'main'. This
represents a major security risk, as evil people could then use this
feature to redefine central variables such as @INC.
CGI.pm will exit with an error if you try to do this.
<p><strong>NOTE:</strong>
Variable names are transformed as necessary into legal Perl
variable names. All non-legal characters are transformed into
underscores. If you need to keep the original names, you should use
the param() method instead to access CGI variables by name.
</p>
<P>
<H3><A NAME="param_fetch">Direct Access to the Parameter List</A></H3>
<blockquote><pre>
$q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
unshift @{$q->param_fetch(-name=>'address')},'George Munster';
</pre></blockquote>
If you need access to the parameter list in a way that isn't covered
by the methods above, you can obtain a direct reference to it by
calling the <b>param_fetch()</b> method with the name of the parameter
you want. This will return an array reference to the named
parameters, which you then can manipulate in any way you like.
<p>
You may call <b>param_fetch()</b> with the name of the CGI parameter,
or with the <b>-name</b> argument, which has the same meaning as
elsewhere.
<h3>Fetching the Parameter List as a Hash</h3>
<blockquote>
<pre>
$params = $q->Vars;
print $params->{'address'};
@foo = split("\0",$params->{'foo'});
%params = $q->Vars;
use CGI ':cgi-lib';
$params = Vars;
</pre>
</blockquote>
<p>
Many people want to fetch the entire parameter list as a hash in which
the keys are the names of the CGI parameters, and the values are the
parameters' values. The <B>Vars()</B> method does this. Called in a
scalar context, it returns the parameter list as a tied hash
reference. Changing a key changes the value of the parameter in the
underlying CGI parameter list. Called in an list context, it returns
the parameter list as an ordinary hash. This allows you to read the
contents of the parameter list, but not to change it.
<p>
When using this, the thing you must watch out for are multivalued CGI
parameters. Because a hash cannot distinguish between scalar and
list context, multivalued parameters will be returned as a packed
string, separated by the "\0" (null) character. You must split this
packed string in order to get at the individual values. This is the
convention introduced long ago by Steve Brenner in his cgi-lib.pl
module for Perl version 4.
<p>
If you wish to use <B>Vars()</B> as a function, import the
<I>:cgi-lib</I> set of function calls (also see the section on <a
href="#migrating">CGI-LIB compatibility</a>).
<h3><A NAME="errors">RETRIEVING CGI ERRORS</A></h3>
<p> Errors can occur while processing user input, particularly when
processing uploaded files. When these errors occur, CGI will stop
processing and return an empty parameter list. You can test for the
existence and nature of errors using the <strong>cgi_error()</strong>
function. The error messages are formatted as HTTP status codes. You
can either incorporate the error text into an HTML page, or use it as
the value of the HTTP status:
<pre>
my $error = $q->cgi_error;
if ($error) {
print $q->header(-status=>$error),
$q->start_html('Problems'),
$q->h2('Request not processed'),
$q->strong($error);
exit 0;
}
</pre>
<p>
When using the function-oriented interface (see the next section),
errors may only occur the first time you call
<strong>param()</strong>. Be prepared for this!
<A HREF="#contents">Table of contents</A>
<HR>
<H2><A NAME="saving">Saving the Current State of a Form</A></H2>
<H3>Saving the State to a File</H3>
<PRE>
$query->save(\*FILEHANDLE)
</PRE>
This writes the current query out to the file handle of your choice.
The file handle must already be open and be writable, but other than
that it can point to a file, a socket, a pipe, or whatever. The contents
of the form are written out as TAG=VALUE pairs, which can be reloaded
with the new() method at some later time. You can write out multiple
queries to the same file and later read them into query objects one by one.
<p>
If you wish to use this method from the function-oriented (non-OO)
interface, the exported name for this method is
<cite>save_parameters()</cite>.
See <A HREF="#advanced"> advanced techniques</A> for more information.
<H3><A NAME="self_referencing">
Saving the State in a Self-Referencing URL</A></H3>
<PRE>
$my_url=$query->self_url
</PRE>
This call returns a URL that, when selected, reinvokes this script with
all its state information intact. This is most useful when you want to
jump around within a script-generated document using internal anchors, but
don't want to disrupt the current contents of the form(s). See <A HREF="#advanced">
advanced techniques</A> for an example.
<P>
If you'd like to get the URL without the entire query string appended to
it, use the <code>url()</code> method:
<PRE>
$my_self=$query->url
</PRE>
<h3>Obtaining the Script's URL</h3>
<PRE>
$full_url = $query->url();
$full_url = $query->url(-full=>1); #alternative syntax
$relative_url = $query->url(-relative=>1);
$absolute_url = $query->url(-absolute=>1);
$url_with_path = $query->url(-path_info=>1);
$url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
</PRE>
<code>url()</code> returns the script's URL in a variety of formats.
Called without any arguments, it returns the full form of the URL,
including host name and port number
<pre>
http://your.host.com/path/to/script.cgi
</pre>
You can modify this format with the following named arguments:
<dl>
<dt><strong>-absolute</strong>
<dd>If true, produce an absolute URL, e.g.
<pre>
/path/to/script.cgi
</pre>
<p>
<dt><strong>-relative</strong>
<dd>Produce a relative URL. This is useful if you want to reinvoke your
script with different parameters. For example:
<pre>
script.cgi
</pre>
<p>
<dt><strong>-full</strong>
<dd>Produce the full URL, exactly as if called without any arguments.
This overrides the -relative and -absolute arguments.
<p>
<dt><strong>-path</strong>,<strong>-path_info</strong>
<dd>Append the additional path information to the URL. This can be
combined with -full, -absolute or -relative. -path_info
is provided as a synonym.
<p>
<dt><strong>-query</strong> (<strong>-query_string</strong>)
<dd>Append the query string to the URL. This can be combined with
-full, -absolute or -relative. -query_string is provided
as a synonym.
</dl>
<H3>Mixing POST and URL Parameters</H3>
<pre>
$color = $query->url_param('color');
</pre>
It is possible for a script to receive CGI parameters in the URL as
well as in the fill-out form by creating a form that POSTs to a URL
containing a query string (a "?" mark followed by arguments). The
<b>param()</b> method will always return the contents of the POSTed
fill-out form, ignoring the URL's query string. To retrieve URL
parameters, call the <b>url_param()</b> method. Use it in the same
way as <b>param()</b>. The main difference is that it allows you to
read the parameters, but not set them.
<p>
Under no circumstances will the contents of the URL query string
interfere with similarly-named CGI parameters in POSTed forms. If you
try to mix a URL query string with a form submitted with the GET
method, the results will not be what you expect.
<p>
<A HREF="#contents">Table of contents</A>
<HR>
<H3><A NAME="named_param">
Calling CGI Functions that Take Multiple Arguments</A>
</H3>
In versions of CGI.pm prior to 2.0, it could get difficult to remember
the proper order of arguments in CGI function calls that accepted five
or six different arguments. As of 2.0, there's a better way to pass
arguments to the various CGI functions. In this style, you pass a
series of name=>argument pairs, like this:
<PRE>
$field = $query->radio_group(-name=>'OS',
-values=>[Unix,Windows,Macintosh],
-default=>'Unix');
</PRE>
The advantages of this style are that you don't have to remember the
exact order of the arguments, and if you leave out a parameter, it
will usually default to some reasonable value. If you provide
a parameter that the method doesn't recognize, it will usually do
something useful with it, such as incorporating it into the HTML
tag as an attribute. For example if Netscape decides next week to add a new
JUSTIFICATION parameter to the text field tags, you can start using
the feature without waiting for a new version of CGI.pm:
<PRE>
$field = $query->textfield(-name=>'State',
-default=>'gaseous',
-justification=>'RIGHT');
</PRE>
This will result in an HTML tag that looks like this:
<PRE>
<INPUT TYPE="textfield" NAME="State" VALUE="gaseous"
JUSTIFICATION="RIGHT">
</PRE>
Parameter names are case insensitive: you can use -name, or -Name or
-NAME.
Actually, CGI.pm only looks for a hyphen in the first parameter. So
you can leave it off subsequent parameters if you like. Something to
be wary of is the potential that a string constant like "values" will
collide with a keyword (and in fact it does!) While Perl usually
figures out when you're referring to a function and when you're
referring to a string, you probably should put quotation marks around
all string constants just to play it safe.
<P>
HTML/HTTP parameters that contain internal hyphens, such as <i>-Content-language</i>
can be passed by putting quotes around them, or by using an underscore
for the second hyphen, e.g. <cite>-Content_language</cite>.
<p>
The fact that you must use curly {} braces around the attributes
passed to functions that create simple HTML tags but don't use them
around the arguments passed to all other functions has many people,
including myself, confused. As of 2.37b7, the syntax is extended to
allow you to use curly braces for all function calls:
<PRE>
$field = $query->radio_group({-name=>'OS',
-values=>[Unix,Windows,Macintosh],
-default=>'Unix'});
</PRE>
<A HREF="#contents">Table of contents</A>
<HR>
<H2><A NAME="header">
Creating the HTTP Header</A>
</H2>
<H3><A NAME="standard_header">
Creating the Standard Header for a Virtual Document</A>
</H3>
<PRE>
print $query->header('image/gif');
</PRE>
This prints out the required HTTP Content-type: header and the requisite
blank line beneath it. If no parameter is specified, it will default to
'text/html'.
<P>
An extended form of this method allows you to specify a status code
and a message to pass back to the browser:
<PRE>
print $query->header(-type=>'image/gif',
-status=>'204 No Response');
</PRE>
This presents the browser with a status code of 204 (No response).
Properly-behaved browsers will take no action, simply remaining on the
current page. (This is appropriate for a script that does some
processing but doesn't need to display any results, or for a script
called when a user clicks on an empty part of a clickable image map.)
<P>
Several other named parameters are recognized. Here's a
contrived example that uses them all:
<PRE>
print $query->header(-type=>'image/gif',
-status=>'402 Payment Required',
-expires=>'+3d',
-cookie=>$my_cookie,
-charset=>'UTF-7',
-attachment=>'foo.gif',
-Cost=>'$0.02');
</PRE>
<h4>-expires</h4>
Some browsers, such as Internet Explorer, cache the output of CGI
scripts. Others, such as Netscape Navigator do not. This leads to
annoying and inconsistent behavior when going from one browser to
another. You can force the behavior to be consistent by using the
<strong>-expires</strong> parameter. When you specify an absolute or
relative expiration interval with this parameter, browsers and
proxy servers will cache the script's output until the indicated
expiration date. The following forms are all valid for the
<strong>-expires</strong> field: <pre>
+30s 30 seconds from now
+10m ten minutes from now
+1h one hour from now
-1d yesterday (i.e. "ASAP!")
now immediately
+3M in three months
+10y in ten years time
Thu, 25-Apr-1999 00:40:33 GMT at the indicated time & date
</pre>
When you use <strong>-expires</strong>, the script also generates a
correct time stamp for the generated document to ensure that your
clock and the browser's clock agree. This allows you to create
documents that are reliably cached for short periods of time.
<p>
<strong>CGI::expires()</strong> is the static function call used internally that turns
relative time intervals into HTTP dates. You can call it directly if
you wish.
<h4>-cookie</h4>
The <strong>-cookie</strong> parameter generates a header that tells
Netscape browsers to return a "magic cookie" during all subsequent
transactions with your script. HTTP cookies have a special format
that includes interesting attributes such as expiration time. Use the
<a href="#cookies">cookie()</a> method to create and retrieve session
cookies. The value of this parameter can be either a scalar value or
an array reference. You can use the latter to generate multiple
cookies. (You can use the alias <strong>-cookies</strong> for
readability.)
<h4>-nph</h4>
The <strong>-nph</strong> parameter, if set to a non-zero value, will
generate a valid header for use in no-parsed-header scripts. For
example:
<blockquote><pre>
print $query->header(-nph=>1,
-status=>'200 OK',
-type=>'text/html');
</pre></blockquote>
You will need to use this if:
<ol>
<li>You are using Microsoft Internet Information Server.
<li>If you need to create unbuffered output, for example for use
in a "server push" script.
<li>To take advantage of HTTP extensions not supported by your server.
</ol>
See <a href="#nph">Using NPH Scripts</a> for more information.
<h4>-charset</h4>
The <b>-charset</b> parameter can be used to control the character set
sent to the browser. If not provided, defaults to ISO-8859-1. As a
side effect, this calls the charset() method to set the behavior for
escapeHTML().
<h4>-attachment</h4>
The <b>-attachment</b> parameter can be used to turn the page into an
attachment. Instead of displaying the page, some browsers will prompt
the user to save it to disk. The value of the argument is the
suggested name for the saved file. In order for this to work, you may
have to set the <b>-type</b> to "application/octet-stream".
<h4>-p3p</h4>
The <b>-p3p</b> parameter will add a P3P tag to the outgoing header. The
parameter can be an arrayref or a space-delimited string of P3P tags.
For example:
<blockquote><pre>
print header(-p3p=>[qw(CAO DSP LAW CURa)]);
print header(-p3p=>'CAO DSP LAW CURa');
</pre></blockquote>
In either case, the outgoing header will be formatted as:
<blockquote><pre>
P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
</pre></blockquote>
<h4>Other header fields</h4>
Any other parameters that you pass to <strong>header()</strong> will be turned
into correctly formatted HTTP header fields, even if they aren't called for
in the current HTTP spec. For example, the example that appears a few paragraphs
above creates a field that looks like this:
<pre>
Cost: $0.02
</pre>
You can use this to take advantage of new HTTP header fields without
waiting for the next release of CGI.pm.
<H3><A NAME="redirect">Creating the Header for a Redirection Request</A></H3>
<PRE>
print $query->redirect('http://somewhere.else/in/the/world');
</PRE>
This generates a redirection request for the remote browser. It will
immediately go to the indicated URL. You should exit soon after this.
Nothing else will be displayed.
<P>
You can add your own headers to this as in the header() method.
<P>
You should always use full URLs (including the http: or ftp: part) in
redirection requests. Relative URLs will <b>not</b> work correctly.
<p>
An alternative syntax for <code>redirect()</code> is:
<blockquote><pre>
print $query->redirect(-location=>'http://somewhere.else/',
-nph=>1,
-status=>301);
</pre></blockquote>
The <strong>-location</strong> parameter gives the destination URL.
You may also use <strong>-uri</strong> or <strong>-url</strong> if you
prefer.
<p>
The <strong>-nph</strong> parameter, if non-zero tells CGI.pm that
this script is running as a no-parsed-header script. See <a
href="#nph">Using NPH Scripts</a> for more information.
<p>
The <strong>-status</strong> parameter will set the status of the
redirect. HTTP defines three different possible redirection status
codes:
<pre>
301 Moved Permanently
302 Found
303 See Other
</pre>
<p>
The default if not specified is 302, which means "moved temporarily."
You may change the status to another status code if you wish. Be
advised that changing the status to anything other than 301, 302 or
303 will probably break redirection.
<p>
The <strong>-method</strong> parameter tells the browser what method
to use for redirection. This is handy if, for example, your script
was called from a fill-out form POST operation, but you want to
redirect the browser to a static page that requires a GET.
<p>
All other parameters recognized by the <tt>header()</tt> method are
also valid in <tt>redirect</tt>.
<A HREF="#contents">Table of contents</A>
<HR>
<H2><A NAME="html">HTML Shortcuts</A></H2>
<H3>Creating an HTML Header</H3>
<PRE>
<EM>named parameter style</EM>
print $query->start_html(-title=>'Secrets of the Pyramids',
-author=>'fred@capricorn.org',
-base=>'true',
-meta=>{'keywords'=>'pharoah secret mummy',
'copyright'=>'copyright 1996 King Tut'},
-style=>{'src'=>'/styles/style1.css'},
-dtd=>1,
-BGCOLOR=>'blue');
<EM>old style</EM>
print $query->start_html('Secrets of the Pyramids',
'fred@capricorn.org','true');
</PRE>
This will return a canned HTML header and the opening <BODY> tag.
All parameters are optional:
<UL>
<LI>The title (<strong>-title</strong>)
<LI>The author's e-mail address (will create a <LINK REV="MADE"> tag if present
(<strong>-author</strong>)
<LI>A true flag if you want to include a <BASE> tag in the header
(<strong>-base</strong>). This
helps resolve relative addresses to absolute ones when the document is moved,
but makes the document hierarchy non-portable. Use with care!
<LI>A <strong>-xbase</strong> parameter, if you want to include a <BASE> tag that points
to some external location. Example:
<pre>
print $query->start_html(-title=>'Secrets of the Pyramids',
-xbase=>'http://www.nile.eg/pyramid.html');
</pre>
<LI>A <strong>-target</strong> parameter, if you want to have all links and fill
out forms on the page go to a different frame. Example:
<pre>
print $query->start_html(-title=>'Secrets of the Pyramids',
-target=>'answer_frame');
</pre>
<strong>-target</strong> can be used with either
<strong>-xbase</strong> or <strong>-base</strong>.
<LI>A <strong>-meta</strong> parameter to define one or more <META> tags. Pass
this parameter a reference to an associative array containing key/value pairs. Each
pair becomes a <META> tag in a format similar to this one.
<blockquote><pre>
<META NAME="keywords" CONTENT="pharoah secret mummy">
<META NAME="description" CONTENT="copyright 1996 King Tut">
</pre></blockquote>
To create an HTTP-EQUIV tag, use the <B>-head</B> argument as described below.
<li>The <b>-encoding</b> argument can be used to specify the character set for
XHTML. It defaults to iso-8859-1 if not specified.
<li>The <b>-declare_xml</b> argument, when used in conjunction with XHTML,
will put a <?xml> declaration at the top of the HTML header. The sole
purpose of this declaration is to declare the character set
encoding. In the absence of -declare_xml, the output HTML will contain
a <meta> tag that specifies the encoding, allowing the HTML to pass
most validators. The default for -declare_xml is false.
<li>A <strong>-lang</strong>> argument is used to incorporate a language attribute into
the <HTM>> tag. The default if not specified is "en-US" for US English. For example:
<blockquote><pre>
print $q->start_html(-lang=>'fr-CA');
</pre></blockquote>
To leave off the lang attribute, as you must do if you want to generate
legal HTML 3.2 or earlier, pass the empty string (-lang=>'').
<LI>A <strong>-dtd</strong> parameter to make start_html()
generate an SGML document type definition for the document.
This is used by SGML editors and high-end Web publishing systems
to determine the type of the document. However, it breaks some
browsers, in particular AOL's. The value of this parameter can
be one of:
<ol>
<li>A valid DTD (see <a
href="http://ugweb.cs.ualberta.ca/%7egerald/validate/lib/catalog">http://ugweb.cs.ualberta.ca/%7egerald/validate/lib/catalog</a> for a list). Example: <pre>-dtd=>'-//W3C//DTD HTML 3.2//EN'</pre>
<li>A true value that does not begin with "-//", in which case
you will get the standard default DTD (valid for HTML 2.0).
</ol>
You can change the default DTD by calling
<strong>default_dtd()</strong> with the preferred value.
<li>A <strong>-style</strong> parameter to define a cascading stylesheet.
More information on this can be found in <a
href="#stylesheets">Limited Support for Cascading Style Sheets</a>
<li>A <strong>-head</strong> parameter to define other arbitrary elements
of the <HEAD> section. For example:
<pre>
print start_html(-head=>Link({-rel=>'next',
-href=>'http://www.capricorn.com/s2.html'}));
</pre>
or even
<pre>
print start_html(-head=>[ Link({-rel=>'next',
-href=>'http://www.capricorn.com/s2.html'}),
Link({-rel=>'previous',
-href=>'http://www.capricorn.com/s1.html'})
]
);
</pre>
To create an HTTP-EQUIV tag, use something like this:
<pre>
print start_html(-head=>meta({-http_equiv=>'Content-Type',
-content=>'text/html'}))
</pre>
<LI>A <strong>-script</strong> parameter to define Netscape <a
href="#javascripting">JavaScript</a> functions
to incorporate into the HTML page. This is the preferred way to
define a library of JavaScript functions that will be called
from elsewhere within the page. CGI.pm will attempt to format
the JavaScript code in such a way that non-Netscape browsers won't
try to display the JavaScript
code. Unfortunately some browsers get confused nevertheless.
Here's an example of how to create a JavaScript library and
incorporating it into the HTML code header:
<pre>
$query = new CGI;
print $query->header;
$JSCRIPT=<<END;
// Ask a silly question
function riddle_me_this() {
var r = prompt("What walks on four legs in the morning, " +
"two legs in the afternoon, " +
"and three legs in the evening?");
response(r);
}
// Get a silly answer
function response(answer) {
if (answer == "man")
alert("Right you are!");
else
alert("Wrong! Guess again.");
}
END
print $query->start_html(-title=>'The Riddle of the Sphinx',
-script=>$JSCRIPT);
</pre>
Netscape 3.0 and higher allows you to place the JavaScript code
in an external
document and refer to it by URL. This allows you to keep the JavaScript
code in a file or CGI script rather than cluttering up each page with the
source. Netscape 3.X-4.X and Internet Explorer 3.X-4.X also recognize a "language"
parameter that allows you to use other languages, such as VBScript and
PerlScript (yes indeed!) To use these attributes pass a HASH
reference in the <strong>-script</strong> parameter containing one
or more of the keys <strong>language</strong>, <strong>src</strong>, or
<strong>code</strong>. Here's how to refer to an external script URL:
<pre>
print $q->start_html(-title=>'The Riddle of the Sphinx',
-script=>{-language=>'JavaScript',
-src=>'/javascript/sphinx.js'}
);
</pre>
Here's how to refer to scripting code incorporated directly into the page:
<pre>
print $q->start_html(-title=>'The Riddle of the Sphinx',
-script=>{-language=>'PerlScript',
-code=>'print "hello world!\n;"'}
);
</pre>
A final feature allows you to incorporate multiple <SCRIPT> sections into the
header. Just pass the list of script sections as an array reference.
This allows you to specify different source files for different dialects
of JavaScript. Example:
<pre>
print $q->start_html(-title=>'The Riddle of the Sphinx',
-script=>[
{ -language => 'JavaScript1.0',
-src => '/javascript/utilities10.js'
},
{ -language => 'JavaScript1.1',
-src => '/javascript/utilities11.js'
},
{ -language => 'JavaScript1.2',
-src => '/javascript/utilities12.js'
},
{ -language => 'JavaScript28.2',
-src => '/javascript/utilities219.js'
}
]
);
</pre>
(If this looks a bit extreme, take my advice and stick with straight CGI scripting.)
<p>
<LI>A <strong>-noScript</strong> parameter to pass some HTML that will be displayed
in browsers that do not have JavaScript (or have JavaScript turned off).
<LI><strong>-onLoad</strong> and <strong>-onUnload</strong> parameters to
register JavaScript event handlers to be executed when the
page generated by your script is opened and closed respectively.
Example:
<pre>
print $query->start_html(-title=>'The Riddle of the Sphinx',
-script=>$JSCRIPT,
-onLoad=>'riddle_me_this()');
</pre>
See <a href="#javascripting">JavaScripting</a> for more details.
<LI>Any additional attributes you want to incorporate into the <BODY>
tag (as many as you like). This is a good way to incorporate other
Netscape extensions, such as background color and wallpaper pattern.
(The example above sets the page background to a vibrant blue.) You can
use this feature to take advantage of new HTML features without
waiting for a CGI.pm release.
</UL>
<H3>Ending an HTML Document</H3>
<PRE>
print $query->end_html
</PRE>
This ends an HTML document by printing the </BODY> </HTML> tags.
<H3>Other HTML Tags</H3>
CGI.pm provides shortcut methods for many other HTML tags. All HTML2
tags and the Netscape extensions are supported, as well as the HTML3
and HTML4 tags. Unpaired tags, paired tags, and tags that contain
attributes are all supported using a simple syntax.
<p>
To see the list of HTML tags that are supported, open up the CGI.pm
file and look at the functions defined in the %EXPORT_TAGS array.
<h4>Unpaired Tags</h4>
Unpaired tags include <P>, <HR> and <BR>. The
syntax for creating them is:
<pre>
print $query->hr;
</pre>
This prints out the text "<hr>".
<h4>Paired Tags</h4>
Paired tags include <EM>, <I> and the like. The syntax
for creating them is:
<pre>
print $query->em("What a silly art exhibit!");
</pre>
This prints out the text "<em>What a silly art
exhibit!</em>".
<p>
You can pass as many text arguments as you like: they'll be
concatenated together with spaces. This allows you to create nested
tags easily:
<pre>
print $query->h3("The",$query->em("silly"),"art exhibit");
</pre>
This creates the text:
<pre>
<h3>The <em>silly</em> art exhibit</h3>
</pre>
<p>
When used in conjunction with the <a href="#import">import</a>
facility, the HTML shortcuts can make CGI scripts easier to read. For
example:
<pre>
use CGI qw/:standard/;
print h1("Road Guide"),
ol(
li(a({href=>"start.html"},"The beginning")),
li(a({href=>"middle.html"},"The middle")),
li(a({href=>"end.html"},"The end"))
);
</pre>
<p>
Most HTML tags are represented as lowercase function calls. There are
a few exceptions:
<ol>
<li>The <tr> tag used to start a new table row conflicts with the
perl <cite>translate</cite> function <code>tr()</code>. Use
TR() or Tr() instead.
<li>The <param> tag used to pass parameters to an applet
conflicts with CGI's own <code>param() </code> method. Use
PARAM() instead.
<li>The <select> tag used to create selection lists conflicts
with Perl's select() function. Use <code>Select()</code> instead.
<li>The <sub> tag used to create subscripts conflicts
wit Perl's operator for creating subroutines. Use
<code>Sub()</code> instead.
</ol>
<h4>Tags with Attributes</h4>
To add attributes to an HTML tag, simply pass a reference to an
associative array as the first argument. The keys and values of the
associative array become the names and values of the attributes. For
example, here's how to generate an <A> anchor link:
<pre>
use CGI qw/:standard/;
print a({-href=>"bad_art.html"},"Jump to the silly exhibit");
<i><A HREF="bad_art.html">Jump to the silly exhibit</A></i>
</pre>
You may dispense with the dashes in front of the attribute names if
you prefer:
<pre>
print img {src=>'fred.gif',align=>'LEFT'};
<i><IMG ALIGN="LEFT" SRC="fred.gif"></i>
</pre>
Sometimes an HTML tag attribute has no argument. For example, ordered
lists can be marked as COMPACT, or you wish to specify that a table
has a border with <TABLE BORDER>. The syntax for this is an
argument that that points to an undef string:
<pre>
print ol({compact=>undef},li('one'),li('two'),li('three'));
</pre>
Prior to CGI.pm version 2.41, providing an empty ('') string as an
attribute argument was the same as providing undef. However, this has
changed in order to accomodate those who want to create tags of the form
<IMG ALT="">. The difference is shown in this table:
<table border="1">
<tr><th>CODE</th> <th>RESULT</th></tr>
<tr><td><tt>img({alt=>undef})</tt></td> <td><IMG ALT></td></tr>
<tr><td><tt>img({alt=>''})</tt></td> <td><IMT ALT=""></td></tr>
</table>
<h4>Distributive HTML Tags and Tables</h4>
All HTML tags are distributive. If you give them an argument
consisting of a <b>reference</b> to a list, the tag will be
distributed across each element of the list. For example, here's one
way to make an ordered list:
<blockquote><pre>
print ul(
li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy']);
);
</pre></blockquote>
This example will result in HTML output that looks like this:
<blockquote><pre>
<UL>
<LI TYPE="disc">Sneezy</LI>
<LI TYPE="disc">Doc</LI>
<LI TYPE="disc">Sleepy</LI>
<LI TYPE="disc">Happy</LI>
</UL>
</pre></blockquote>
You can take advantage of this to create HTML tables easily and
naturally. Here is some code and the HTML it outputs:
<blockquote><pre>
use CGI qw/:standard :html3/;
print table({-border=>undef},
caption(strong('When Should You Eat Your Vegetables?')),
Tr({-align=>CENTER,-valign=>TOP},
[
th(['','Breakfast','Lunch','Dinner']),
th('Tomatoes').td(['no','yes','yes']),
th('Broccoli').td(['no','no','yes']),
th('Onions').td(['yes','yes','yes'])
]
)
);
</pre></blockquote>
<TABLE border="1"><CAPTION><STRONG>When Should You Eat Your Vegetables?</STRONG></CAPTION>
<TR ALIGN="CENTER" VALIGN="TOP"><TH></TH> <TH>Breakfast</TH> <TH>Lunch</TH> <TH>Dinner</TH></TR>
<TR ALIGN="CENTER" VALIGN="TOP"><TH>Tomatoes</TH><TD>no</TD> <TD>yes</TD> <TD>yes</TD></TR>
<TR ALIGN="CENTER" VALIGN="TOP"><TH>Broccoli</TH><TD>no</TD> <TD>no</TD> <TD>yes</TD></TR>
<TR ALIGN="CENTER" VALIGN="TOP"><TH>Onions</TH><TD>yes</TD> <TD>yes</TD> <TD>yes</TD></TR>
</TABLE>
<P>
If you want to produce tables programatically, you can do it this way:
<blockquote><pre>
use CGI qw/:standard :html3/;
@values = (1..5);
@headings = ('N','N'.sup('2'),'N'.sup('3'));
@rows = th(\@headings);
foreach $n (@values) {
push(@rows,td([$n,$n**2,$n**3]));
}
print table({-border=>undef,-width=>'25%'},
caption(b('Wow. I can multiply!')),
Tr(\@rows)
);
</pre></blockquote>
<TABLE BORDER="1" WIDTH="25%"><CAPTION><B>Wow. I can multiply!</B></CAPTION>
<TR><TH>N</TH> <TH>N<SUP>2</SUP></TH> <TH>N<SUP>3</SUP></TH></TR>
<TR><TD>1</TD> <TD>1</TD> <TD>1</TD></TR>
<TR><TD>2</TD> <TD>4</TD> <TD>8</TD></TR>
<TR><TD>3</TD> <TD>9</TD> <TD>27</TD></TR>
<TR><TD>4</TD> <TD>16</TD> <TD>64</TD></TR>
<TR><TD>5</TD> <TD>25</TD> <TD>125</TD></TR>
</TABLE>
<A HREF="#contents">Table of contents</A>
<HR>
<H2><A NAME="forms">Creating Forms</A></H2>
<EM>General note 1.</EM>
The various form-creating methods all return
strings to the caller. These strings will contain the HTML code
that will create the requested form element. You are responsible for
actually printing out these strings. It's set up this way so that you
can place formatting tags around the form elements.
<P>
<A NAME="overriding">
<EM>General note 2.</EM>
</A>
The default values that you specify for the
forms are only used the <STRONG>first</STRONG> time the script is invoked. If there
are already values present in the query string, they are used, even if
blank.
<P>If you want to change the value of a field from its previous
value, you have two choices:
<OL>
<LI> call the <STRONG>param()</STRONG> method to set it.
<LI> use the <B>-override</B> (alias <B>-force</B>) parameter. (This is a
new feature in 2.15) This forces the default value to be used,
regardless of the previous value of the field:
<PRE>
print $query->textfield(-name=>'favorite_color',
-default=>'red',
-override=>1);
</PRE>
</OL>
If you want to reset all fields to their defaults, you can:
<OL>
<LI>Create a special <VAR>defaults</VAR> button using the <STRONG>defaults()</STRONG> method.
<LI>Create a hypertext link that calls your script without any parameters.
</OL>
<EM>General note 3.</EM> You can put multiple forms on the same page if you
wish. However, be warned that it isn't always easy to preserve state information
for more than one form at a time. See <A HREF="#advanced">advanced techniques</A>
for some hints.
<P>
<EM>General note 4.</EM> By popular demand, the text and labels that you
provide for form elements are escaped according to HTML rules. This means
that you can safely use "<CLICK ME>" as the label for a button. However,
this behavior may interfere with your ability to incorporate special HTML
character sequences, such as &Aacute; (Á) into your fields. If
you wish to turn off automatic escaping, call the <CODE>autoEscape()</CODE>
method with a false value immediately after creating the CGI object:
<PRE>
$query = new CGI;
$query->autoEscape(0);
</PRE>
You can turn autoescaping back on at any time with <CODE>$query->autoEscape(1)</CODE>
<p>
<EM>General note 5.</EM> Some of the form-element generating methods
return multiple tags. In a scalar context, the tags will be
concatenated together with spaces, or whatever is the current value of
the $" global. In a list context, the methods will return a list of
elements, allowing you to modify them if you wish. Usually you will
not notice this behavior, but beware of this:
<pre>
printf("%s\n",$query->end_form())
</pre>
end_form() produces several tags, and only the first of them will be
printed because the format only expects one value.
<p>
<H3>Form Elements</H3>
<MENU>
<LI><A HREF="#startform">Opening a form</A>
<LI><A HREF="#textfield">Text entry fields</A>
<LI><A HREF="#textarea">Big text entry fields</A>
<LI><A HREF="#password">Password fields</A>
<LI><A HREF="#upload">File upload fields</A>
<LI><A HREF="#menu">Popup menus</A>
<LI><A HREF="#scrolling_list">Scrolling lists</A>
<LI><A HREF="#checkbox_group">Checkbox groups</A>
<LI><A HREF="#checkbox">Individual checkboxes</A>
<LI><A HREF="#radio">Radio button groups</A>
<LI><A HREF="#submit">Submission buttons</A>
<LI><A HREF="#reset">Reset buttons</A>
<LI><A HREF="#defaults">Reset to defaults button</A>
<LI><A HREF="#hidden">Hidden fields</A>
<LI><A HREF="#image">Clickable Images</A>
<LI><A HREF="#button">JavaScript Buttons</A>
<LI><A HREF="#escape">Autoescaping HTML</A>
</MENU>
<A HREF="#contents">Up to table of contents</A>
<H3><A NAME="isindex">Creating An Isindex Tag</A></H3>
<PRE>
print $query->isindex($action);
</PRE>
<STRONG>isindex()</STRONG> without any arguments returns an
<ISINDEX> tag that designates your script as the URL to call.
If you want the browser to call a different URL to handle the search,
pass isindex() the URL you want to be called.
<H3><A NAME="startform">Starting And Ending A Form</A></H3>
<PRE>
print $query->startform($method,$action,$encoding);
<VAR>...various form stuff...</VAR>
print $query->endform;
</PRE>
<STRONG>startform()</STRONG> will return a <FORM> tag with the
optional method, action and form encoding that you specify.
<STRONG>endform()</STRONG> returns a </FORM> tag.
<P> The form encoding supports the "file upload" feature of Netscape
2.0 (and higher) and Internet Explorer 4.0 (and higher). The form
encoding tells the browser how to package up the contents of the form
in order to transmit it across the Internet. There are two types of
encoding that you can specify:
<DL>
<DT> <STRONG>application/x-www-form-urlencoded</STRONG>
<DD> This is the type of encoding used by all browsers prior to
Netscape 2.0. It is compatible with many CGI scripts and is
suitable for short fields containing text data. For your
convenience, CGI.pm stores the name of this encoding
type in <CODE>$CGI::URL_ENCODED</CODE>.
<DT> <STRONG>multipart/form-data</STRONG>
<DD> This is the newer type of encoding introduced by Netscape 2.0.
It is suitable for forms that contain very large fields or that
are intended for transferring binary data. Most importantly,
it enables the "file upload" feature of Netscape 2.0 forms. For
your convenience, CGI.pm stores the name of this encoding type
in <CODE>CGI::MULTIPART()</CODE>
<P>
Forms that use this type of encoding are not easily interpreted
by CGI scripts unless they use CGI.pm or another library that
knows how to handle them. Unless you are using the file upload
feature, there's no particular reason to use this type of encoding.
</DL>
For compatability, the startform() method uses the older form of
encoding by default. If you want to use the newer form of encoding
By default, you can call <A HREF="#multipart">start_multipart_form()</A>
instead of <CODE>startform()</CODE>.
<p>
If you plan to make use of the <a href="#javascripting">JavaScript
features</a>, you can provide <code>startform()</code> with the
optional <code>-name</code> and/or <code>-onSubmit</code> parameters.
<code>-name</code> has no effect on the display of the form, but can
be used to give the form an identifier so that it can be manipulated
by JavaScript functions. Provide the <code>-onSubmit</code> parameter
in order to register some JavaScript code to be performed just before
the form is submitted. This is useful for checking the validity of a
form before submitting it. Your JavaScript code should return a value
of "true" to let Netscape know that it can go ahead and submit the
form, and "false" to abort the submission.
<H3><A NAME="multipart">Starting a Form that Uses the "File Upload" Feature</A></H3>
<PRE>
print $query->start_multipart_form($method,$action,$encoding);
<VAR>...various form stuff...</VAR>
print $query->endform;
</PRE>
This has exactly the same usage as <CODE>startform()</CODE>, but
it specifies form encoding type <CODE>multipart/form-data</CODE>
as the default.
<H3><A NAME="textfield">Creating A Text Field</A></H3>
<PRE>
<EM>Named parameter style</EM>
print $query->textfield(-name=>'field_name',
-default=>'starting value',
-size=>50,
-maxlength=>80);
<EM>Old style</EM>
print $query->textfield('foo','starting value',50,80);
</PRE>
<STRONG>textfield()</STRONG> will return a text input field.
<UL>
<LI>The first parameter (<strong>-name</strong>) is the required name for the field.
<LI>The optional second parameter (<strong>-default</strong>) is the starting value
for the field contents.
<LI>The optional third parameter (<strong>-size</strong>) is the size of the field in
characters.
<LI>The optional fourth parameter (<strong>-maxlength</strong>) is the
maximum number of characters the field will accomodate.
</UL>
As with all these methods, the field will be initialized with its
previous contents from earlier invocations of the script. If you
want to force in the new value, overriding the existing one, see
<A HREF="#overriding">General note 2</A>.
<P>
When the form is processed, the value of the text field can be
retrieved with:
<PRE>
$value = $query->param('foo');
</PRE>
<p>
<strong>JavaScripting:</strong> You can also provide
<strong>-onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut</strong> and
<strong>-onSelect</strong> parameters to register <a href="#javascripting">
JavaScript</a> event handlers.
<H3><A NAME="textarea">Creating A Big Text Field</A></H3>
<PRE>
<EM>Named parameter style</EM>
print $query->textarea(-name=>'foo',
-default=>'starting value',
-rows=>10,
-columns=>50);
<EM>Old style</EM>
print $query->textarea('foo','starting value',10,50);
</PRE>
<STRONG>textarea()</STRONG> is just like textfield(), but it allows you to specify
rows and columns for a multiline text entry box. You can provide
a starting value for the field, which can be long and contain
multiple lines.
<p>
<strong>JavaScripting:</strong> Like textfield(), you can provide
<strong>-onChange, -onFocus, -onBlur, -onMouseOver,
-onMouseOut</strong> and <strong>-onSelect</strong> parameters to
register <a href="#javascripting"> JavaScript</a> event handlers.
<H3><A NAME="password">Creating A Password Field</A></H3>
<PRE>
<EM>Named parameter style</EM>
print $query->password_field(-name=>'secret',
-value=>'starting value',
-size=>50,
-maxlength=>80);
<EM>Old style</EM>
print $query->password_field('secret','starting value',50,80);
</PRE>
<STRONG>password_field()</STRONG> is identical to textfield(), except that its contents
will be starred out on the web page.
<H3><A NAME="upload">Creating a File Upload Field</A></H3>
<PRE>
<EM>Named parameters style</EM>
print $query->filefield(-name=>'uploaded_file',
-default=>'starting value',
-size=>50,
-maxlength=>80);
<EM>Old style</EM>
print $query->filefield('uploaded_file','starting value',50,80);
</PRE>
<STRONG>filefield()</STRONG> will return a form field that prompts the user
to upload a file.
<UL>
<LI>The first parameter (<strong>-name</strong>) is the required name for the field.
<LI>The optional second parameter (<strong>-default</strong>) is the starting value
for the file name.
This field is currently ignored by all browsers, but there's
always hope!
<LI>The optional third parameter (<strong>-size</strong>) is the size of the field in
characters.
<LI>The optional fourth parameter (<strong>-maxlength</strong>) is the
maximum number of characters the field will accomodate.
</UL>
filefield() will return a file upload field for use with recent
browsers. The browser will prompt the remote user to select a file to
transmit over the Internet to the server. Other browsers currently
ignore this field.
<P>
In order to take full advantage of the file upload
facility you must use the new <A HREF="#multipart">multipart
form encoding scheme</A>. You can do this either
by calling <A HREF="#startform">startform()</A>
and specify an encoding type of <CODE>$CGI::MULTIPART</CODE>
or by using the new <A HREF="#multipart">start_multipart_form()</A>
method. If you don't use multipart encoding, then you'll be
able to retrieve the name of the file selected by the remote
user, but you won't be able to access its contents.
<P>
When the form is processed, you can retrieve the entered filename
by calling param().
<PRE>
$filename = $query->param('uploaded_file');
</PRE>
where "uploaded_file" is whatever you named the file upload field.
Depending on the browser version, the filename that gets returned may
be the full local file path on the <STRONG>remote user's</STRONG>
machine, or just the bare filename. If a path is provided, the
follows the path conventions of the local machine.
<P>
The filename returned is also a file handle. You can read the contents
of the file using standard Perl file reading calls:
<PRE>
# Read a text file and print it out
while (<$filename>) {
print;
}
# Copy a binary file to somewhere safe
open (OUTFILE,">>/usr/local/web/users/feedback");
while ($bytesread=read($filename,$buffer,1024)) {
print OUTFILE $buffer;
}
close $filename;
</PRE>
<p>
There are problems with the dual nature of the upload fields. If you
<code>use strict</code>, then Perl will complain when you try to use a
string as a filehandle. You can get around this by placing the file
reading code in a block containing the <code>no strict</code> pragma.
More seriously, it is possible for the remote user to type garbage
into the upload field, in which case what you get from <b>param()</b>
is not a filehandle at all, but a string.
<p>
To be safe, use the <b>upload()</b> function (new in version 2.47).
When called with the name of an upload field, <b>upload()</b> returns a
filehandle, or undef if the parameter is not a valid filehandle.
<pre>
$fh = $query->upload('uploaded_file');
while (<$fh>) {
print;
}
</pre>
<p>
In an list context, upload() will return an array of filehandles.
This makes it possible to create forms that use the same name for
multiple upload fields.
<p>
This is the recommended idiom.
<p>
You can have several file upload fields in the same form, and even
give them the same name if you like (in the latter case
<CODE>param()</CODE> will return a list of file names). However, if
the user attempts to upload several files with exactly the same name,
CGI.pm will only return the last of them. This is a known bug.
<P>
When processing an uploaded file, CGI.pm creates a temporary file on
your hard disk and passes you a file handle to that file. After you
are finished with the file handle, CGI.pm unlinks (deletes) the
temporary file. If you need to you can access the temporary file
directly. Its name is stored inside the CGI object's "private" data,
and you can access it by passing the file name to the
<a href="#tmpfilename">tmpFileName()</a> method:
<pre>
$filename = $query->param('uploaded_file');
$tmpfilename = $query->tmpFileName($filename);
</pre>
<p>
The temporary file will be deleted automatically when your program
exits unless you manually rename it. On some operating systems (such
as Windows NT), you will need to close the temporary file's filehandle
before your program exits. Otherwise the attempt to delete the
temporary file will fail.
<p>
You can set up a callback that will be called whenever a file upload
is being read during the form processing. This is much like the
UPLOAD_HOOK facility available in Apache::Request, with the exception
that the first argument to the callback is an Apache::Upload object,
here it's the remote filename.
<p>
<pre>
$q = CGI->new(\&hook);
sub hook {
my ($filename, $buffer, $bytes_read, $data) = @_;
print "Read $bytes_read bytes of $filename\n";
}
</pre>
<p>
If using the function-oriented interface, call the CGI::upload_hook()
method before calling param() or any other CGI functions:
CGI::upload_hook(\&hook,$data);
<p>
This method is not exported by default. You will have to import it
explicitly if you wish to use it without the CGI:: prefix.
<p>
A potential problem with the temporary file upload feature is that the
temporary file is accessible to any local user on the system. In
previous versions of this module, the temporary file was world
readable, meaning that anyone could peak at what was being uploaded.
As of version 2.36, the modes on the temp file have been changed to
read/write by owner only. Only the Web server and its CGI scripts can
access the temp file. Unfortunately this means that one CGI script
can spy on another! To make the temporary files
<strong>really</strong> private, set the CGI global variable
$CGI::PRIVATE_TEMPFILES to 1. Alternatively, call the built-in
function CGI::private_tempfiles(1), or just <cite>use CGI
qw/-private_tempfiles</cite>. The temp file will now be unlinked as
soon as it is created, making it inaccessible to other users. The
<strong>downside</strong> of this is that you will be unable to access
this temporary file directly (<cite>tmpFileName()</cite> will continue
to return a string, but you will find no file at that location.)
Further, since PRIVATE_TEMPFILES is a global variable, its setting
will affect all instances of CGI.pm if you are running mod_perl. You
can work around this limitation by declaring $CGI::PRIVATE_TEMPFILES
as a local at the top of your script.
<p>
On Windows NT, it is impossible to make a temporary file private.
This is because Windows doesn't allow you to delete a file before
closing it.
<p>
Usually the browser sends along some header information along with the
text of the file itself. Currently the headers contain only the
original file name and the MIME content type (if known). Future
browsers might send other information as well (such as modification
date and size). To retrieve this information, call
<strong>uploadInfo()</strong>. It returns a reference to an
associative array containing all the document headers. For example,
this code fragment retrieves the MIME type of the uploaded file (be
careful to use the proper capitalization for "Content-Type"!):
<pre>
$filename = $query->param('uploaded_file');
$type = $query->uploadInfo($filename)->{'Content-Type'};
unless ($type eq 'text/html') {
die "HTML FILES ONLY!";
}
</pre>
<p>
<strong>JavaScripting:</strong> Like textfield(), filefield() accepts
<strong>-onChange, -onFocus, -onBlur, -onMouseOver,
-onMouseOut</strong> and <strong>-onSelect</strong> parameters to
register <a href="#javascripting"> JavaScript</a> event handlers.
<A HREF="#upload_caveats">Caveats and potential problems in
the file upload feature.</A>
<H3><A NAME="menu">Creating A Popup Menu</A></H3>
<PRE>
<EM>Named parameter style</EM>
print $query->popup_menu(-name=>'menu_name',
-values=>[qw/eenie meenie minie/],
-labels=>{'eenie'=>'one',
'meenie'=>'two',
'minie'=>'three'},
-default=>'meenie');
print $query->popup_menu(-name=>'menu_name',
-values=>['eenie','meenie','minie'],
-default=>'meenie');
<EM>Old style</EM>
print $query->popup_menu('menu_name',
['eenie','meenie','minie'],'meenie',
{'eenie'=>'one','meenie'=>'two','minie'=>'three'});
</PRE>
<STRONG>popup_menu()</STRONG> creates a menu.
<UL>
<LI>The required first argument (<strong>-name</strong>) is the menu's name.
<LI>The required second argument (<strong>-values</strong>) is an array
<EM>reference</EM> containing the list
of menu items in the menu. You can pass the method an anonymous
array, as shown in the example, or a reference to a named array,
such as <TT>\@foo</TT>. If you pass a <em>HASH reference</em>,
the keys will be used for the menu values, and the values will
be used for the menu labels (see -labels below). However, the
menu values will be in arbitrary order.
<LI>The optional third parameter (<strong>-default</strong>) is the name of the
default menu choice.
If not specified, the first item will be the default. The value of
the previous choice will be maintained across queries.
<LI>The optional fourth parameter (<strong>-labels</strong>) allows you
to pass a reference to an associative array containing user-visible
labels for one or more of the menu items. You can use this when you
want the user to see one menu string, but have the browser return your
program a different one. If you don't specify this, the value string
will be used instead ("eenie", "meenie" and "minie" in this
example). This is equivalent to using a hash reference for the
-values parameter.
</UL>
When the form is processed, the selected value of the popup menu can
be retrieved using:
<PRE>
$popup_menu_value = $query->param('menu_name');
</PRE>
<strong>JavaScripting:</strong> You can provide <strong>-onChange,
-onFocus, -onMouseOver, -onMouseOut, and -onBlur</strong> parameters
to register <a href="#javascripting">JavaScript</a> event handlers.
<H3><A NAME="scrolling_list">Creating A Scrolling List</A></H3>
<PRE>
<EM>Named parameter style</EM>
print $query->scrolling_list(-name=>'list_name',
-values=>['eenie','meenie','minie','moe'],
-default=>['eenie','moe'],
-size=>5,
-multiple=>'true',
-labels=>\%labels);
<EM>Old style</EM>
print $query->scrolling_list('list_name',
['eenie','meenie','minie','moe'],
['eenie','moe'],5,'true',
\%labels);
</PRE>
<STRONG>scrolling_list()</STRONG> creates a scrolling list.
<UL>
<LI>The first and second arguments (<strong>-name, -values</strong>)are the list name
and values, respectively. As in the popup menu, the second argument should
be an array reference or hash reference. In the latter case,
the values of the hash are used as the human-readable labels in
the list.
<LI>The optional third argument (<strong>-default</strong>)can be either a reference
to a list containing the values to be selected by default, or can be a
single value to select. If this argument is missing or undefined,
then nothing is selected when the list first appears.
<LI>The optional fourth argument (<strong>-size</strong>) is the display size of the list.
<LI>The optional fifth argument (<strong>-multiple</strong>) can be set to true to allow multiple
simultaneous selections.
<LI>The option sixth argument (<strong>-labels</strong>) can be used to assign user-visible labels
to the list items different from the ones used for the values
as above. This is equivalent to passing a hash reference to -values.
In this example we assume that an associative array <CODE>%labels</CODE>
has already been created.
</UL>
When this form is processed, all selected list items will be returned as
a list under the parameter name 'list_name'. The values of the
selected items can be retrieved with:
<PRE>
@selected = $query->param('list_name');
</PRE>
<strong>JavaScripting:</strong> You can provide <strong>-onChange,
-onFocus, -onMouseOver, -onMouseOut</strong> and
<strong>-onBlur</strong> parameters to register <a
href="#javascripting">JavaScript</a> event handlers.
<H3><A NAME="checkbox_group">Creating A Group Of Related Checkboxes</A></H3>
<PRE>
<EM>Named parameter style</EM>
print $query->checkbox_group(-name=>'group_name',
-values=>['eenie','meenie','minie','moe'],
-default=>['eenie','moe'],
-linebreak=>'true',
-labels=>\%labels);
<EM>Old Style</EM>
print $query->checkbox_group('group_name',
['eenie','meenie','minie','moe'],
['eenie','moe'],'true',\%labels);
<EM>HTML3 Browsers Only</EM>
print $query->checkbox_group(-name=>'group_name',
-values=>['eenie','meenie','minie','moe'],
-rows=>2,-columns=>2);
</PRE>
<STRONG>checkbox_group()</STRONG> creates a list of checkboxes that are related
by the same name.
<UL>
<LI>The first and second arguments (<strong>-name, -values</strong>) are the checkbox
name and values,
respectively. As in the popup menu, the second argument should
be an array reference or a hash reference. These values are
used for the user-readable labels printed next to the checkboxes
as well as for the values passed to your script in the query string.
<LI>The optional third argument (<strong>-default</strong>) can be either a
reference to a list
containing the values to be checked by default, or can be a
single value to checked. If this argument is missing or undefined,
then nothing is selected when the list first appears.
<LI>The optional fourth argument (<strong>-linebreak</strong>) can be set to true to
place line breaks
between the checkboxes so that they appear as a vertical list.
Otherwise, they will be strung together on a horizontal line.
When the form is procesed, all checked boxes will be returned as
a list under the parameter name 'group_name'. The values of the
"on" checkboxes can be retrieved with:
<LI>The optional fifth argument (<strong>-labels</strong>) is a reference to an hash
of checkbox labels. This allows you to use different strings for
the user-visible button labels and the values sent to your script. In
this example we assume that an associative array <CODE>%labels</CODE>
has previously been created. This is equivalent to passing a
hash reference to -values. If you don't use
<strong>-nolabels</strong>, CGI.pm will add HTML label
tag around each checkbox and its label, so a browser can identify the
text as form element label properly.
<LI>The optional parameter <STRONG>-nolabels</STRONG> can be used to
suppress the printing of labels next to the button. This is
useful if you want to capture the button elements individually and use them
inside labeled HTML3 tables.
<LI><STRONG>Browsers that understand HTML3 tables</STRONG>
(such as Netscape) can take advantage of the optional
parameters <STRONG>-rows</STRONG>, and <STRONG>-columns</STRONG>.
These parameters cause
checkbox_group() to return an HTML3 compatible table containing
the checkbox group formatted with the specified number of rows
and columns. You can provide just the -columns parameter if you
wish; checkbox_group will calculate the correct number of rows
for you.
<P>
To include row and column headings in the returned table, you
can use the <STRONG>-rowheaders</STRONG> and <STRONG>-colheaders</STRONG>
parameters. Both
of these accept a pointer to an array of headings to use.
The headings are just decorative. They don't reorganize the
interpetation of the checkboxes -- they're still a single named
unit.
<P>
When viewed with browsers that don't understand HTML3 tables, the
-rows and -columns parameters will leave you
with a group of buttons that may be awkwardly formatted but
still useable. However, if you add row
and/or column headings, the resulting text will be very hard to
read.
</UL>
When the form is processed, the list of checked buttons in the group
can be retrieved like this:
<PRE>
@turned_on = $query->param('group_name');
</PRE>
This function actually returns an array of button elements. You can
capture the array and do interesting things with it, such as incorporating
it into your own tables or lists. The <strong>-nolabels</strong> option
is also useful in this regard:
<PRE>
@h = $query->checkbox_group(-name=>'choice',
-value=>['fee','fie','foe'],
-nolabels=>1);
create_nice_table(@h);
</PRE>
<strong>JavaScripting:</strong> You can provide an <strong>-onClick</strong>
parameter to register some <a href="#javascripting">JavaScript</a>
code to be performed every time the user clicks on any of the buttons
in the group.
<H3><A NAME="checkbox">Creating A Standalone Checkbox</A></H3>
<PRE>
<EM>Named parameter list</EM>
print $query->checkbox(-name=>'checkbox_name',
-checked=>'checked',
-value=>'TURNED ON',
-label=>'Turn me on');
<EM>Old style</EM>
print $query->checkbox('checkbox_name',1,'TURNED ON','Turn me on');
</PRE>
<STRONG>checkbox()</STRONG> is used to create an isolated checkbox that isn't logically
related to any others.
<UL>
<LI>The first parameter (<STRONG>-name</STRONG> is the required name
for the checkbox. It
will also be used for the user-readable label printed next to
the checkbox.
<LI>The optional second parameter (<STRONG>-checked</STRONG> specifies
that the checkbox is turned on by default. Aliases for this
parameter are <STRONG>-selected</STRONG> and <STRONG>-on</STRONG>.
<LI>The optional third parameter (<STRONG>-value</STRONG> specifies
the value of the checkbox
when it is checked. If not provided, the word "on" is assumed.
<LI>The optional fourth parameter (<STRONG>-label</STRONG> assigns a
user-visible label to the button.
If not provided, the checkbox's name will be used.
CGI.pm will add HTML label tag around the checkbox and its label,
so a browser can identify the text as form element label properly.
</UL>
The value of the checkbox can be retrieved using:
<PRE>
$turned_on = $query->param('checkbox_name');
</PRE>
<strong>JavaScripting:</strong> You can provide an <code>-onClick</code>
parameter to register some <a href="#javascripting">JavaScript</a>
code to be performed every time the user clicks on the button.
<H3><A NAME="radio">Creating A Radio Button Group</A></H3>
<PRE>
<EM>Named parameter style</EM>
print $query->radio_group(-name=>'group_name',
-values=>['eenie','meenie','minie'],
-default=>'meenie',
-linebreak=>'true',
-labels=>\%labels);
<EM>Old style</EM>
print $query->radio_group('group_name',['eenie','meenie','minie'],
'meenie','true',\%labels);
<EM>HTML3-compatible browsers only</EM>
print $query->radio_group(-name=>'group_name',
-values=>['eenie','meenie','minie','moe'],
-rows=>2,-columns=>2);
</PRE>
<STRONG>radio_group()</STRONG> creates a set of logically-related radio buttons.
Turning one member of the group on turns the others off.
<UL>
<LI>The first argument (<STRONG>-name</STRONG> is the name of the
group and is required.
<LI>The second argument (<STRONG>-values</STRONG> is the list of
values for the radio buttons.
The values and the labels that appear on the page are identical.
Pass an array <EM>reference</EM> in the second argument, either using
an anonymous array, as shown, or by referencing a named array as
in <CODE>\@foo</CODE>. You may also use a hash reference in
order to produce human-readable labels that are different from
the values that will be returned as parameters to the CGI
script.
<LI>The optional third parameter (<STRONG>-default</STRONG> is the
value of the default button to
turn on. If not specified, the first item will be the default. Specify
some nonexistent value, such as "-" if you don't want any button
to be turned on.
<LI>The optional fourth parameter (<STRONG>-linebreak</STRONG> can be
set to 'true' to put
line breaks between the buttons, creating a vertical list.
<LI>The optional fifth parameter (<STRONG>-labels</STRONG> specifies
an associative array containing labels to be printed next to
each button. If not provided the button value will be
used instead. This example assumes that the associative array
<CODE>%labels</CODE> has already been defined. This is
equivalent to passing a hash reference to -values.
If you don't use <strong>-nolabels</strong>, CGI.pm will add HTML label
tag around each radio button and its label, so a browser can identify the
text as form element label properly.
<LI>The optional parameter <STRONG>-nolabels</STRONG> can be used to
suppress the printing of labels next to the button. This is
useful if you want to capture the button elements individually and use them
inside labeled HTML3 tables.
<LI><STRONG>Browsers that understand HTML3 tables</STRONG>
(such as Netscape) can take advantage of the optional
parameters <STRONG>-rows</STRONG>, and <STRONG>-columns</STRONG>.
These parameters cause
radio_group() to return an HTML3 compatible table containing
the radio cluster formatted with the specified number of rows
and columns. You can provide just the -columns parameter if you
wish; radio_group will calculate the correct number of rows
for you.
<P>
To include row and column headings in the returned table, you
can use the <STRONG>-rowheader</STRONG> and <STRONG>-colheader</STRONG>
parameters. Both
of these accept a pointer to an array of headings to use.
The headings are just decorative. They don't reorganize the
interpetation of the radio buttons -- they're still a single named
unit.
<P>
When viewed with browsers that don't understand HTML3 tables, the
-rows and -columns parameters will leave you
with a group of buttons that may be awkwardly formatted but
still useable. However, if you add row
and/or column headings, the resulting text will be very hard to
read.
</UL>
When the form is processed, the selected radio button can
be retrieved using:
<PRE>
$which_radio_button = $query->param('group_name');
</PRE>
This function actually returns an array of button elements. You can
capture the array and do interesting things with it, such as incorporating
it into your own tables or lists The <strong>-nolabels</strong> option
is useful in this regard.:
<PRE>
@h = $query->radio_group(-name=>'choice',
-value=>['fee','fie','foe'],
-nolabels=>1);
create_nice_table(@h);
</PRE>
<p>
<strong>JavaScripting</strong>: You can provide an <strong>-onClick</strong>
parameter to register some <a href="#javascripting">JavaScript</a>
code to be performed every time the user clicks on any of the buttons
in the group.
<H3><A NAME="submit">Creating A Submit Button</A></H3>
<PRE>
<EM>Named parameter style</EM>
print $query->submit(-name=>'button_name',
-value=>'value');
<EM>Old style</EM>
print $query->submit('button_name','value');
</PRE>
<STRONG>submit()</STRONG> will create the query submission button. Every form
should have one of these.
<UL>
<LI>The first argument (<STRONG>-name</STRONG>is optional.
You can give the button a
name if you have several submission buttons in your form and
you want to distinguish between them.
<LI>The second argument (<STRONG>-value</STRONG>is also optional.
This gives the button
a value that will be passed to your script in the query string,
and will also appear as the user-visible label.
<p>
You can figure out which of several buttons was pressed by using
different values for each one:
<PRE>
$which_one = $query->param('button_name');
</PRE>
<LI>You can use <strong>-label</strong> as an alias for
<strong>-value</strong>. I always get confused about which of
<code>-name</code> and <code>-value</code> changes the user-visible
label on the button.
</UL>
<strong>JavaScripting:</strong> You can provide an <strong>-onClick</strong>
parameter to register some <a href="#javascripting">JavaScript</a>
code to be performed every time the user clicks on the button.
You can't prevent a form from being submitted, however. You must
provide an <strong>-onSubmit</strong> handler to the <a href="#">form
itself</a> to do that.
<H3><A NAME="reset">Creating A Reset Button</A></H3>
<PRE>
print $query->reset
</PRE>
<STRONG>reset()</STRONG> creates the "reset" button. It undoes whatever
changes the user has recently made to the form, but does <STRONG>not</STRONG>
necessarily reset the form all the way to the defaults. See <STRONG>defaults()</STRONG>
for that. It takes the optional label for the button ("Reset" by default).
<strong>JavaScripting:</strong> You can provide an <strong>-onClick</strong>
parameter to register some <a href="#javascripting">JavaScript</a>
code to be performed every time the user clicks on the button.
<H3><A NAME="defaults">Creating A Defaults Button</A></H3>
<PRE>
print $query->defaults('button_label')
</PRE>
<STRONG>defaults()</STRONG> creates "reset to defaults" button.
It takes the optional label for the button ("Defaults" by default).
When the user presses this button, the form will automagically
be cleared entirely and set to the defaults you specify in your
script, just as it was the first time it was called.
<H3><A NAME="hidden">Creating A Hidden Field</A></H3>
<PRE>
<EM>Named parameter style</EM>
print $query->hidden(-name=>'hidden_name',
-default=>['value1','value2'...]);
<EM>Old style</EM>
print $query->hidden('hidden_name','value1','value2'...);
</PRE>
<STRONG>hidden()</STRONG> produces a text field that can't be seen by the user. It
is useful for passing state variable information from one invocation
of the script to the next.
<UL>
<LI>The first argument (<STRONG>-name</STRONG>) is required and
specifies the name of this field.
<LI>The second and subsequent arguments specify the value for the hidden field.
This is a quick and dirty way of passing perl arrays through forms. If
you use the named parameter style, you must provide the parameter
<STRONG>-default</STRONG> and an array reference here.
</UL>
<STRONG><A NAME="hidden_fields_warning">
<IMG SRC="examples/caution.xbm" ALT="[CAUTION]">
As of version 2.0 I have changed the behavior of hidden fields
once again. Read this if you use hidden fields.</A></STRONG>
<P>
Hidden fields used to behave differently from all other fields: the
provided default values always overrode the "sticky" values. This was the
behavior people seemed to expect, however it turns out to make it harder
to write state-maintaining forms such as shopping cart programs. Therefore
I have made the behavior consistent with other fields.
<P>
Just like all the other form elements, the value of a
hidden field is "sticky". If you want to replace a hidden field with
some other values after the script has been called once you'll have to
do it manually before writing out the form element:
<PRE>
$query->param('hidden_name','new','values','here');
print $query->hidden('hidden_name');
</PRE>
Fetch the value of a hidden field this way:
<PRE>
$hidden_value = $query->param('hidden_name');
-or (for values created with arrays)-
@hidden_values = $query->param('hidden_name');
</PRE>
<H3><A NAME="image">Creating a Clickable Image Button</A></H3>
<PRE>
<EM>Named parameter style</EM>
print $query->image_button(-name=>'button_name',
-src=>'/images/NYNY.gif',
-align=>'MIDDLE');
<EM>Old style</EM>
print $query->image_button('button_name','/source/URL','MIDDLE');
</PRE>
<STRONG>image_button()</STRONG> produces an inline image that acts as
a submission button. When selected, the form is submitted and the
clicked (x,y) coordinates are submitted as well.
<UL>
<LI>The first argument(<STRONG>-name</STRONG> is required and
specifies the name of this
field.
<LI>The second argument (<STRONG>-src</STRONG>specifies the URL of
the image to display. It
must be one of the types supported by inline images (e.g. GIF), but
can be any local or remote URL.
<LI>The third argument (<STRONG>-align</STRONG>is anything you might
want to use in the ALIGN attribute, such as
TOP, BOTTOM, LEFT, RIGHT or MIDDLE. This field is optional.
</UL>
When the image is clicked, the results are passed to your script in two
parameters named "button_name.x" and "button_name.y", where "button_name"
is the name of the image button.
<PRE>
$x = $query->param('button_name.x');
$y = $query->param('button_name.y');
</PRE>
<strong>JavaScripting:</strong> Current versions of JavaScript do not
honor the <code>-onClick</code> handler, unlike other buttons.
<H3><A NAME="button">Creating a JavaScript Button</A></H3>
<PRE>
<EM>Named parameter style</EM>
print $query->button(-name=>'button1',
-value=>'Click Me',
-onClick=>'doButton(this)');
<EM>Old style</EM>
print $query->image_button('button1','Click Me','doButton(this)');
</PRE>
<STRONG>button()</STRONG> creates a JavaScript button. When the button is
pressed, the JavaScript code pointed to by the <code>-onClick</code> parameter
is executed. This only works with Netscape 2.0 and higher. Other browsers
do not recognize JavaScript and probably won't even display the button.
<UL>
<LI>The first argument(<STRONG>-name</STRONG> is required and
specifies the name of this field.
<LI>The second argument (<STRONG>-value</STRONG> gives the button
a value, and will be used as the user-visible label on the button.
<LI>The third argument (<STRONG>-onClick</STRONG> is any valid
JavaScript code. It's usually a call to a JavaScript function
defined somewhere else (see the <a href="#html">start_html()</a>
method), but can be any JavaScript you like. Multiple lines
are allowed, but you must be careful not to include any double
quotes in the JavaScript text.
</UL>
See <a href="#javascripting">JavaScripting</a> for more information.
<H3><A NAME="escape">Controlling HTML Autoescaping</A></H3>
By default, if you use a special HTML character such as >, <
or & as the label or value of a button, it will be escaped
using the appropriate HTML escape sequence (e.g. &gt;). This
lets you use anything at all for the text of a form field without
worrying about breaking the HTML document. However, it may also
interfere with your ability to use special characters, such as
Á as default contents of fields. You can turn this
feature on and off with the method <CODE>autoEscape()</CODE>.
<P>
Use
<PRE>
$query->autoEscape(0);
</PRE>
to turn automatic HTML escaping off, and
<PRE>
$query->autoEscape(1);
</PRE>
to turn it back on.
<HR>
<H2><A NAME="import">Importing CGI Methods</A></H2>
A large number of scripts allocate only a single query object, use it
to read parameters or to create a fill-out form, and then discard it.
For this type of script, it may be handy to import CGI module methods
into your name space. The most common syntax for this is:
<blockquote><pre>
use CGI qw(:standard);
</pre></blockquote>
This imports the standard methods into your namespace. Now instead of
getting parameters like this:
<blockquote><pre>
use CGI;
$dinner = $query->param('entree');
</pre></blockquote>
You can do it like this:
<blockquote><pre>
use CGI qw(:standard);
$dinner = param('entree');
</pre></blockquote>
Similarly, instead of creating a form like this:
<blockquote><pre>
print $query->start_form,
"Check here if you're happy: ",
$query->checkbox(-name=>'happy',-value=>'Y',-checked=>1),
"<P>",
$query->submit,
$query->end_form;
</pre></blockquote>
You can create it like this:
<blockquote><pre>
print start_form,
"Check here if you're happy: ",
checkbox(-name=>'happy',-value=>'Y',-checked=>1),
p,
submit,
end_form;
</pre></blockquote>
Even though there's no CGI object in view in the second example, state
is maintained using an implicit CGI object that's created
automatically. The form elements created this way are sticky, just as
before. If you need to get at the implicit CGI object directly, you
can refer to it as:
<blockquote><pre>
$CGI::Q;
</pre></blockquote>
<p>
The <strong>use CGI</strong> statement is used to import method names
into the current name space. There is a slight overhead for each name
you import, but ordinarily is nothing to worry about. You can import
selected method names like this:
<blockquote><pre>
use CGI qw(header start_html end_html);
</pre></blockquote>
Ordinarily, however, you'll want to import groups of methods using
export tags. Export tags refer to sets of logically related methods
which are imported as a group with <strong>use</strong>. Tags are
distinguished from ordinary methods by beginning with a ":" character.
This example imports the methods dealing with the CGI protocol
(<code>param()</code> and the like) as well as shortcuts that generate
HTML2-compliant tags:
<blockquote>
<pre>
use CGI qw(:cgi :html2);
</pre>
</blockquote>
Currently there are 8 method families defined in CGI.pm. They are:
<dl>
<dt><cite>:cgi</cite>
<dd>These are all the tags that support one feature or another of
the CGI protocol, including param(), path_info(), cookie(),
request_method(), header() and the like.
<dt><cite>:form</cite>
<dd>These are all the form element-generating methods, including
start_form(), textfield(), etc.
<dt><cite>:html2</cite>
<dd>These are HTML2-defined shortcuts such as br(), p() and head().
It also includes such things
as start_html() and end_html() that aren't exactly HTML2, but
are close enough.
<dt><cite>:html3</cite>
<dd>These contain various HTML3 tags for tables, frames, super- and
subscripts, applets and other objects.
<dt><cite>:html4</cite>
<dd>These contain various HTML4 tags, including table headers and footers.
<dt><cite>:netscape</cite>
<dd>These are Netscape extensions not included in the HTML3
category including blink() and center().
<dt><cite>:html</cite>
<dd>These are all the HTML generating shortcuts, comprising the
union of <cite>html2, html3,</cite> and <cite>netscape</cite>.
<dt><cite>:multipart</cite>
<dd>These are various functions that simplify creating documents of
the various multipart MIME types, and are useful for
implementing server push.
<dt><cite>:standard</cite>
<dd>This is the union of <cite>html2, html3, html4, form,</cite> and
<cite>:cgi</cite>.
<dt><cite>:all</cite>
<dd>This imports all the public methods into your namespace!
</dl>
<h3>Pragmas</h3>
In addition to importing individual methods and method families,
<cite>use CGI</cite> recognizes several pragmas, all proceeded by
dashes.
<dl>
<dt><b>-any</b>
<dd>When you <cite>use CGI -any</cite>, then any method that the
query object doesn't recognize will be interpreted as a new HTML tag.
This allows you to support the next <cite>ad hoc</cite> Netscape or
Microsoft HTML extension. For example, to support Netscape's latest
tag, <GRADIENT> (which causes the user's desktop to be flooded
with a rotating gradient fill until his machine reboots), you can use
something like this:
<blockquote><pre>
use CGI qw(-any);
$q=new CGI;
print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
</pre></blockquote>
Since using <cite>any</cite> causes any mistyped method name
to be interpreted as an HTML tag, use it with care or not at
all.
<p>
<dt><b>-compile</b>
<dd>This causes the indicated autoloaded methods to be compiled up front,
rather than deferred to later. This is useful for scripts that
run for an extended period of time under FastCGI or mod_perl,
and for those destined to be crunched by Malcolm Beattie's Perl
compiler. Use it in conjunction with the methods or method familes
you plan to use.
<blockquote><pre>
use CGI qw(-compile :standard :html3);
</pre></blockquote>
or even
<blockquote><pre>
use CGI qw(-compile :all);
</pre></blockquote>
<p>
Note that using the -compile pragma in this way will always have
the effect of importing the compiled functions into the current
namespace. If you want to compile without importing use the
<a href="#compile">compile()</a> method instead.
<p>
<dt><b>-autoload</b>
<dd>Overrides the autoloader so that any function in your program that is
not recognized is referred to CGI.pm for possible evaluation.
This allows you to use all the CGI.pm functions without adding
them to your symbol table, which is of concern for mod_perl
users who are worried about memory consumption.
<strong>Warning:</strong> when <em>-autoload</em> is in effect,
you cannot use "poetry mode" (functions without the
parenthesis). Use <cite>hr()</cite> rather than
<cite>hr</cite>, or add something like <em>use subs qw/hr p
header/</em> to the top of your script.
<p>
<dt><b>-nosticky</b>
<dd>Turns off "sticky" behavior in fill-out forms. Every form
element will act as if you passed -override.
<p>
<dt><b>-no_xhtml</b>
<dd>By default, CGI.pm versions 2.69 and higher emit XHTML
(<a href="http://www.w3.org/TR/xhtml1/">http://www.w3.org/TR/xhtml1/</a>).
The -no_xhtml pragma disables this feature. Thanks to Michalis Kabrianis
<kabrianis@hellug.gr> for this feature.
<p>
<dt><b>-nph</b>
<dd>This makes CGI.pm produce a header appropriate for an NPH (no
parsed header) script. You may need to do other things as well
to tell the server that the script is NPH. See the <a href="#nph">discussion
of NPH scripts</a> below.
<p>
<dt><b>-oldstyle_urls</b>
<dd>Separate the name=value pairs in CGI parameter query strings emitted by
self_url() and query_string() with ampersands. Otherwise, CGI.pm emits
HTML-compliant semicolons. If you use this form, be sure to escape ampersands
into HTML entities with escapeHTML. Example:
<blockquote>
<pre>
$href = $q->self_url();
$href = escapeHTML($href);
print <a href="$href">I'm talking to myself</a>
</pre>
</blockquote>
<p>
<dt><b>-newstyle_urls</b>
<dd>Separate the name=value pairs in CGI parameter query strings with
semicolons rather than ampersands. For example:
<blockquote>
<pre>
name=fred;age=24;favorite_color=3
</pre>
</blockquote>
As of version 2.64, this is the default style.
<dt><b>-no_debug</b>
<dd>This turns off the command-line processing features. If you
want to run a CGI.pm script from the command line to produce
HTML, and you don't want it interpreting arguments on the command
line as CGI name=value arguments, then use this pragma:
<blockquote><pre>
use CGI qw(-no_debug :standard);
</pre></blockquote>
<p>
<dt><b>-debug</b>
<dd>This turns on full debugging. In addition to reading CGI arguments
from the command-line processing, CGI.pm will pause and try to read
arguments from STDIN, producing the message "(offline mode: enter
name=value pairs on standard input)" features.
<p>
See <a href="#debugging">debugging</a> for more details.
<p>
<dt><b>-private_tempfiles</b>
<dd>CGI.pm can process uploaded file. Ordinarily it spools the
uploaded file to a temporary directory, then deletes the file
when done. However, this opens the risk of eavesdropping as
described in the <a href="#upload">file upload section.</a>
Another CGI script author could peek at this data during the
upload, even if it is confidential information. On Unix systems,
the <b>-private_tempfiles</b>
pragma will cause the temporary file to be unlinked as soon
as it is opened and before any data is written into it,
eliminating the risk of eavesdropping.
</dl>
<h3>Special Forms for Importing HTML-Tag Functions</h3>
Many of the methods generate HTML tags. As described below, tag
functions automatically generate both the opening and closing tags.
For example:
<pre>
print h1('Level 1 Header');
</pre>
produces
<pre>
<H1>Level 1 Header</H1>
</pre>
There will be some times when you want to produce the start and end
tags yourself. In this case, you can use the form
start_I<cite>tag_name</cite> and end_I<cite>tag_name</cite>, as in:
<pre>
print start_h1,'Level 1 Header',end_h1;
</pre>
With a few exceptions (described below), start_<cite>tag_name</cite>
and end_I<cite>tag_name</cite> functions are not generated
automatically when you <cite>use CGI</cite>. However, you can specify
the tags you want to generate <cite>start/end</cite> functions for by
putting an asterisk in front of their name, or, alternatively,
requesting either "start_<cite>tag_name</cite>" or
"end_<cite>tag_name</cite>" in the import list.
<p>
Example:
<pre>
use CGI qw/:standard *table start_ul/;
</pre>
In this example, the following functions are generated in addition to
the standard ones:
<ol>
<li><code>start_table()</code> (generates a <TABLE> tag)
<li><code>end_table()</code> (generates a </TABLE> tag)
<li><code>start_ul()</code> (generates a <UL> tag)
<li><code>end_ul()</code> (generates a </UL> tag)
</ol>
<h3>AUTOESCAPING HTML</h3>
By default, all HTML that are emitted by the form-generating functions
are passed through a function called escapeHTML():
<blockquote><pre>
$escaped_string = escapeHTML("unescaped string");
</pre></blockquote>
<p>
Provided that you have specified a character set of ISO-8859-1 (the
default), the standard HTML escaping rules will be used. The "<"
character becomes "&lt;", ">" becomes "&gt;", "&"
becomes "&amp;", and the quote character becomes "&quot;". In
addition, the hexadecimal 0x8b and 0x9b characters, which many
windows-based browsers interpret as the left and right angle-bracket
characters, are replaced by their numeric HTML entities ("&#139"
and "&#155;"). If you manually change the charset, either by
calling the charset() method explicitly or by passing a -charset
argument to header(), then <b>all</b> characters will be replaced by
their numeric entities, since CGI.pm has no lookup table for all the
possible encodings.
<p>
Autoescaping does not apply to other HTML-generating functions, such
as h1(). You should call escapeHTML() yourself on any data that is
passed in from the outside, such as nasty text that people may enter
into guestbooks.
<p>
To change the character set, use charset(). To turn
autoescaping off completely, use autoescape():
<blockquote><pre>
$charset = charset([$charset]); # Get or set the current character set.
$flag = autoEscape([$flag]); # Get or set the value of the autoescape flag.
</pre></blockquote>
<h3>PRETTY-PRINTING HTML</h3>
By default, all the HTML produced by these functions comes out as one
long line without carriage returns or indentation. This is yuck, but
it does reduce the size of the documents by 10-20%. To get
pretty-printed output, please use <cite>CGI::Pretty</cite>, a subclass
contributed by <a href="mailto:bpaulsen@lehman.com">Brian Paulsen</a>.
<H3>Optional Utility Functions</H3>
In addition to the standard imported functions, there are a few
optional functions that you must request by name if you want them.
They were originally intended for internal use only, but are now made
available by popular request.
<h4>escape(), unescape()</h4>
<blockquote><pre>
use CGI qw/escape unescape/;
$q = escape('This $string contains ~wonderful~ characters');
$u = unescape($q);
</pre></blockquote>
These functions escape and unescape strings according to the URL
hex escape rules. For example, the space character will be converted
into the string "%20".
<h4>escapeHTML(), unescapeHTML()</h4>
<blockquote><pre>
use CGI qw/escapeHTML unescapeHTML/;
$q = escapeHTML('This string is <illegal> html!');
$u = unescapeHTML($q);
</pre></blockquote>
These functions escape and unescape strings according to the HTML
character entity rules. For example, the character < will be
escaped as &lt;.
<h4><a name="compile">compile()</a></h4>
Ordinarily CGI.pm autoloads most of its functions on an as-needed
basis. This speeds up the loading time by deferring the compilation
phase. However, if you are using mod_perl, FastCGI or another system
that uses a persistent Perl interpreter, you will want to precompile
the methods at initialization time. To accomplish this, call the
package function <b>compile()</b> like this:
<blockquote><pre>
use CGI ();
CGI->compile(':all');
</pre></blockquote>
The arguments to <b>compile()</b> are a list of method names or sets,
and are identical to those accepted by the use operator.
<HR>
<H2><A NAME="debugging">Debugging</A></H2>
If you are running the script
from the command line or in the perl debugger, you can pass the script
a list of keywords or parameter=value pairs on the command line or
from standard input (you don't have to worry about tricking your
script into reading from environment variables).
You can pass keywords like this:
<PRE>
my_script.pl keyword1 keyword2 keyword3
</PRE>
<EM>or this:</EM>
<PRE>
my_script.pl keyword1+keyword2+keyword3
</PRE>
<EM>or this:</EM>
<PRE>
my_script.pl name1=value1 name2=value2
</PRE>
<EM>or this:</EM>
<PRE>
my_script.pl name1=value1&name2=value2
</PRE>
If you pass the <b>-debug</b> pragma to CGI.pm, you can send CGI
name-value pairs as newline-delimited parameters on standard input:
<PRE>
% my_script.pl
first_name=fred
last_name=flintstone
occupation='granite miner'
^D
</PRE>
<P>When debugging, you can use quotation marks and the backslash
character to escape spaces and other funny characters in exactly
the way you would in the shell (which isn't surprising since CGI.pm
uses "shellwords.pl" internally). This lets you do this sort of thing:
<PRE>
my_script.pl 'name 1=I am a long value' name\ 2=two\ words
</PRE>
<p>
If you run a script that uses CGI.pm from the command line and fail to
provide it with any arguments, it will print out the line
<pre>
(offline mode: enter name=value pairs on standard input)
</pre>
then appear to hang. In fact, the library is waiting for you to give
it some parameters to process on its standard input. If you want to
give it some parameters, enter them as shown above, then indicate that
you're finished with input by pressing ^D (^Z on NT/DOS systems). If
you don't want to give CGI.pm parameters, just press ^D.
<p>
You can suppress this behavior in any of the following ways:
<dl>
<dt>1. Call the script with an empty parameter.
<dd>Example:
<pre>
my_script.pl ''
</pre>
<p>
<dt>2. Redirect standard input from /dev/null or an empty file.
<dd>Example:
<pre>
my_script.pl </dev/null
</pre>
<p>
<dt>3. Include "-no_debug" in the list of symbols to import on the
"use" line.
<dd>Example:
<pre>
use CGI qw/:standard -no_debug/;
</pre>
</dl>
<A HREF="#contents">Table of contents</A>
<H3><A NAME="dumping">Dumping Out All The Name/Value Pairs</A></H3>
The <STRONG>Dump()</STRONG> method produces a string consisting of all the query's
name/value pairs formatted nicely as a nested list. This is useful
for debugging purposes:
<PRE>
print $query->Dump
</PRE>
Produces something that looks like this:
<PRE>
<UL>
<LI>name1
<UL>
<LI>value1
<LI>value2
</UL>
<LI>name2
<UL>
<LI>value1
</UL>
</UL>
</PRE>
You can achieve the same effect by incorporating the CGI object directly
into a string, as in:
<PRE>
print "<H2>Current Contents:</H2>\n$query\n";
</PRE>
<HR>
<H2><A NAME="environment">HTTP Session Variables</A></H2>
Some of the more useful environment variables can be fetched
through this interface. The methods are as follows:
<DL>
<DT>Accept()
<DD>Return a list of MIME types that the remote browser
accepts. If you give this method a single argument
corresponding to a MIME type, as in
<CODE>$query->Accept('text/html')</CODE>, it will return a
floating point value corresponding to the browser's
preference for this type from 0.0 (don't want) to 1.0.
Glob types (e.g. text/*) in the browser's accept list
are handled correctly. Note the capitalization of the initial letter. This avoids
conflict with the Perl built-in accept().
<DT>auth_type()
<DD>Return the authorization type, if protection is active. Example "Basic".
<DT><a name="raw_cookie">raw_cookie()</a>
<DD>Returns the "magic cookie" maintained by Netscape 1.1 and higher in a raw
state. You'll probably want to use <a href="cookies">cookie()</a> instead,
which gives you a high-level interface to the cookie functions.
Called with no parameters, raw_cookie() returns the entire
cookie structure, which may consist of several cookies appended
together (you can recover individual cookies by splitting on the
"; " sequence. Called with the name of a cookie, returns the unescaped
value of the cookie as set by the server. This may be useful for retrieving
cookies that your script did not set.
<DT><a name="path_info">path_info()</a>
<DD>Returns additional path information from the script URL.
E.G. fetching <CODE>/cgi-bin/your_script/additional/stuff</CODE> will
result in <CODE>$query->path_info()</CODE> returning
<CODE>"/additional/stuff"</CODE>. In addition to reading the
path information, you can set it by giving path_info() an
optional string argument. The argument is expected to begin
with a "/". If not present, one will be added for you. The new
path information will be returned by subsequent calls to
path_info(), and will be incorporated into the URL generated by
self_url().
<DT>path_translated()
<DD>As per path_info() but returns the additional
path information translated into a physical path, e.g.
<CODE>"/usr/local/etc/httpd/htdocs/additional/stuff"</CODE>.
You cannot change the path_translated, nor will setting the
additional path information change this value. The reason for
this restriction is that the translation of path information
into a physical path is ordinarily done by the server in a layer
that is inaccessible to CGI scripts.
<DT>query_string()
<DD>Returns a query string suitable for maintaining state.
<DT>referer()
<DD>Return the URL of the page the browser was viewing
prior to fetching your script. Not available for all
browsers.
<DT>remote_addr()
<DD>Return the dotted IP address of the remote host.
<DT>remote_ident()
<DD>Return the identity-checking information from the remote host. Only
available if the remote host has the identd daemon turned on.
<DT>remote_host()
<DD>Returns either the remote host name or IP address.
if the former is unavailable.
<DT>remote_user()
<DD>Return the name given by the remote user during password authorization.
<DT>request_method()
<DD>Return the HTTP method used to request your script's URL, usually
one of <code>GET, POST,</code> or <code>HEAD</code>.
<DT>script_name()
<DD>Return the script name as a partial URL, for self-refering
scripts.
<DT>server_name()
<DD>Return the name of the WWW server the script is running under.
<DT>server_software()
<DD>Return the name and version of the server software.
<DT>virtual_host()
<DD>When using the virtual host feature of some servers, returns the
name of the virtual host the browser is accessing.
<DT>server_port()
<DD>Return the communications port the server is using.
<DT>virtual_port()
<DD>Like server_port() except that it takes virtual hosts into account.
<DT>user_agent()
<DD>Returns the identity of the remote user's browser software,
e.g. "Mozilla/1.1N (Macintosh; I; 68K)"
<DT>user_name()
<DD>Attempts to obtain the remote user's name, using a variety
of environment variables. This only works with older browsers
such as Mosaic. Netscape does not reliably report the user
name!
<DT>http()
<DD>Called with no arguments returns the list of HTTP environment
variables, including such things as HTTP_USER_AGENT,
HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
like-named HTTP header fields in the request. Called with the name of
an HTTP header field, returns its value. Capitalization and the use
of hyphens versus underscores are not significant.
<p>
For example, all three of these examples are equivalent:
<pre>
$requested_language = $q->http('Accept-language');
$requested_language = $q->http('Accept_language');
$requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
</pre>
<DT>https()
<DD>The same as http(), but operates on the HTTPS environment variables
present when the SSL protocol is in effect. Can be used to determine
whether SSL is turned on.
</DL>
<A HREF="#contents">Table of contents</A>
<HR>
<H2><A NAME="cookies">HTTP Cookies</A></H2>
Netscape browsers versions 1.1 and higher, and all versions of
Internet Explorer support a so-called "cookie" designed to help
maintain state within a browser session. CGI.pm has several methods
that support cookies.
<p>
A cookie is a name=value pair much like the named parameters in a CGI
query string. CGI scripts create one or more cookies and send
them to the browser in the HTTP header. The browser maintains a list
of cookies that belong to a particular Web server, and returns them
to the CGI script during subsequent interactions.
<p>
In addition to the required name=value pair, each cookie has several
optional attributes:
<dl>
<dt>an expiration time
<dd>This is a time/date string (in a special GMT format) that indicates
when a cookie expires. The cookie will be saved and returned to your
script until this expiration date is reached if the user exits
the browser and restarts it. If an expiration date isn't specified, the cookie
will remain active until the user quits the browser.
<p>
Negative expiration times (e.g. "-1d") cause some browsers
to delete the cookie from its persistent store. This is a
poorly documented feature.
<p>
<dt>a domain
<dd>This is a partial or complete domain name for which the cookie is
valid. The browser will return the cookie to any host that matches
the partial domain name. For example, if you specify a domain name
of ".capricorn.com", then the browser will return the cookie to
Web servers running on any of the machines "www.capricorn.com",
"www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
must contain at least two periods to prevent attempts to match
on top level domains like ".edu". If no domain is specified, then
the browser will only return the cookie to servers on the host the
cookie originated from.<p>
<dt>a path
<dd>If you provide a cookie path attribute, the browser will check it
against your script's URL before returning the cookie. For example,
if you specify the path "/cgi-bin", then the cookie will be returned
to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
and "/cgi-bin/customer_service/complain.pl", but not to the script
"/cgi-private/site_admin.pl". By default, path is set to "/", which
causes the cookie to be sent to any CGI script on your site.
<dt>a "secure" flag
<dd>If the "secure" attribute is set, the cookie will only be sent to your
script if the CGI request is occurring on a secure channel, such as SSL.
</dl>
The interface to HTTP cookies is the <strong>cookie()</strong> method:
<pre>
$cookie = $query->cookie(-name=>'sessionID',
-value=>'xyzzy',
-expires=>'+1h',
-path=>'/cgi-bin/database',
-domain=>'.capricorn.org',
-secure=>1);
print $query->header(-cookie=>$cookie);
</pre>
<strong>cookie()</strong> creates a new cookie. Its parameters include:
<dl>
<dt><strong>-name</strong>
<dd>The name of the cookie (required). This can be any string at all.
Although Netscape limits its cookie names to non-whitespace
alphanumeric characters, CGI.pm removes this restriction by escaping
and unescaping cookies behind the scenes.<p>
<dt><strong>-value</strong>
<dd>The value of the cookie. This can be any scalar value,
array reference, or even associative array reference. For example,
you can store an entire associative array into a cookie this way:
<pre>
$cookie=$query->cookie(-name=>'family information',
-value=>\%childrens_ages);
</pre>
<dt><strong>-path</strong>
<dd>The optional partial path for which this cookie will be valid, as described
above.<p>
<dt><strong>-domain</strong>
<dd>The optional partial domain for which this cookie will be valid, as described
above.
<dt><strong>-expires</strong>
<dd>The optional expiration date for this cookie. The format is as described
in the section on the <strong>header()</strong> method:
<pre>
"+1h" one hour from now
</pre>
<dt><strong>-secure</strong>
<dd>If set to true, this cookie will only be used within a secure
SSL session.
</dl>
The cookie created by <strong>cookie()</strong> must be incorporated into the HTTP
header within the string returned by the <a href="#header">header()</a> method:
<pre>
print $query->header(-cookie=>$my_cookie);
</pre>
To create multiple cookies, give header() an array reference:
<pre>
$cookie1 = $query->cookie(-name=>'riddle_name',
-value=>"The Sphynx's Question");
$cookie2 = $query->cookie(-name=>'answers',
-value=>\%answers);
print $query->header(-cookie=>[$cookie1,$cookie2]);
</pre>
To retrieve a cookie, request it by name by calling cookie()
method without the <strong>-value</strong> parameter:
<pre>
use CGI;
$query = new CGI;
%answers = $query->cookie('answers');
# $query->cookie(-name=>'answers') works too!
</pre>
To retrieve the names of all cookies passed to your script, call
<strong>cookie()</strong> without any parameters. This allows you to
iterate through all cookies:
<pre>
foreach $name ($query->cookie()) {
print $query->cookie($name);
}
</pre>
<p>
The cookie and CGI namespaces are separate. If you have a parameter
named 'answers' and a cookie named 'answers', the values retrieved by
param() and cookie() are independent of each other. However, it's
simple to turn a CGI parameter into a cookie, and vice-versa:
<pre>
# turn a CGI parameter into a cookie
$c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
# vice-versa
$q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
</pre>
<p>
See the <a href="./examples/cookie.cgi">cookie.cgi</a> example script
for some ideas on how to use cookies effectively.
<p>
<strong>NOTE:</strong> There are some limitations on cookies. Here is
what RFC2109, section 6.3, states:
<pre>
Practical user agent implementations have limits on the number and
size of cookies that they can store. In general, user agents' cookie
support should have no fixed limits. They should strive to store as
many frequently-used cookies as possible. Furthermore, general-use
user agents should provide each of the following minimum capabilities
individually, although not necessarily simultaneously:
* at least 300 cookies
* at least 4096 bytes per cookie (as measured by the size of the
characters that comprise the cookie non-terminal in the syntax
description of the Set-Cookie header)
* at least 20 cookies per unique host or domain name
User agents created for specific purposes or for limited-capacity
devices should provide at least 20 cookies of 4096 bytes, to ensure
that the user can interact with a session-based origin server.
The information in a Set-Cookie response header must be retained in
its entirety. If for some reason there is inadequate space to store
the cookie, it must be discarded, not truncated.
Applications should use as few and as small cookies as possible, and
they should cope gracefully with the loss of a cookie.
</pre>
Unfortunately, some browsers appear to have limits that are more
restrictive than those given in the RFC. If you need to store a lot
of information, it's probably better to create a unique session ID,
store it in a cookie, and use the session ID to locate an external
file/database saved on the server's side of the connection.
<p>
<A HREF="#contents">Table of contents</A>
<HR>
<H2><A NAME="frames">Support for Frames</A></H2>
CGI.pm contains support for <a
href="http://home.netscape.com/assist/net_sites/frames.html">HTML
frames</a>, a feature of Netscape 2.0 and higher, and Internet
Explorer 3.0 and higher. Frames are supported in two ways:
<ol>
<li> You can provide the name of a new or preexisting frame in the startform()
and start_multipart_form() methods using the <code>-target</code>
parameter. When the form is submitted, the output
will be redirected to the indicated frame:
<pre>
print $query->start_form(-target=>'result_frame');
</pre>
<li> You can direct the output of a script into a new window or into a
preexisting named frame by providing the name of the frame as a
<code>-target</code> argument in the header method. For example,
the following code will pop up a new window and display the script's
output:
<pre>
$query = new CGI;
print $query->header(-target=>'_blank');
</pre>
This feature is a non-standard extension to HTTP which is supported
by Netscape browsers, but <b>not by Internet Explorer</b>.
</ol>
Using frames effectively can be tricky. To create a proper frameset in which
the query and response are displayed side-by-side requires you to
divide the script into three functional sections. The first section should
create the <frameset> declaration and exit. The second section is
responsible for creating the query form and directing it into the one
frame. The third section is responsible for creating the response and directing
it into a different frame.
<p>
<a href="examples/">The examples directory</a> contains a script called
<a href="examples/popup.cgi">popup.cgi</a> that demonstrates a simple
popup window. <a href="examples/frameset.cgi">frameset.cgi</a> provides
a skeleton script for creating side-by-side query/result frame sets.
<HR>
<H2><A NAME="javascripting">Support for JavaScript</A></H2>
Netscape versions 2.0 and higher incorporate an interpreted language
called JavaScript. Internet Explorer, 3.0 and higher, supports a
closely-related dialect called JScript. JavaScript isn't the same as
Java, and certainly isn't at all the same as Perl, which is a great
pity. JavaScript allows you to programatically change the contents of
fill-out forms, create new windows, and pop up dialog box from within
Netscape itself. From the point of view of CGI scripting, JavaScript
is quite useful for validating fill-out forms prior to submitting
them.
<p>
You'll need to know JavaScript in order to use it. The
<a href="http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/">
Netscape JavaScript manual</a> contains
a good tutorial and reference guide to the JavaScript programming
language.
<p>
The usual way to use JavaScript is to define a set of functions in
a <SCRIPT> block inside the HTML header and then to register
event handlers in the various
elements of the page. Events include such things as the mouse passing
over a form element, a button being clicked, the contents of a text
field changing, or a form being submitted. When an event occurs
that involves an element that has registered an event handler, its
associated JavaScript code gets called.
<p>
The elements that can register event handlers include the <BODY>
of an HTML document, hypertext links, all the various elements of a
fill-out form, and the form itself. There are a large number of
events, and each applies only to the elements for which it is
relevant. Here is a partial list:
<dl>
<dt><b>onLoad</b>
<dd>The browser is loading the current document. Valid in:
<ul>
<li>The HTML <BODY> section only.
</ul>
<dt><b>onUnload</b>
<dd>The browser is closing the current page or frame. Valid for:
<ul>
<li>The HTML <BODY> section only.
</ul>
<dt><b>onSubmit</b>
<dd>The user has pressed the submit button of a form. This event
happens just before the form is submitted, and your function
can return a value of <em>false</em> in order to abort the
submission. Valid for:
<ul>
<li>Forms only.
</ul>
<dt><b>onClick</b>
<dd>The mouse has clicked on an item in a fill-out form.
Valid for:
<ul>
<li>Buttons (including submit, reset, and image buttons)
<li>Checkboxes
<li>Radio buttons
</ul>
<dt><b>onChange</b>
<dd>The user has changed the contents of a field.
Valid for:
<ul>
<li>Text fields
<li>Text areas
<li>Password fields
<li>File fields
<li>Popup Menus
<li>Scrolling lists
</ul>
<dt><b>onFocus</b>
<dd>The user has selected a field to work with. Valid for:
<ul>
<li>Text fields
<li>Text areas
<li>Password fields
<li>File fields
<li>Popup Menus
<li>Scrolling lists
</ul>
<dt><b>onBlur</b>
<dd>The user has deselected a field (gone to work somewhere
else). Valid for:
<ul>
<li>Text fields
<li>Text areas
<li>Password fields
<li>File fields
<li>Popup Menus
<li>Scrolling lists
</ul>
<dt><b>onSelect</b>
<dd>The user has changed the part of a text field that is
selected. Valid for:
<ul>
<li>Text fields
<li>Text areas
<li>Password fields
<li>File fields
</ul>
<dt><b>onMouseOver</b>
<dd>The mouse has moved over an element.
<ul>
<li>Text fields
<li>Text areas
<li>Password fields
<li>File fields
<li>Popup Menus
<li>Scrolling lists
</ul>
<dt><b>onMouseOut</b>
<dd>The mouse has moved off an element.
<ul>
<li>Text fields
<li>Text areas
<li>Password fields
<li>File fields
<li>Popup Menus
<li>Scrolling lists
</ul>
</dl>
In order to register a JavaScript event handler with an HTML element,
just use the event name as a parameter when you call the
corresponding CGI method. For example, to have your
<code>validateAge()</code> JavaScript code executed every time the
textfield named "age" changes, generate the field like this:
<pre>
print $q->textfield(-name=>'age',-onChange=>"validateAge(this)");
</pre>
This example assumes that you've already declared the
<code>validateAge()</code> function by incorporating it into
a <SCRIPT> block. The CGI.pm
<a href="#html">start_html()</a> method provides a convenient way
to create this section.
<p>
Similarly, you can create a form that checks itself over for
consistency and alerts the user if some essential value is missing by
creating it this way:
<pre>
print $q->startform(-onSubmit=>"validateMe(this)");
</pre>
See the <a href="examples/javascript.cgi">javascript.cgi</a> script for a
demonstration of how this all works.
<p>
The JavaScript "standard" is still evolving, which means that new
handlers may be added in the future, or may be present in some
browsers and not in others. You do not need to wait for a new version
of CGI.pm to use new event handlers. Just like any other tag
attribute they will produce syntactically correct HTML. For instance,
if Microsoft invents a new event handler called
<strong>onInterplanetaryDisaster</strong>, you can install a handler for it with:
<blockquote><pre>
print button(-name=>'bail out',-onInterPlaneteryDisaster=>"alert('uh oh')");
</pre></blockquote>
<a href="#contents">Table of contents</a>
<hr>
<h2><a name="stylesheets">Limited Support for Cascading Style Sheets</a></h2>
<p>
CGI.pm has limited support for HTML3's cascading style sheets (css).
To incorporate a stylesheet into your document, pass the
<strong>start_html()</strong> method a <strong>-style</strong>
parameter. The value of this parameter may be a scalar, in which case
it is incorporated directly into a <STYLE> section, or it may be
a hash reference. In the latter case you should provide the hash with
one or more of <strong>-src</strong> or <strong>-code</strong>.
<strong>-src</strong> points to a URL where an externally-defined
stylesheet can be found. <strong>-code</strong> points to a scalar
value to be incorporated into a <STYLE> section. Style
definitions in <strong>-code</strong> override similarly-named ones in
<strong>-src</strong>, hence the name "cascading."
<p>
You may also specify the MIME type of the stylesheet by including an
optional <strong>-type</strong> parameter in the hash pointed to by
<strong>-style</strong>. If not specified, the type defaults to
'text/css'.
<p>
To refer to a style within the body of your document, add the
<strong>-class</strong> parameter to any HTML element:
<blockquote><pre>
print h1({-class=>'Fancy'},'Welcome to the Party');
</pre></blockquote>
Or define styles on the fly with the <strong>-style</strong> parameter:
<blockquote><pre>
print h1({-style=>'Color: red;'},'Welcome to Hell');
</pre></blockquote>
You may also use the new <strong>span()</strong> element to apply a
style to a section of text:
<blockquote><pre>
print span({-style=>'Color: red;'},
h1('Welcome to Hell'),
"Where did that handbasket get to?"
);
</pre></blockquote>
Note that you must import the ":html3" definitions to get the
<strong>span()</strong> and <strong>style()</strong> methods.
<p>
You won't be able to do much with this unless you understand the CSS
specification. A more intuitive subclassable library for cascading
style sheets in Perl is in the works, but until then, please
read the CSS specification at <a
href="http://www.w3.org/pub/WWW/Style/">http://www.w3.org/pub/WWW/Style/</a>
to find out how to use these features. Here's a final example to get
you started.
<blockquote><pre>
use CGI qw/:standard :html3/;
#here's a stylesheet incorporated directly into the page
$newStyle=<<END;
<!--
P.Tip {
margin-right: 50pt;
margin-left: 50pt;
color: red;
}
P.Alert {
font-size: 30pt;
font-family: sans-serif;
color: red;
}
-->
END
print header();
print start_html( -title=>'CGI with Style',
-style=>{-src=>'http://www.capricorn.com/style/st1.css',
-code=>$newStyle}
);
print h1('CGI with Style'),
p({-class=>'Tip'},
"Better read the cascading style sheet spec before playing with this!"
),
span({-style=>'color: magenta'},"Look Mom, no hands!",
p(),
"Whooo wee!"
);
print end_html;
</pre></blockquote>
<p>
Pass an array reference to <B>-code</B> or <b>-src</b>in order to
incorporate multiple stylesheets into your document.
<p>
Should you wish to incorporate a verbatim stylesheet that includes
arbitrary formatting in the header, you may pass a -verbatim tag to
the -style hash, as follows:
<pre><blockquote>
print $q->start_html (-STYLE => {-verbatim => '@import
url("/server-common/css/'.$cssFile.'");',
-src => '/server-common/css/core.css'});
</blockquote></pre>
<p>
This will generate HTML like this:
<pre><blockquote>
<link rel="stylesheet" type="text/css"
href="/server-common/css/core.css">
<style type="text/css">
@import url("/server-common/css/main.css");
</style>
</blockquote></pre>
<p>
Any additional arguments passed in the -style value will be
incorporated into the <link> tag. For example:
<pre><blockquote>
start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
-media => 'all'});
</blockquote></pre>
This will give:
<blockquote><pre>
<link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
<link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
</pre></blockquote>
<p>
To make more complicated <link> tags, use the Link() function
and pass it to start_html() in the -head argument, as in:
<blockquote><pre>
@h = (Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/ss.css',-media=>'all'}),
Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/fred.css',-media=>'paper'}));
print start_html({-head=>\@h})
</pre></blockquote>
<a href="#contents">Table of contents</a>
<hr>
<H2><A NAME="nph">Using NPH Scripts</A></H2>
NPH, or "no-parsed-header", scripts bypass the server completely by
sending the complete HTTP header directly to the browser. This has
slight performance benefits, but is of most use for taking advantage
of HTTP extensions that are not directly supported by your server,
such as server push and PICS headers.
<p>
Servers use a variety of conventions for designating CGI scripts as
NPH. IIS and many Unix servers look at the beginning of the script's
name for the prefix "nph-".
<p>
CGI.pm supports NPH scripts with a special NPH mode. When in this
mode, CGI.pm will output the necessary extra header information when
the <code>header()</code> and <code>redirect()</code> methods are
called.
<p>
<strong>Important:</strong> If you use the Microsoft Internet
Information Server, you <em>must</em> designate your script as an NPH
script. Otherwise many of CGI.pm's features, such as redirection and
the ability to output non-HTML files, will fail. However, after
applying Service Pack 6, NPH scripts <em>do not work at all</em> on
IIS without a special patch from Microsoft. See <a
href="http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP">Knowledgebase
article Q280/3/31 Non-Parsed Headers Stripped From CGI Applications
That Have nph- Prefix in Name</a>
<p>
There are a number of ways to put CGI.pm into NPH mode:
<dl>
<dt>In the <strong>use</strong> statement:
<dd>Simply add "-nph" to the list of symbols to be imported into
your script:
<blockquote><pre>
use CGI qw(:standard -nph)
</pre></blockquote>
<p>
<dt>By calling the <strong>nph()</strong> method:
<dd>Call <strong>nph()</strong> with a non-zero parameter at any
point after using CGI.pm in your program.
<blockquote><pre>
CGI->nph(1)
</pre>
</blockquote>
<p>
<dt>By using <strong>-nph</strong> parameters in the
<strong>header()</strong> and <strong>redirect()</strong>
statements:
<dd>
<blockquote><pre>
print $q->header(-nph=>1);
</pre></blockquote>
</dl>
<hr>
<H2><A NAME="advanced">Advanced Techniques</A></H2>
<H3>A Script that Saves Some Information to a File and Restores It</H3>
This script will save its state to a file of the user's choosing when the
"save" button is pressed, and will restore its state when the "restore" button
is pressed. Notice that <EM>it's very important to check the file name</EM>
for shell metacharacters so that the script doesn't inadvertently open up a
command or overwrite someone's file. For this to work, the script's current
directory must be writable by "nobody".
<PRE>
#!/usr/local/bin/perl
use CGI;
$query = new CGI;
print $query->header;
print $query->start_html("Save and Restore Example");
print "<H1>Save and Restore Example</H1>\n";
# Here's where we take action on the previous request
&save_parameters($query) if $query->param('action') eq 'save';
$query = &restore_parameters($query) if $query->param('action') eq 'restore';
# Here's where we create the form
print $query->startform;
print "Popup 1: ",$query->popup_menu('popup1',['eenie','meenie','minie']),"\n";
print "Popup 2: ",$query->popup_menu('popup2',['et','lux','perpetua']),"\n";
print "<P>";
print "Save/restore state from file: ",$query->textfield('savefile','state.sav'),"\n";
print "<P>";
print $query->submit('action','save'),$query->submit('action','restore');
print $query->submit('action','usual query');
print $query->endform;
# Here we print out a bit at the end
print $query->end_html;
sub save_parameters {
local($query) = @_;
local($filename) = &clean_name($query->param('savefile'));
if (open(FILE,">$filename")) {
$query->save(\*FILE);
close FILE;
print "<STRONG>State has been saved to file $filename</STRONG>\n";
} else {
print "<STRONG>Error:</STRONG> couldn't write to file $filename: $!\n";
}
}
sub restore_parameters {
local($query) = @_;
local($filename) = &clean_name($query->param('savefile'));
if (open(FILE,$filename)) {
$query = new CGI(\*FILE); # Throw out the old query, replace it with a new one
close FILE;
print "<STRONG>State has been restored from file $filename</STRONG>\n";
} else {
print "<STRONG>Error:</STRONG> couldn't restore file $filename: $!\n";
}
return $query;
}
# Very important subroutine -- get rid of all the naughty
# metacharacters from the file name. If there are, we
# complain bitterly and die.
sub clean_name {
local($name) = @_;
unless ($name=~/^[\w\._-]+$/) {
print "<STRONG>$name has naughty characters. Only ";
print "alphanumerics are allowed. You can't use absolute names.</STRONG>";
die "Attempt to use naughty characters";
}
return $name;
}
</PRE>
If you use the CGI save() and restore() methods a lot, you might be
interested in the <cite>Boulderio</cite>
file format. It's a way of transferring semi-strucured data from the
standard output of one program to the standard input of the next. It
comes with a simple Perl database that allows you to store and
retrieve records from a DBM or DB_File database, and is compatible
with the format used by save() and restore(). You can get more
information on Boulderio from:
<blockquote><pre>
<a href="http://stein.cshl.org/software/boulder/">http://stein.cshl.org/software/boulder/</a>
</pre></blockquote>
<H3>A Script that Uses Self-Referencing URLs to Jump to Internal Links</H3>
(Without losing form information).
<P>Many people have experienced problems with internal links on pages that have
forms. Jumping around within the document causes the state of the form to be
reset. A partial solution is to use the self_url() method to generate a link
that preserves state information. This script illustrates how this works.
<PRE>
#!/usr/local/bin/perl
use CGI;
$query = new CGI;
# We generate a regular HTML file containing a very long list
# and a popup menu that does nothing except to show that we
# don't lose the state information.
print $query->header;
print $query->start_html("Internal Links Example");
print "<H1>Internal Links Example</H1>\n";
print "<A NAME=\"start\"></A>\n"; # an anchor point at the top
# pick a default starting value;
$query->param('amenu','FOO1') unless $query->param('amenu');
print $query->startform;
print $query->popup_menu('amenu',[('FOO1'..'FOO9')]);
print $query->submit,$query->endform;
# We create a long boring list for the purposes of illustration.
$myself = $query->self_url;
print "<OL>\n";
for (1..100) {
print qq{<LI>List item #$_<A HREF="$myself#start">Jump to top</A>\n};
}
print "</OL>\n";
print $query->end_html;
</PRE>
<H3>Multiple forms on the same page</H3>
There's no particular trick to this. Just remember to close one form before
you open another one. You can reuse the same query object or create a new one.
Either technique works.
<P>
There is, however, a problem with maintaining the states of multiple forms. Because
the browser only sends your script the parameters from the form in which the submit
button was pressed, the state of all the other forms will be lost. One way to get
around this, suggested in this example, is to use hidden fields to pass as much
information as possible regardless of which form the user submits.
<PRE>
#!/usr/local/bin/perl
use CGI;
$query=new CGI;
print $query->header;
print $query->start_html('Multiple forms');
print "<H1>Multiple forms</H1>\n";
# form 1
print "<HR>\n";
print $query->startform;
print $query->textfield('text1'),$query->submit('submit1');
print $query->hidden('text2'); # pass information from the other form
print $query->endform;
print "<HR>\n";
# form 2
print $query->startform;
print $query->textfield('text2'),$query->submit('submit2');
print $query->hidden('text1'); # pass information from the other form
print $query->endform;
print "<HR>\n";
print $query->end_html;
</PRE>
<p>
<A HREF="#contents">Table of contents</A>
<HR>
<h2><a name="subclassing">Subclassing CGI.pm</a></h2>
CGI.pm uses various tricks to work in both an object-oriented and
function-oriented fashion. It uses even more tricks to load quickly,
despite the fact that it is a humungous module. These tricks may get
in your way when you attempt to subclass CGI.pm.
<p>
If you use standard subclassing techniques and restrict yourself to
using CGI.pm and its subclasses in the object-oriented manner, you'll
have no problems. However, if you wish to use the function-oriented
calls with your subclass, follow this model:
<blockquote><pre>
package MySubclass;
use vars qw(@ISA $VERSION);
require CGI;
@ISA = qw(CGI);
$VERSION = 1.0;
$CGI::DefaultClass = __PACKAGE__;
$AutoloadClass = 'CGI';
sub new {
....
}
1;
</pre></blockquote>
The first special trick is to set the CGI package variable
$CGI::DefaultClass to the name of the module you are defining. If you
are using perl 5.004 or higher, you can use the special token
"__PACKAGE__" to retrieve the name of the current module. Otherwise,
just hard code the name of the module. This variable tells CGI what
type of default object to create when called in the function-oriented
manner.
<p>
The second trick is to set the package variable $AutoloadClass to the
string "CGI". This tells the CGI autoloader where to look for
functions that are not defined. If you wish to override CGI's
autoloader, set this to the name of your own package.
<p>
More information on extending CGI.pm can be found in my new book,
<cite>The Official Guide to CGI.pm</cite>, which was published by John
Wiley & Sons in April 1998. Check out the book's <a
href="http://www.wiley.com/compbooks/stein/">Web site</a>, which
contains multiple useful coding examples.
<p>
<A HREF="#contents">Table of contents</A>
<HR>
<h2><a name="mod_perl">Using CGI.pm with mod_perl and FastCGI</a></h2>
<h3>FastCGI</h3>
<a href="http://www.fastcgi.com">FastCGI</a> is a protocol invented by
OpenMarket that markedly speeds up CGI scripts under certain
circumstances. It works by opening up the script at server startup
time and redirecting the script's IO to a Unix domain socket. Every
time a new CGI request comes in, the script is passed new parameters
to work on. This allows the script to perform all its time-consuming
operations at initialization time (including loading CGI.pm!) and then
respond quickly to new requests.
<p>
FastCGI modules are available for the Apache and NCSA servers as well
as for OpenMarket's own server. In order to use FastCGI with Perl you
have to run a specially-modified version of the Perl interpreter.
Precompiled Binaries and a patch kit are all available on OpenMarket's
FastCGI web site.
<p>
To use FastCGI with CGI.pm, change your scripts as follows:
<h4>Old Script</h4>
<blockquote><pre>
#!/usr/local/bin/perl
use CGI qw(:standard);
print header,
start_html("CGI Script"),
h1("CGI Script"),
"Not much to see here",
hr,
address(a({href=>'/'},"home page"),
end_html;
</pre></blockquote>
<h4>New Script</h4>
<blockquote><pre>
#!/usr/local/fcgi/bin/perl
use CGI::Fast qw(:standard);
# Do time-consuming initialization up here.
while (new CGI::Fast) {
print header,
start_html("CGI Script"),
h1("CGI Script"),
"Not much to see here",
hr,
address(a({href=>'/'},"home page"),
end_html;
}
</pre></blockquote>
That's all there is to it. The param() method, form-generation, HTML
shortcuts, etc., all work the way you expect.
<h3>mod_perl</h3>
<a href="http://www.perl.com/CPAN/modules/Apache/">mod_perl</a> is a
module for the Apache Web server that embeds a Perl interpreter into
the Web server. It can be run in either of two modes:
<ol>
<li>Server launches a new Perl interpreter every time it needs to
interpret a Perl script. This speeds CGI scripts significantly
because there's no overhead for launching a new Perl process.
<li>A "fast" mode in which the server launches your script at
initialization time. You can
load all your favorite modules (like CGI.pm!) at initialization time,
greatly speeding things up.
</ol>
CGI.pm works with mod_perl, versions 0.95 and higher. If you use Perl
5.003_93 or higher, your scripts should run without any modifications.
Users with earlier versions of Perl should use the
<cite>CGI::Apache</cite> module instead. This example shows the
change needed:
<h4>Old Script</H4>
<blockquote><pre>
#!/usr/local/bin/perl
use CGI qw(:standard);
print header,
start_html("CGI Script"),
h1("CGI Script"),
"Not much to see here",
hr,
address(a({href=>'/'},"home page"),
end_html;
</pre></blockquote>
<h4>New Script</h4>
<blockquote><pre>
#!/usr/bin/perl
use CGI::Apache qw(:standard);
print header,
start_html("CGI Script"),
h1("CGI Script"),
"Not much to see here",
hr,
address(a({href=>'/'},"home page"),
end_html;
}
</pre></blockquote>
<strong>Configuration note:</strong> When using CGI.pm with mod_perl
it is <strong>not</strong> necessary to enable the
<tt>PerlSendHeader</tt> directive. This is handled automatically by
CGI.pm and by Apache::Registry.
<p>
mod_perl comes with a small wrapper library named
<cite>CGI::Switch</cite> that selects dynamically between using CGI
and CGI::Apache. This library is no longer needed. However users of
CGI::Switch can continue to use it without risk. Note that the
"simple" interface to the CGI.pm functions does not work with
CGI::Switch. You'll have to use the object-oriented versions (or use
the sfio version of Perl!)
<p>
If you use CGI.pm in many of your mod_perl scripts, you may want to
preload CGI.pm and its methods at server startup time. To do this,
add the following line to httpd.conf:
<blockquote><pre>
PerlScript /home/httpd/conf/startup.pl
</pre></blockquote>
Create the file /home/httpd/conf/startup.pl and put in it all the
modules you want to load. Include CGI.pm among them and call its <a
href="#compile">compile()</a> method to precompile its autoloaded
methods.
<blockquote><pre>
#!/usr/local/bin/perl
use CGI ();
CGI->compile(':all');
</pre></blockquote>
Change the path to the startup script according to your preferences.
<p>
<A HREF="#contents">Table of contents</A>
<HR>
<H2><a name="migrating">Migrating from cgi-lib.pl</a></H2>
To make it easier to convert older scripts that use cgi-lib.pl,
CGI.pm provides a <strong>CGI::ReadParse()</strong> call that
is compatible with cgi-lib.pl's <strong>ReadParse()</strong>
subroutine.
<p>
When you call ReadParse(), CGI.pm creates an associative array named
<code>%in</code> that contains the named CGI parameters. Multi-valued
parameters are separated by "\0" characters in exactly the same way
cgi-lib.pl does it. The function result is the number of parameters
parsed. You can use this to determine whether the script is being
called from a fill out form or not.
<p>
To port an old script to CGI.pm, you have to make just two changes:
<h4>Old Script</h4>
<pre>
require "cgi-lib.pl";
ReadParse();
print "The price of your purchase is $in{price}.\n";
</pre>
<h4>New Script</h4>
<pre>
use CGI qw(:cgi-lib);
ReadParse();
print "The price of your purchase is $in{price}.\n";
</pre>
Like cgi-lib's ReadParse, pass a variable <em>glob</em> in
order to use a different variable than the default "%in":
<pre>
ReadParse(*Q);
@partners = split("\0",$Q{'golf_partners'});
</pre>
<p>
The associative array created by CGI::ReadParse() contains
a special key 'CGI', which returns the CGI query object
itself:
<pre>
ReadParse();
$q = $in{CGI};
print $q->textfield(-name=>'wow',
-value=>'does this really work?');
</pre>
<p>
This allows you to add the more interesting features
of CGI.pm to your old scripts without rewriting them completely.
As an added benefit, the <strong>%in</strong> variable is
actually <code>tie()</code>'d to the CGI object. Changing the
CGI object using <strong>param()</strong> will dynamically
change <strong>%in</strong>, and vice-versa.
<p>
cgi-lib.pl's <code>@in</code> and <code>$in</code> variables are
<strong>not</strong> supported. In addition, the extended version of
ReadParse() that allows you to spool uploaded files to disk is not
available. You are strongly encouraged to use CGI.pm's file upload
interface instead.
<p>
See <a href="cgi-lib_porting.html">cgi-lib_porting.html</a> for more
details on porting cgi-lib.pl scripts to CGI.pm.
<HR>
<H2>
<A NAME="upload_caveats">
Using the File Upload Feature
</A>
</H2>
The file upload feature doesn't work with every combination of browser
and server. The various versions of Netscape and Internet Explorer on
the Macintosh, Unix and Windows platforms don't all seem to implement
file uploading in exactly the same way. I've tried to make CGI.pm
work with all versions on all platforms, but I keep getting reports
from people of instances that break the file upload feature.
<p>
Known problems include:
<ol>
<li>Large file uploads may fail when using SSL version 2.0. This
affects the Netscape servers and possibly others that use the SSL
library. I have received reports that WebSite Pro suffers from
this problem. This is a documented bug in the
Netscape implementation of SSL and not a problem with CGI.pm.
<li>If you try to upload a <strong>directory</strong> path with Unix
Netscape, the browser will hang until you hit the "stop" button.
I haven't tried to figure this one out since I think it's dumb
of Netscape to allow this to happen at all.
<li>If you create the CGI object in one package (e.g. "main") and
then obtain the filehandle in a different package (e.g. "foo"),
the filehandle will be accessible through "main" but not "foo".
In order to use the filehandle, try the following contortion:
<blockquote><pre>
$file = $query->param('file to upload');
$file = "main::$file";
...
</pre></blockquote>
I haven't found a way to determine the correct caller in this
situation. I might add a readFile() method to CGI if this
problem bothers enough people.
</ol>
The main technical challenge of handling file uploads is that
it potentially involves sending more data to the CGI script
than the script can hold in main memory. For this reason
CGI.pm creates temporary files in
either the <CODE>/usr/tmp</CODE> or the <CODE>/tmp</CODE>
directory. These temporary files
have names like <CODE>CGItemp125421</CODE>, and should be
deleted automatically.
<P>
<H3>Frequent Problems</H3>
<h4>When you run a script from the command line, it says "offline
mode: enter name=value pairs on standard input". What do I do
now?</h4>
This is a prompt to enter some CGI parameters for the purposes of
debugging. You can now type in some parameters like this:
<pre>
first_name=Fred
last_name=Flintstone
city=Bedrock
</pre>
End the list by typing a control-D (or control-Z on DOS/Windows
systems).
<p>
If you want to run a CGI script from a script or batch file, and don't
want this behavior, just pass it an empty parameter list like this:
<pre>
my_script.pl ''
</pre>
This will work too on Unix systems:
<pre>
my_script.pl </dev/null
</pre>
Another option is to use the "-no_debug" pragma when you "use"
CGI.pm. This will suppress command-line debugging completely:
<pre>
use CGI qw/:standard -no_debug/;
</pre>
<h4>CGI.pm breaks when you use "use integer"</h4>
<p>
Due to problems that integer.pm has with unary negation, calls to
CGI.pm that use the -arg=>value format will break if you load the
integer.pm module. This is fixed in Perl 5.005_61 and up.
<p>
A workaround is to put all arguments in quotes:
'-arg'=>'value'
<H4>You can't retrieve the name of the uploaded file
using the param() method</H4>
Most likely the remote user isn't using version 2.0 (or higher)
of Netscape. Alternatively she just isn't filling in the form
completely.
<h4>When you accidentally try to upload a directory name,
the browser hangs</h4>
This seems to be a Netscape browser problem. It starts to
upload junk to the script, then hangs. You can abort by
hitting the "stop" button.
<H4>You can read the name of the uploaded file, but can't
retrieve the data</H4>
First check that you've told CGI.pm to
use the new <A HREF="#multipart">multipart/form-data</A>
scheme. If it still isn't working, there may be a problem
with the temporary files that CGI.pm needs to create in
order to read in the (potentially very large) uploaded files.
Internally, CGI.pm tries to create temporary files with
names similar to <CODE>CGITemp123456</CODE> in a temporary
directory. To find a suitable directory it first looks
for <CODE>/usr/tmp</CODE> and then for <CODE>/tmp</CODE>.
If it can't find either of these directories, it tries
for the current directory, which is usually the same
directory that the script resides in.
<P>
If you're on a non-Unix system you may need to modify CGI.pm to point
at a suitable temporary directory. This directory must be writable by
the user ID under which the server runs (usually "nobody") and must
have sufficient capacity to handle large file uploads. Open up
CGI.pm, and find the line:
<PRE>
package TempFile;
foreach ('/usr/tmp','/tmp') {
do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
}
</PRE>
Modify the foreach() line to contain a series of one or more
directories to store temporary files in.
<p>
Alternatively, you can just skip the search entirely and force CGI.pm
to store its temporary files in some logical location. Do this at the
top of your script with a line like this one:
$TempFile::TMPDIRECTORY='/WWW_ROOT';
<h4>On Windows Systems, the temporary file is never deleted, but hangs
around in <code>\temp</code>, taking up space.</h4>
Be sure to close the filehandle before your program exits. In fact,
close the file as soon as you're finished with it, because the file
will end up hanging around if the script later crashes.
<p>
Unix users don't have this problem, because well designed operating
systems make it possible to delete a file without closing it.
<h4>When you press the "back" button, the same page is loaded,
not the previous one.</h4>
Netscape 2.0's history list gets confused when processing multipart
forms. If the script generates different pages for the form and the
results, hitting the "back" button doesn't always return you to the
previous page; instead Netscape reloads the current page. This happens
even if you don't use an upload file field in your form.
<p>
A workaround for this is to use additional path information to trick
Netscape into thinking that the form and the response have different
URLs. I recommend giving each form a sequence number and bumping the
sequence up by one each time the form is accessed:
<pre>
my($s) = $query->path_info=~/(\d+)/; # get sequence
$s++; #bump it up
# Trick Netscape into thinking it's loading a new script:
print $q->start_multipart_form(-action=>$q->script_name . "/$s");
</pre>
<h4>You can't find the temporary file that CGI.pm creates</h4>
You're encouraged to copy the data into your own file by reading from the
file handle that CGI.pm provides you with. In the future there
may be no temporary file at all, just a pipe. However, for now, if
you really want to get at the temp file, you can retrieve its path
using the <a href="#tmpfilename">tmpFileName()</a> method. Be sure
to move the temporary file elsewhere in the file system if you don't
want it to be automatically deleted when CGI.pm exits.
<HR>
<h2><a name="push">Server Push</a></h2>
<p> CGI.pm provides four simple functions for producing multipart
documents of the type needed to implement server push. To import
these into your namespace, you must import the ":push" set. You are
also advised to put the script into NPH mode and to set $| to 1 to
avoid buffering problems. </p>
<p>Here is a simple script that demonstrates server push:</p>
<blockquote><pre>
#!/usr/local/bin/perl
use CGI qw/:push -nph/;
$| = 1;
print multipart_init(-boundary=>'----------------here we go!');
foreach (0 .. 4) {
print multipart_start(-type=>'text/plain'),
"The current time is ",scalar(localtime),"\n";
if ($_ < 4) {
print multipart_end;
} else {
print multipart_final;
}
sleep 1;
}
</pre></blockquote>
<p> This script initializes server push by calling
<cite>multipart_init()</cite>. It then enters a loop in
which it begins a new multipart section by calling
<cite>multipart_start()</cite>, prints the current local time, and
ends a multipart section with <cite>multipart_end()</cite>. It then
sleeps a second, and begins again. On the final iteration, it ends the
multipart section with <cite>multipart_final()</cite> rather than with
<cite>multipart_end()</cite>. </p>
<dl>
<dt>multipart_init()
<dd>
<blockquote><pre>
multipart_init(-boundary=>$boundary);
</pre></blockquote>
Initialize the multipart system. The -boundary argument specifies
what MIME boundary string to use to separate parts of the document.
If not provided, CGI.pm chooses a reasonable boundary for you.
<p>
<dt>multipart_start()
<dd><blockquote><pre>
multipart_start(-type=>$type)
</pre></blockquote>
Start a new part of the multipart document using the specified MIME
type. If not specified, text/html is assumed.
<p>
<dt>multipart_end()
<dd><blockquote><pre>
multipart_end()
</pre></blockquote>
End a part. You must remember to call multipart_end() once for each
multipart_start(), except at the end of the last part of the multipart
document when multipart_final() should be called instead of
multipart_end().
<p>
<dt>multipart_final()
<dd><blockquote><pre>
multipart_final()
</pre></blockquote>
End all parts.
You should call multipart_final() rather than multipart_end() at the
end of the last part of the multipart document.
</dl>
Users interested in server push applications should also have a look
at the CGI::Push module.
<p>Only Netscape Navigator supports server push. Internet Explorer browsers
do not.</p>
<p>
<A HREF="#contents">Table of contents</A>
<HR>
<H2><a name="dos">Avoiding Denial of Service Attacks</a></H2>
A potential problem with CGI.pm is that, by default, it attempts to
process form POSTings no matter how large they are. A wily hacker
could attack your site by sending a CGI script a huge POST of many
megabytes. CGI.pm will attempt to read the entire POST into a
variable, growing hugely in size until it runs out of memory. While
the script attempts to allocate the memory the system may slow down
dramatically. This is a form of denial of service attack.
<p>
Another possible attack is for the remote user to force CGI.pm to
accept a huge file upload. CGI.pm will accept the upload and store it
in a temporary directory even if your script doesn't expect to receive
an uploaded file. CGI.pm will delete the file automatically when it
terminates, but in the meantime the remote user may have filled up the
server's disk space, causing problems for other programs.
<p>
The best way to avoid denial of service attacks is to limit the amount
of memory, CPU time and disk space that CGI scripts can use. Some Web
servers come with built-in facilities to accomplish this. In other
cases, you can use the shell <em>limit</em> or <em>ulimit</em>
commands to put ceilings on CGI resource usage.
<p>
CGI.pm also has some simple built-in protections against denial of
service attacks, but you must activate them before you can use them.
These take the form of two global variables in the CGI name space:
<dl>
<dt><strong><tt>$CGI::POST_MAX</tt></strong>
<dd>If set to a non-negative integer, this variable puts a ceiling
on the size of POSTings, in bytes. If CGI.pm detects a POST
that is greater than the ceiling, it will immediately exit with an error
message. This value will affect both ordinary POSTs and
multipart POSTs, meaning that it limits the maximum size of file
uploads as well. You should set this to a reasonably high
value, such as 1 megabyte.
<p>
<dt><strong><tt>$CGI::DISABLE_UPLOADS</tt></strong>
<dd>If set to a non-zero value, this will disable file uploads
completely. Other fill-out form values will work as usual.
</dl>
You can use these variables in either of two ways.
<ol>
<li>On a script-by-script basis. Set the variable at the top of the
script, right after the "use" statement:
<pre>
use CGI qw/:standard/;
use CGI::Carp 'fatalsToBrowser';
$CGI::POST_MAX=1024 * 100; # max 100K posts
$CGI::DISABLE_UPLOADS = 1; # no uploads
</pre>
<p>
<li>Globally for all scripts. Open up CGI.pm, find the definitions
for <tt>$POST_MAX</tt> and <tt>$DISABLE_UPLOADS</tt>, and set
them to the desired values. You'll find them towards the top of
the file in a subroutine named <tt>initialize_globals</tt>.
</ol>
Since an attempt to send a POST larger than <tt>$POST_MAX</tt> bytes
will cause a fatal error, you might want to use CGI::Carp to echo the
fatal error message to the browser window as shown in the example
above. Otherwise the remote user will see only a generic "Internal
Server" error message. See the manual page for CGI::Carp for more
details.
<p>
An attempt to send a POST larger than $POST_MAX bytes will cause
<b>param()</b> to return an empty CGI parameter list. You can test for
this event by checking <b>cgi_error()</b>, either after you create the CGI
object or, if you are using the function-oriented interface, call
<b>param()</b> for the first time. If the POST was intercepted, then
cgi_error() will return the message "413 POST too large".
<p>
This error message is actually defined by the HTTP protocol, and is
designed to be returned to the browser as the CGI script's status
code. For example:
<pre>
$uploaded_file = param('upload');
if (!$uploaded_file && cgi_error()) {
print header(-status=>cgi_error());
exit 0;
}
</pre>
<p>
Some browsers may not know what to do with this status code. It may
be better just to create an HTML page that warns the user of the
problem.
<A HREF="#contents">Table of contents</A>
<HR>
<H2><A NAME="non_unix">Using CGI.pm on non-Unix Platforms</A></H2>
I don't have access to all the combinations of hardware and software
that I really need to make sure that CGI.pm works consistently for all
Web servers, so I rely heavily on helpful reports from users like
yourself.
<p>
There are a number of differences in file name and text processing
conventions on different platforms. By default, CGI.pm is set up to
work properly on a Unix (or Linux) system. During load, it will
attempt to guess the correct operating system using the Config module.
Currently it guesses correctly; however if the operating system names
change it may not work right. The main symptom will be that file
upload does not work correctly. If this happens, find the place at
the top of the script where the OS is defined, and uncomment the
correct definition:
<pre>
# CHANGE THIS VARIABLE FOR YOUR OPERATING SYSTEM
# $OS = 'UNIX';
# $OS = 'MACINTOSH';
# $OS = 'WINDOWS';
# $OS = 'VMS';
</pre>
Other notes follow:
<H3><a name="windows">Windows NT</a></H3>
CGI.pm works well with WebSite, the EMWACS server, Purveyor and the
Microsoft IIS server. CGI.pm must be put in the perl5 library
directory, and all CGI scripts that use it should be placed in cgi-bin
directory. You also need to associate the <CODE>.pl</CODE> suffix
with perl5 using the NT file manager (Website, Purveyor), or install
the correct script mapping registry keys for IIS. Perl for Windows is
available from the ActiveState company, which can be found at:
<blockquote>
<a href="http://www.activestate.com/">http://www.activestate.com/</a>
</blockquote>
<p>
WebSite uses a slightly different cgi-bin directory structure than
the standard. For this server, place the scripts in the
<CODE>cgi-shl</CODE> directory. CGI.pm appears to work correctly
in both the Windows95 and WindowsNT versions of WebSite.
<p>
Old Netscape Communications Server technical notes recommended
placing <code>perl.exe</code> in cgi-bin. This a very bad idea because
it opens up a gaping security hole. Put a C <code>.exe</code> wrapper
around the perl script until such time as Netscape recognizes NT file
manager associations, or provides a Perl-compatible DLL library for its
servers.
<p>
If you find that binary files get slightly larger when uploaded but
that text files remain the same, then binary made is not correctly
activated. Be sure to set the $OS variable to 'NT' or 'WINDOWS'. If
you continue to have problems, make sure you're calling
<strong>binmode()</strong> on the filehandle that you use to write
the uploaded file to disk.
<H3>VMS</H3>
I don't have access to a VMS machine, and I'm not sure whether file upload
works correctly. Other features are known to work.
<H3>Macintosh</H3>
Most CGI.pm features work with MacPerl version 5.0.6r1 or higher under
the WebStar and MacHTTP servers. In order to install a Perl program
to use with the Web, you'll need Matthias Nuuracher's PCGI extension,
available at:
<blockquote><pre>
<a href="ftp://err.ethz.ch/pub/neeri/MacPerl/">ftp://err.ethz.ch/pub/neeri/MacPerl/</a>
</pre></blockquote>
Known incompatibilities between CGI.pm and MacPerl include:
<ol>
<li>The perl compiler will object to the use of -values in named
parameters. Put single quotes around this parameter ('-values')
or use the singular form ('-value') instead.
<li>File upload isn't working in my hands (Perl goes into an endless
loop). Other people have gotten it to work.
</ol>
<HR>
<H2><A NAME="future">The Relation of this Library to the CGI Modules</A></H2>
This library is maintained in parallel with the full featured CGI,
URL, and HTML modules. I use this library to test out new ideas
before incorporating them into the CGI hierarchy. I am continuing to
maintain and improve this library in order to satisfy people who are
looking for an easy-to-use introduction to the world of CGI scripting.
<p>
The CGI::* modules are being reworked to be interoperable with the
excellent LWP modules. Stay tuned.
<P>The current version of CGI.pm can be found at:
<PRE> <A HREF="http://www.genome.wi.mit.edu/ftp/pub/software/WWW">
http://www.genome.wi.mit.edu/ftp/pub/software/WWW/</A>
</PRE>
<P>
You are encouraged to look at these other Web-related modules:
<DL>
<DT> <A HREF="http://www.genome.wi.mit.edu/ftp/pub/software/WWW/CGIperl/">
CGI::Base,CGI::Form,CGI::MiniSrv,CGI::Request and CGI::URI::URL</A>
<DD> Modules for parsing script input, manipulating URLs, creating
forms and even launching a miniature Web server.
<DT> <A HREF="http://www.ics.uci.edu/pub/websoft/libwww-perl/">
libwww-perl</A>
<DD> Modules for fetching Web resources from within Perl, writing
Web robots, and much more.
</DL>
You might also be interested in two packages for creating graphics
on the fly:
<DL>
<DT> <A HREF="http://www.genome.wi.mit.edu/ftp/pub/software/WWW/GD.html">GD.html</A>
<DD> A module for creating GIF images on the fly, using Tom Boutell's
<A HREF="http://www.boutell.com/gd/">gd</A> graphics library.
<DT> <A HREF="http://www.genome.wi.mit.edu/ftp/pub/software/utilities/">qd.pl</A>
<DD> A library for creating Macintosh PICT files on the fly (which
can be converted to GIF or JPEG using NetPBM).
</DL>
<P>
For a collection of CGI scripts of various levels of complexity,
see the companion pages for my book
<A HREF="http://www.genome.wi.mit.edu/WWW/">How to Set Up and
Maintain a World Wide Web Site</A>
<HR> <H2><A NAME="distribution">Distribution Information:</A></H2>
This code is copyright 1995-1998 by Lincoln Stein. It may be used and
modified freely, but I do request that this copyright notice remain
attached to the file. You may modify this module as you wish, but if
you redistribute a modified version, please attach a note listing the
modifications you have made.
<HR>
<H2><A NAME="book">The CGI.pm Book</A></H2>
<cite>The Official Guide to CGI.pm</cite>, by Lincoln Stein, is packed
with tips and techniques for using the module, along with information
about the module's internals that can't be found anywhere else. It is
available on bookshelves now, or can be ordered from <a
href="http://www.amazon.com">amazon.com</a>. Also check the book's
companion Web site at:
<blockquote>
<a href="http://www.wiley.com/compbooks/stein/">http://www.wiley.com/compbooks/stein/</a>
</blockquote>
<HR>
<H2><A NAME="y2000">CGI.pm and the Year 2000 Problem</A></H2>
Versions of CGI.pm prior to 2.36 suffered a year 2000 problem in the
handling of cookies. Cookie expiration dates were expressed using two
digits as dictated by the then-current Netscape cookie protocol. The
cookie protocol has since been cleaned up. My belief is that versions
of CGI.pm 2.36 and higher are year 2000 compliant.
<HR>
<H2><A NAME="mailingList">The CGI-perl mailing list</A></H2>
The CGI Perl mailing list is defunct and is unlikely to be
resurrected. Please address your questions to <a
href="news:comp.infosystems.www.authoring.cgi">comp.infosystems.www.authoring.cgi</a>
if they relate to the CGI protocol or the usage of CGI.pm <i>per
gse</i>, or to <a href="news:comp.lang.perl.misc">comp.lang.perl.misc</a>
for Perl <STRONG>language</STRONG> issues. Please read this
documentation thoroughly, read the FAQs for these newsgroups and scan
through previous messages before you make a posting. Respondents are
not always friendly to people who neglect to do so!
<H2><a name="bugs">Bug Reports</a></H2>
Address bug reports and comments to:<BR> <A
HREF="mailto:lstein@cshl.org">lstein@cshl.org</A>. When sending bug
reports, please provide the following information:
<ul>
<li>the version of CGI.pm (<code>perl -MCGI -e 'print $CGI::VERSION'</code>)
<li>the version of Perl (<code>perl -v</code>)
<li>the name and version of your Web server
<li>the name and version of the operating system you are using
<li>if applicable, the name and version of the browser you are using
<li>a short test script that reproduces the problem (30 lines or less)
</ul>
It is very important that I receive this information in order to help
you.
<p>
<A HREF="#contents">Up to table of contents</A>
<HR>
<H2><A NAME="new">Revision History</A></H2>
<h3>Version 3.06</h3>
<ol>
<li>Fixed bare call to script() in start_html
<li>Moved Fh::DESTROY out of autoloaded functions so as to avoid clobbering
$@ when CGI functions are executed in an eval{} context.
<li>mod_perl 2.0 version detection patch in CGI::Cookie provided by
Allen Day.
<li>autoEscape() flag is now respected when generating extra attributes.
<li>Tests for *tag start/end generation from Shlomi Fish.
<li>Support for can() method provided by Ron Savage.
<li>Fix for lang='' when outputting XHTML.
</ol>
<h3>Version 3.05</h3>
<ol>
<li>Fixed uninitialized variable warning on start_form() when running from command line.
<li>Fixed CGI::_set_attributes so that attributes with a - are handled correctly.
<li>Fixed CGI::Carp::die() so as to avoid problems from _longmess() clobbering @_.
<li>If HTTP_X_FORWARDED_HOST is defined (i.e. running under a proxy), the
various functions that return HOST will use that instead.
<li>Fix for undefined utf8() call in CGI::Util.
<li>Changed the call to warningsToBrowser() in CGI::Carp::fatalsToBrowser to call only
after HTTP header is sent (thanks to Didier Lebrun for noticing).
<li>Patches from Dan Harkless to make CGI.pm validatable against HTML 3.2.
<li>Fixed an extraneous "foo=bar" appearing when extra style parameters passed to
start_html;
<li>Fixed cross-site scripting bug in startform() pointed out by Dan Harkless.
<li>Fixed documentation to discuss list context behavior of form-element generators
explicitly.
<li>Fixed incorrect results from end_form() when called in OO manner.
<li>Fixed query string stripping in order to handle URLs containing escaped newlines.
<li>During server push, set NPH to 0 rather than 1. This is supposed to fix problems
with Apache.
<li>Fixed incorrect processing of multipart form fields that contain embedded quotes.
There's still the issue of how to handle ones that contain embedded semicolons,
but no one has complained (yet).
<li>Fixed documentation bug in -style argument to start_html()
<li>Added -status argument to redirect().
</ol>
<h3>Version 3.04</h3>
<ol>
<li>Fixed the problem with mod_perl crashing when "defaults" button pressed.
</ol>
<h3>Version 3.03</h3>
<ol>
<li>Fix upload hook functionality
<li>Workaround for CGI->unescape_html()
<li>Bumped version numbers in CGI::Fast and CGI::Util for 5.8.3-tobe
</ol>
</h3>
<h3>Version 3.02</h3>
<ol>
<li>Bring in Apache::Response just in case.
<li>File upload on EBCDIC systems now works.
</ol>
<h3>Version 3.01</h3>
<ol>
<li>No fix yet for upload failures when running on EBCDIC server.
<li>Fixed uninitialized glob warnings that appeared when file uploading under perl 5.8.2.
<li>Added patch from Schlomi Fish to allow debugging of PATH_INFO from command line.
<li>Added patch from Steve Hay to correctly unlink tmp files under mod_perl/windows
<li>Added upload_hook functionality from Jamie LeTaul
<li>Workarounds for mod_perl 2 IO issues. Check that file upload and state saving still working.
<li>Added code for underreads.
<li>Fixed misleading description of redirect() and relative URLs in the POD docs.
<li>Workaround for weird interaction of CGI::Carp with Safe module reported by William McKee.
<li>Added patches from Ilmari Karonen to improve behavior of CGI::Carp.
<li>Fixed documentation error in -style argument.
<li>Added virtual_port() method for finding out what port server is listening on
in a virtual-host aware fashion.
</ol>
<h3>Version 3.00</h3>
<ol>
<li>Patch from Randal Schwartz to fix bug introduced by cross-site
scripting vulnerability "fix."
<li>Patch from JFreeman to replace UTF-8 escape constant of 0xfe with 0xfc.
Hope this is right!
</ol>
<h3>Version 2.99</h3>
<ol>
<li>Patch from Steve Hay to fix extra Content-type: appearing on browser
screen when FatalsToBrowser invoked.
<li>Patch from Ewann Corvellec to fix cross-site scripting vulnerability.
<li>Fixed tmpdir routine for file uploading to solve problem that occurs
under mod_perl when tmpdir is writable at startup time, but not at
session time.
</ol>
<h3>Version 2.98</h3>
<ol>
<li>Fixed crash in Dump() function.
</ol>
<h3>Version 2.97</h3>
<ol>
<li>Sigh. Uploaded wrong 2.96 to CPAN.
</ol>
<h3>Version 2.96</h3>
<ol>
<li>More bugfixes to the -style argument.
</ol>
<h3>Version 2.95</h3>
<ol>
<li>Fixed bugs in start_html(-style=>...) support introduced
in 2.94.
</ol>
<h3>Version 2.94</h3>
<ol>
<li>Removed warning from reset() method.
<li>Moved <area> and <map> tags into the :html3 group. Hope this
removes undefined CGI::Area errors.
<li>Changed CGI::Carp to play with mod_perl2 and to (hopefully)
restore reporting of compile-time errors.
<li>Fixed potential deadlock between web server and CGI.pm when aborting a read due to POST_MAX
(reported by Antti Lankila).
<li>Fixed issue with tag-generating function not incorporating content when first variable undef.
<li>Fixed cross-site scripting bug reported by obscure.
<li>Fixed Dump() function to return correctly formed XHTML - bug reported by Ralph Siemsen.
</ol>
<h3>Version 2.93</h3>
<ol>
<li>Fixed embarassing bug in mp1 support.
</ol>
<h3>Version 2.92</h3>
<ol>
<li>Fix to be P3P compliant submitted from MPREWITT.
<li>Added CGI->r() API for mod_perl1/mod_perl2.
<li>Fixed bug in redirect() that was corrupting cookies.
<li>Minor fix to behavior of reset() button to make it consistent with submit() button
(first time this has been changed in 9 years).
<li>Patch from Dan Kogai to handle UTF-8 correctly in 5.8 and higher.
<li>Patch from Steve Hay to make CGI::Carp's error messages appear on MSIE browsers.
<li>Added Yair Lenga's patch for non-urlencoded postings.
<li>Added Stas Bekman's patches for mod_perl 2 compatibility.
<li>Fixed uninitialized escape behavior submitted by William Campbell.
<li>Fixed tied behavior so that you can pass arguments to tie()
<li>Fixed incorrect generation of URLs when the path_info contains + and other odd characters.
<li>Fixed redirect(-cookies=>$cookie) problem.
<li>Fixed tag generation bug that affects -javascript passed to start_html().
</ol>
<h3>Version 2.91</h3>
<ol>
<li>Attribute generation now correctly respects the value of autoEscape().
<li>Fixed endofrm() syntax error introduced by Ben Edgington's patch.
</ol>
<h3>Version 2.90</h3>
<ol>
<li>Fixed bug in redirect header handling.
<li>Added P3P option to header().
<li>Patches from Alexey Mahotkin to make CGI::Carp work correctly with object-oriented exceptions.
<li>Removed inaccurate description of how to set multiple cookies from CGI::Cookie pod file.
<li>Patch from Kevin Mahony to prevent running out of filehandles when uploading lots of files.
<li>Documentation enhancement from Mark Fisher to note that the import_names() method transforms the
parameter names into valid Perl names.
<li>Patch from Dan Harkless to suppress lang attribute in <html> tag if specified as a null string.
<li>Patch from Ben Edgington to fix broken XHTML-transitional 1.0 validation on endform().
<li>Custom html header fix from Steffen Beyer (first letter correctly upcased now)
<li>Added a -verbatim option to stylesheet generation from Michael Dickson
<li>Faster delete() method from Neelam Gupta
<li>Fixed broken Cygwin support.
<li>Added empty charset support from Bradley Baetz
<li>Patches from Doug Perham and Kevin Mahoney to fix file upload failures
when uploaded file is a multiple of 4096.
</ol>
<h3>Version 2.89</h3>
<ol>
<li>Fixed behavior of ACTION tag when POSTING to a URL that has a query string.
<li>Added Patch from Michael Rommel to handle multipart/mixed uploads from Opera
</ol>
<h3>Version 2.88</h3>
<ol>
<li>Fixed problem with uploads being refused under Perl 5.8 when
under Taint mode.
<li>Fixed uninitialized variable warnings under Perl 5.8.
<li>Fixed CGI::Pretty regression test failures.
</ol>
<h3>Version 2.87</h3>
<ol>
<li>Security hole patched: when processing multipart/form-data postings,
most arguments were being untainted silently. Returned arguments are
now tainted correctly. This may cause some scripts to fail that used
to work (thanks to Nick Cleaton for pointing this out and persisting
until it was fixed).
<li>Update for mod_perl 2.0.
<li>Pragmas such as -no_xhtml are now respected in mod_perl environment.
</ol>
<h3>Version 2.86</h3>
<ol>
<li>Fixes for broken CGI::Cookie expiration dates introduced in
2.84.
</ol>
<h3>Version 2.85</h3>
<ol>
<li>Fix for broken autoEscape function introduced in 2.84.
</ol>
<h3>Version 2.84</h3>
<ol>
<li>Fix for failed file uploads on Cygwin platforms.
<li>HTML escaping code now replaced 0x8b and 0x9b with unicode
references ‹ and *#8250;
</ol>
<h3>Version 2.83</h3>
<ol>
<li>Fixed autoEscape() documentation inconsistencies.
<li>Patch from Ville Skytt to fix a number of XHTML inconsistencies.
<li>Added Max-Age to list of CGI::Cookie headers.
</ol>
<h3>Version 2.82</h3>
<ol>
<li>Patch from Rudolf Troller to add attribute setting and option groups to form fields.
<li>Patch from Simon Perreault for silent crashes when using CGI::Carp under mod_perl.
<li>Patch from Scott Gifford allows you to set the program name for CGI::Carp.
</ol>
<h3>Version 2.81</h3>
<ol>
<li>Removed extraneous slash from end of stylesheet tags generated by start_html in non-XHTML mode.
<li>Changed behavior of CGI::Carp with respect to eval{} contexts so that output behaves properly
in mod_perl environments.
<li>Fixed default DTD so that it validates with W3C validator.
</ol>
<h3>Version 2.80</h3>
<ol>
<li>Fixed broken messages in CGI::Carp.
<li>Changed checked="1" to checked="checked" for real XHTML compatibility.
<li>Resurrected REQUEST_URI code so that url() works correctly with multiviews.
</ol>
<h3>Version 2.79</h3>
<ol>
<li>Changes to CGI::Carp to avoid "subroutine redefined" error messages.
<li>Default DTD is now XHTML 1.0 Transitional
<li>Patches to support all HTML4 tags.
</ol>
<h3>Version 2.78</h3>
<ol>
<li>Added ability to change encoding in <?xml> assertion.
<li>Fixed the old escapeHTML('CGI') ne "CGI" bug
<li>In accordance with XHTML requirements, there are no longer any
minimized attributes, such as "checked".
<li>Patched bug which caused file uploads of exactly 4096 bytes to
be truncated to 4094 (thanks to Kevin Mahony)
<li>New tests and fixes to CGI::Pretty (thanks to Michael Schwern).
</ol>
<h3>Version 2.77</h3>
<ol>
<li>No new features, but released in order to fix an apparent CPAN bug.
</ol>
<h3>Version 2.76</h3>
<ol>
<li>New esc.t regression test for EBCDIC translations courtesy Peter Prymmer.
<li>Patches from James Jurach to make compatible with FCGI-ProcManager
<li>Additional fields passed to header() (like -Content_disposition)
now honor initial capitalization.
<li>Patch from Andrew McNaughton to handle utf-8 escapes (%uXXXX
codes) in URLs.
</ol>
<h3>Version 2.752</h3>
<ol>
<li>Syntax error in the autoloaded Fh::new() subroutine.
<li>Better error reporting in autoloaded functions.
</ol>
<h3>Version 2.751</h3>
<ol>
<li>Tiny tweak to filename regular expression function on line 3355.
</ol>
<h3>Version 2.75</h3>
<ol>
<li>Fixed bug in server push boundary strings (CGI.pm and CGI::Push).
<li>Fixed bug that occurs when uploading files with funny characters in the name
<li>Fixed non-XHTML-compliant attributes produced by textfield()
<li>Added EPOC support, courtesy Olaf Flebbe
<li>Fixed minor XHTML bugs.
<li>Made escape() and unescape() symmetric with respect to EBCDIC, courtesy
Roca, Ignasi <ignasi.roca@fujitsu.siemens.es>
<li>Removed uninitialized variable warning from CGI::Cookie,
provided by Atipat Rojnuckarin <rojnuca@yahoo.com>
<li>Fixed bug in CGI::Pretty that causes it to print partial end tags when
the $INDENT global is changed.
<li>Single quotes are changed to character entity ' for
compatibility with URLs.
</ol>
<h3>Version 2.74</h3> <p> September
13, 2000 <ol>
<li>Quashed one-character bug that caused CGI.pm to fail on file uploads.
</ol>
<h3>Version 2.73</h3>
<p>
September 12, 2000
<ol>
<li>Added -base to the list of arguments accepted by url().
<li>Fixes to XHTML support.
<li>POST parameters no longer show up in the Location box.
</ol>
<h3>Version 2.72</h3>
<p>
August 19, 2000
<ol>
<li>Fixed the defaults button so that it works again
<li>Charset is now correctly saved and restored when saving to files
<li>url() now works correctly when given scripts with %20 and other
escapes in the additional path info. This undoes a patch introduced
in version 2.47 that I no longer understand the rationale for.
</ol>
<h3>Version 2.71</h3>
<p>
August 13, 2000
<ol>
<li>Newlines in the value attributes of hidden fields and other form elements are
now escaped when using ISO-Latin.
<li>Inline script and style sections are now protected as CDATA sections when
XHTML mode is on (the default).
</ol>
<h3>Version 2.70</h3>
<p>
August 4, 2000
<ol>
<li>Fixed bug in scrolling_list() which omitted a space in front of the "multiple" attribute.
<li>Squashed the "useless use of string in void context" message from redirects.
</ol>
<h3>Version 2.69</h3>
<ol>
<li>startform() now creates default ACTION for POSTs as well as GETs.
This may break some browsers, but it no longer violates the HTML spec.
<li>CGI.pm now emits XHTML by default. Disable with -no_xhtml.
<li>We no longer interpret &#ddd sequences in non-latin character
sets.
</ol>
<h3>Version 2.68</h3>
<ol>
<li>No longer attempts to escape characters when dealing with non
ISO-8861 character sets.
<li>checkbox() function now defaults to using -value as its label,
rather than -name. The current behavior is what has been documented
from the beginning.
<li>-style accepts array reference to incorporate multiple
stylesheets into document.
</ol>
<ol>
<li>Fixed two bugs that caused the -compile pragma to fail with a
syntax error.
</ol>
<h3>Version 2.67</h3>
<ol>
<li>Added XHTML support (incomplete; tags need to be lowercased).
<li>Fixed CGI/Carp when running under mod_perl. Probably broke in other contexts.
<li>Fixed problems when passing multiple cookies.
<li>Suppress warnings from _tableize() that were appearing when using -w switch with
radio_group() and checkbox_group().
<li>Support for the header() -attachment argument, which can give
pages a default file name when saving to disk.
</ol>
<h3>Version 2.66</h3>
<ol>
<li>2.65 changes in make_attributes() broke HTTP header functions
(including redirect), so made it context sensitive.
</ol>
<h3>Version 2.65</h3>
<ol>
<li>Fixed regression tests to skip tests that require implicit fork
on machines without fork().
<li>Changed make_attributes() to automatically escape any HTML reserved
characters.
<li>Minor documentation fix in javascript example.
</ol>
<h3>Version 2.64</h3>
<ol>
<li>Changes introduced in 2.63 broke param() when retrieving parameter lists
containing only a single argument. This is now fixed.
<li>self_url() now defaults to returning parameters delimited with
semicolon. Use the pragma -oldstyle_urls to get the old "&" delimiter.
</ol>
<h3>Version 2.63</h3>
<ol>
<li>Fixed CGI::Push to pull out parameters correctly.
<li>Fixed redirect() so that it works with default character set
<li>Changed param() so as to returned empty string '' when referring
to variables passed in query strings like 'name1=&name2'
</ol>
<h3>Version 2.62</h3>
<ol>
<li>Fixed broken ReadParse() function, and added regression tests
<li>Fixed broken CGI::Pretty, and added regression tests
</ol>
<h3>Version 2.61</h3>
<ol>
<li>Moved more functions from CGI.pm proper into CGI/Util.pm. CGI/Cookie should now be
standalone.
<li>Disabled per-user temporary directories, which were causing grief.
</ol>
<h3>Version 2.60</h3>
<ol>
<li>Fixed junk appearing in autogenerated HTML functions when using object-oriented mode.
</ol>
<h3>Version 2.59</h3>
<ol>
<li>autoescape functionality breaks too much existing code, removed it.
<li>use escapeHTML() manually
</ol>
<h3>Version 2.58</h3>
This is the release version of 2.57.
<h3>Version 2.57</h3>
<ol>
<li>Added -debug pragma and turned off auto reading of STDIN.
<li>Default DTD updated to HTML 4.01 transitional.
<li>Added charset() method and the -charset argument to header().
<li>Fixed behavior of escapeHTML() to respect charset() and to escape nasty
Windows characters (thanks to Tom Christiansen).
<li>Handle REDIRECT_QUERY_STRING correctly.
<li>Removed use_named_parameters() because of dependency problems
and general lameness.
<li>Fixed problems with bad HREF links generated by url(-relative=>1)
when the url is like /people/.
<li>Silenced a warning on upload (patch provided by Jonas Liljegren)
<li>Fixed race condition in CGI::Carp when errors occur during parsing
(patch provided by Maurice Aubrey).
<li>Fixed failure of url(-path_info=>1) when path contains % signs.
<li>Fixed warning from CGI::Cookie when receiving foreign cookies
that don't use name=value format.
<li>Fixed incompatibilities with file uploading on VMS systems.
</ol>
<h3>Version 2.56</h3>
<ol>
<li>Fixed bugs in file upload introduced in version 2.55
<li>Fixed long-standing bug that prevented two files with identical
names from being uploaded.
</ol>
<h3>Version 2.55</h3>
<ol>
<li>Fixed cookie regression test so as not to produce an error.
<li>Fixed path_info() and self_url() to work correctly together when
path_info() modified.
<li>Removed manify warnings from CGI::{Switch,Apache}.
</ol>
<h3>Version 2.54</h3>
<ol>
<li>This will be the last release of the monolithic CGI.pm module. Later versions will be
modularized and optimized.
<li>DOMAIN tag no longer added to cookies by default. This will break some versions of
Internet Explorer, but will avoid breaking networks which use host tables without fully
qualified domain names. For compatibility, please always add the -domain tag when creating
cookies.
<li>Fixed escape() method so that +'s are treated correctly.
<li>Updated CGI::Pretty module.
</ol>
<h3>Version 2.53</h3>
<ol>
<li>Forgot to upgrade regression tests before releasing 2.52. <b>NOTHING ELSE HAS CHANGED IN LIBRARY</b>
</ol>
<h3>Version 2.52</h3>
<ol>
<li>Spurious newline in checkbox() routine removed. (courtesy John Essen)
<li>TEXTAREA linebreaks now respected in dump() routine. (courtesy John Essen)
<li>Patches for DOS ports (courtesy Robert Davies)
<li>Patches for VMS
<li>More fixes for cookie problems
<li>Fix CGI::Carp so that it doesn't affect eval{} blocks (courtesy Byron Brummer)
</ol>
<h3>Version 2.51</h3>
<ol>
<li>Fixed problems with cookies not being remembered when sent to IE 5.0 (and Netscape 5.0 too?)
<li>Numerous HTML compliance problems in cgi_docs.html; fixed
thanks to Michael Leahy
</ol>
<h3>Version 2.50</h3>
<ol>
<li>Added a new Vars() method to retrieve all parameters as a tied hash.
<li>Untainted tainted tempfile name so that script doesn't fail on terminal unlink.
<li>Made picking of upload tempfile name more intelligent so that doesn't fail in case of name collision.
<li>Fixed handling of expire times when passed an absolute timestamp.
<li>Changed dump() to Dump() to avoid name clashes.
</ol>
<h3>Version 2.49</h3>
<ol>
<li>Fixes for FastCGI (globals not getting reset)
<li>Fixed url() to correctly handle query string and path under MOD_PERL
</ol>
<h3>Version 2.48</h3>
<ol>
<li>Reverted detection of MOD_PERL to avoid breaking PerlEX.
</ol>
<h3>Version 2.47</h3>
<ol>
<li>Patch to fix file upload bug appearing in IE 3.01 for Macintosh/PowerPC.
<li>Replaced use of $ENV{SCRIPT_NAME} with $ENV{REQUEST_URI} when running
under Apache, to fix self-referencing URIs.
<li>Fixed bug in escapeHTML() which caused certain constructs, such as
CGI->image_button(), to fail.
<li>Fixed bug which caused strong('CGI') to fail. Be careful to use
CGI::strong('CGI') and not CGI->strong('CGI'). The latter will
produce confusing results.
<li>Added <b>upload()</b> function, as a preferred replacement for
the "filehandle as string" feature.
<li>Added <b>cgi_error()</b> function.
<li>Rewrote file upload handling to return undef rather than dieing
when an error is encountered. Be sure to call
<b>cgi_error()</b> to find out what went wrong.
</ol>
<h3>Version 2.46</h3>
<ol>
<li>Fix for failure of the "include" tests under mod_perl
<li>Added end_multipart_form to prevent failures during qw(-compile :all)
</ol>
<h3>Version 2.45</h3>
<ol>
<li>Multiple small documentation fixes
<li><cite>CGI::Pretty</cite> didn't get into 2.44. Fixed now.
</ol>
<h3>Version 2.44</h3>
<ol>
<li>Fixed file descriptor leak in upload function.
<li>Fixed bug in header() that prevented fields from containing double quotes.
<li>Added Brian Paulsen's <cite>CGI::Pretty</cite> package for
pretty-printing output HTML.
<li>Removed CGI::Apache and CGI::Switch from the distribution.
<li>Generated start_* shortcuts so that start_table(), end_table(),
start_ol(), end_ol(), and so forth now work (see the docs on how to
enable this feature).
<li>Changed accept() to Accept(), sub() to Sub(). There's still a conflict with
reset(), but this will break too many existing scripts!
</ol>
<h3>Version 2.43</h3>
<ol>
<li>Fixed problem with "use strict" and file uploads (thanks to Peter Haworth)
<li>Fixed problem with not MSIE 3.01 for the power_mac not doing
file uploads right.
<li>Fixed problem with file upload on IIS 4.0 when authorization in
use.
<li>-content_type and '-content-type' can now be provided to
header() as synonyms for -type.
<li>CGI::Carp now escapes the ampersand BEFORE escaping the > and
< signs.
<li>Fixed "not an array reference" error when passing a hash
reference to radio_group().
<li>Fixed non-removal of uploaded TMP files on NT platforms which
occurs when server runs on non-C drive (thanks to Steve Kilbane
for finding this one).
</ol>
<h3>Version 2.42</h3>
<ol>
<li>Too many screams of anguish at changed behavior of url(). Is now back
to its old behavior by default, with options to generate all the variants.
<li>Added regression tests. "make test" now works.
<li>Documentation fixes.
<li>Fixes for Macintosh uploads, but uploads STILL do not work pending changes
to MacPerl.
</ol>
<h3>Version 2.41</h3>
<ol>
<li>url() method now includes the path info. Use script_name() to get
it without path info().
<li>Changed handling of empty attributes in HTML tag generation. Be
warned! Use <tt>table({-border=>undef})</tt> rather than
<tt>table({-border=>''})</tt>.
<li>Changes to allow uploaded filenames to be compared to other
strings with "eq", "cmp" and "ne".
<li>Changes to allow CGI.pm to coexist more peacefully with ActiveState PerlEX.
<li>Changes to prevent exported variables from clashing when
importing ":all" set in combination with cookies.
</ol>
<h3>Version 2.40</h3>
<ol>
<li>CGI::Carp patched to work better with mod_perl (thanks to Chris
Dean).
<li>Uploads of files whose names begin with numbers or the Windows
\\UNC\shared\file nomenclature should no longer fail.
<li>The <STYLE> tag (for cascading style sheets) now generates the required TYPE attribute.
<li>Server push primitives added, thanks to Ed Jordan.
<li>Table and other HTML3 functions are now part of the :standard set.
<li>Small documentation fixes.
</ol>
<em>TO DO:</em>
<ol>
<li>Do something about the DTD mess. The module should generate correct DTDs, or at
least offer the programmer a way to specify the correct one.
<li>Split CGI.pm into CGI processing and HTML-generating modules.
<li>More robust file upload (?still not working on the Macintosh?).
<li>Bring in all the HTML4 functionality, particular the
accessibility features.
</ol>
<h3>Version 2.39</h3>
<ol>
<li>file uploads failing because of VMS patch; fixed.
<li>-dtd parameter was not being properly processed.
</ol>
<h3>Version 2.38</h3>
I finally got tired of all the 2.37 betas and released 2.38. The main
difference between this version and the last 2.37 beta (2.37b30) are
some fixes for VMS. This should allow file upload to work properly on
all VMS Web servers.
<h3>Version 2.37, various beta versions</h3>
<ol>
<li>Added a CGI::Cookie::parse() method for lucky mod_perl users.
<li>No longer need separate -values and -labels arguments for
multi-valued form elements.
<li>Added better interface to raw cookies (fix courtesy Ken Fox, kfox@ford.com)
<li>Added param_fetch() function for direct access to parameter list.
<li>Fix to checkbox() to allow for multi-valued single checkboxes (weird problem).
<li>Added a compile() method for those who want to compile without importing.
<li>Documented the import pragmas a little better.
<li>Added a -compile switch to the use clause for the long-suffering
mod_perl and Perl compiler users.
<li>Fixed initialization routines so that FileHandle and type globs
work correctly (and hash initialization doesn't fail!).
<li>Better deletion of temporary files on NT systems.
<li>Added documentation on escape(), unescape(), unescapeHTML() and
unescapeHTML() subroutines.
<li>Added documentation on creating subclasses.
<li>Fixed problem when calling $self->SUPER::foo() from inheriting
subclasses.
<li>Fixed problem using filehandles from within subroutines.
<li>Fixed inability to use the string "CGI" as a parameter.
<li>Fixed exponentially growing $FILLUNIT bug
<li>Check for undef filehandle in read_from_client()
<li>Now requires the UNIVERSAL.pm module, present in Perl 5.003_7 or
higher.
<li>Fixed problem with uppercase-only parameters being ignored.
<li>Fixed vanishing cookie problem.
<li>Fixed warning in initialize_globals() under mod_perl.
<li>File uploads from Macintosh versions of MSIE should now work.
<li>Pragmas now preceded by dashes (-nph) rather than colons (:nph).
Old style is supported for backward compatability.
<li>Can now pass arguments to all functions using {} brackets,
resolving historical inconsistencies.
<li>Removed autoloader warnings about absent MultipartBuffer::DESTROY.
<li>Fixed non-sticky checkbox() when -name used without -value.
<li>Hack to fix path_info() in IIS 2.0. Doesn't help with IIS 3.0.
<li>Parameter syntax for debugging from command line now more straightforward.
<li>Added $DISABLE_UPLOAD to disable file uploads.
<li>Added $POST_MAX to error out if POSTings exceed some ceiling.
<li>Fixed url_param(), which wasn't working at all.
<li>Fixed variable suicide problem in s///e expressions, where the autoloader
was needed during evaluation.
<li>Removed excess spaces between elements of checkbox and radio groups
<li>Can now create "valueless" submit buttons
<li>Can now set path_info as well as read it.
<li>ReadParse() now returns a useful function result.
<li>import_names() now allows you to optionally clear out the
namespace before importing (for mod_perl users)
<li>Made it possible to have a popup menu or radio button with a value of "0".
<li>link() changed to Link() to avoid overriding native link function.
<li>Takes advantage of mod_perl's register_cleanup() function to
clear globals.
<li><LAYER> and <ILAYER> added to :html3 functions.
<li>Fixed problems with private tempfiles and NT/IIS systems.
<li>No longer prints the DTD by default (I bet no one will
complain).
<li>Allow underscores to replace internal hyphens in parameter
names.
<li>CGI::Push supports heterogeneous MIME types and
adjustable delays between pages.
<li>url_param() method added for retrieving URL parameters even
when a fill-out form is POSTed.
<li>Got rid of warnings when radio_group() is called.
<li>Cookies now moved to their very own module.
<li>Fixed documentation bug in CGI::Fast.
<li>Added a :no_debug pragma to the import list.
</ol>
<h3>Version 2.36</h3>
<ol>
<li>Expanded JavaScript functionality
<li>Preliminary support for cascading stylesheets
<li>Security fixes for file uploads:
<ul>
<li>Module will bail out if its temporary file already exists
<li>Temporary files can now be made completely private to
avoid peeking by other users or CGI scripts.
</ul>
<li><cite>use CGI qw/:nph/</cite> wasn't working correctly. Now it
is.
<li>Cookie and HTTP date formats didn't meet spec. Thanks to Mark
Fisher (fisherm@indy.tce.com) for catching and fixing this.
</ol>
p
<h3>Version 2.35</h3>
<ol>
<li>Robustified multipart file upload against incorrect syntax in POST.
<li>Fixed more problems with mod_perl.
<li>Added -noScript parameter to start_html().
<li>Documentation fixes.
</ol>
<h3>Version 2.34</h3>
<ol>
<li>Stupid typo fix
</ol>
<h3>Version 2.33</h3>
<ol>
<li>Fixed a warning about an undefined environment variable.
<li>Doug's patch for redirect() under mod_perl
<li>Partial fix for busted inheritence from CGI::Apache
<li>Documentation fixes.
</ol>
<h3>Version 2.32</h3>
<ol>
<li>Improved support for Apache's mod_perl.
<li>Changes to better support inheritance.
<li>Support for OS/2.
</ol>
<h3>Version 2.31</h3>
<ol>
<li>New <strong>uploadInfo()</strong> method to obtain header
information from uploaded files.
<li><strong>cookie()</strong> without any arguments returns all the
cookies passed to a script.
<li>Removed annoying warnings about $ENV{NPH} when running with the
-w switch.
<li>Removed operator overloading throughout to make compatible with
new versions of perl.
<li><strong>-expires</strong> now implies the <strong>-date</strong>
header, to avoid clock skew.
<li>WebSite passes cookies in $ENV{COOKIE} rather than $ENV{HTTP_COOKIE}.
We now handle this, even though it's O'Reilly's fault.
<li>Tested successfully against new sfio I/O layer.
<li>Documentation fixes.
</ol>
<h3>Version 2.30</h3>
<ol>
<li>Automatic detection of operating system at load time.
<li>Changed select() function to Select() in order to avoid
conflict with Perl built-in.
<li>Added Tr() as an alternative to TR(); some people think it
looks better that way.
<li>Fixed problem with autoloading of MultipartBuffer::DESTROY code.
<li>Added the following methods:
<ul>
<li>virtual_host()
<li>server_software()
</ul>
<li>Automatic NPH mode when running under Microsoft IIS server.
</ol>
<h3>Version 2.29</h3>
<ol>
<li>Fixed cookie bugs
<li>Fixed problems that cropped up when useNamedParameters was set to 1.
<li>Prevent CGI::Carp::fatalsToBrowser() from crapping out when
encountering a die() within an eval().
<li>Fixed problems with filehandle initializers.
</ol>
<h3>Version 2.28</h3>
<ol>
<li>Added support for NPH scripts; also fixes problems with
Microsoft IIS.
<li>Fixed a problem with checkbox() values not being correctly saved
and restored.
<li>Fixed a bug in which CGI objects created with empty string
initializers took on default values from earlier CGI objects.
<li>Documentation fixes.
</ol>
<h3>Version 2.27</h3>
<ol>
<li>Small but important bug fix: the automatic capitalization of
tag attributes was accidentally capitalizing the VALUES as
well as the ATTRIBUTE names (oops).
</ol>
<h3>Version 2.26</h3>
<ol>
<li>Changed behavior of scrolling_list(), checkbox() and checkbox_group()
methods so that defaults are honored correctly. The "fix" causes
endform() to generate additional <INPUT TYPE="HIDDEN"> tags --
don't be surpised.
<li>Fixed bug involving the detection of the SSL protocol.
<li>Fixed documentation error in position of the -meta argument in start_html().
<li>HTML shortcuts now generate tags in ALL UPPERCASE.
<li>start_html() now generates correct SGML header:
<pre>
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
</pre>
<li>CGI::Carp no longer fails "use strict refs" pragma.
</ol>
<h3>Version 2.25</h3>
<ol>
<li>Fixed bug that caused bad redirection on destination URLs with arguments.
<li>Fixed bug involving use_named_parameters() followed by start_multipart_form()
<li>Fixed bug that caused incorrect determination of binmode for Macintosh.
<li>Spelling fixes on documentation.
</ol>
<H3>Version 2.24</H3>
<ol>
<li>Fixed bug that caused generation of lousy HTML for some form elements
<li>Fixed uploading bug in Windows NT
<li>Some code cleanup (not enough)
</ol>
<H3>Version 2.23</H3>
<ol>
<li>Fixed an obscure bug that caused scripts to fail mysteriously.
<li>Fixed auto-caching bug.
<li>Fixed bug that prevented HTML shortcuts from passing taint checks.
<li>Fixed some -w warning problems.
</ol>
<H3>Version 2.22</H3>
<ol>
<li>New CGI::Fast module for use with FastCGI protocol. See pod
documentation for details.
<li>Fixed problems with inheritance and autoloading.
<li>Added TR() (<tr>) and PARAM() (<param>) methods to
list of exported HTML tag-generating functions.
<li>Moved all CGI-related I/O to a bottleneck method so that this can
be overridden more easily in mod_perl (thanks to Doug MacEachern).
<li>put() method as substitute for print() for use in mod_perl.
<li>Fixed crash in tmpFileName() method.
<li>Added tmpFileName(), startform() and endform() to export list.
<li>Fixed problems with attributes in HTML shortcuts.
<li>Functions that don't actually need access to the CGI object now
no longer generate a default one. May speed things up slightly.
<li>Aesthetic improvements in generated HTML.
<li>New examples.
</ol>
<H3>Version 2.21</H3>
<ol>
<li>Added the <cite>-meta</cite> argument to <cite>start_html()</cite>.
<li>Fixed hidden fields (again).
<li>Radio_group() and checkbox_group() now return an appropriate scalar
value when called in a scalar context, rather than returning a numeric
value!
<li>Cleaned up the formatting of form elements to avoid unesthetic
extra spaces within the attributes.
<li>HTML elements now correctly include the closing tag when parameters
are present but null: em('')
<li>Added password_field() to the export list.
</ol>
<H3>Version 2.20</H3>
<ol>
<li>Dumped the SelfLoader because of problems with running with
taint checks and rolled my own. Performance is now
significantly improved.
<li>Added HTML shortcuts.
<li><cite>import()</cite> now adheres to the Perl module
conventions, allowing CGI.pm to import any or all method names
into the user's name space.
<li>Added the ability to initialize CGI objects from strings and
associative arrays.
<li>Made it possible to initialize CGI objects with filehandle
references rather than filehandle strings.
<li>Added the delete_all() and append() methods.
<li>CGI objects correctly initialize from filehandles on NT/95
systems now.
<li>Fixed the problem with binary file uploads on NT/95 systems.
<li>Fixed bug in redirect().
<li>Added '-Window-target' parameter to redirect().
<li>Fixed import_names() so that parameter names containing funny
characters work.
<li>Broke the unfortunate connection between cookie and CGI parameter name space.
<li>Fixed problems with hidden fields whose values are 0.
<li>Cleaned up the documentation somewhat.
</ol>
<H3>Version 2.19</H3>
<ol>
<li>Added cookie() support routines.
<li>Added -expires parameter to header().
<li>Added cgi-lib.pl compatability mode.
<li>Made the module more configurable for different
operating systems.
<li>Fixed a dumb bug in JavaScript button() method.
</ol>
<H3>Version 2.18</H3>
<ol>
<li>Fixed a bug that corrects a hang that
occurs on some platforms when processing file uploads.
Unfortunately this disables the check for bad Netscape
uploads.
<li>Fixed bizarre problem involving the inability to process
uploaded files that begin with a non alphabetic character
in the file name.
<li>Fixed a bug in the hidden fields involving the -override
directive being ignored when scalar defaults were passed.
<li>Added documentation on how to disable the SelfLoader features.
</ol>
<H3>Version 2.17</H3>
<ol>
<li>Added support for the SelfLoader module.
<li>Added oodles of JavaScript support routines.
<li>Fixed bad bug in query_string() method that caused some parameters
to be silently dropped.
<li>Robustified file upload code to handle premature termination by the
client.
<li>Exported temporary file names on file upload.
<li>Removed spurious "uninitialized variable" warnings that
appeared when running under 5.002.
<li>Added the Carp.pm library to the standard distribution.
<li>Fixed a number of errors in this documentation, and probably
added a few more.
<li>Checkbox_group() and radio_group() now return the buttons as arrays,
so that you can incorporate the individual buttons into specialized
tables.
<li>Added the '-nolabels' option to checkbox_group() and radio_group().
Probably should be added to all the other HTML-generating routines.
<li>Added the url() method to recover the URL without the entire
query string appended.
<li>Added request_method() to list of environment variables available.
<li>Would you believe it? Fixed hidden fields <em>again</em>!
</ol>
<H3>Version 2.16</H3>
<ol>
<li> Fixed hidden fields <em>yet again</em>.
<li> Fixed subtle problems in the file upload method that caused
intermittent failures (thanks to Keven Hendrick for this one).
<li> Made file upload more robust in the face of bizarre behavior
by the Macintosh and Windows Netscape clients.
<li> Moved the POD documentation to the bottom of the module
at the request of Stephen Dahmen.
<li> Added the -xbase parameter to the start_html() method, also
at the request of Stephen Dahmen.
<li> Added JavaScript form buttons at Stephen's request. I'm not sure how to
use this Netscape extension correctly, however, so for now the form()
method is in the module as an undocumented feature.
Use at your own risk!
</ol>
<H3>Version 2.15</H3>
<OL>
<LI> Added the <B>-override</B> parameter to all field-generating
methods.
<LI> Documented the <CODE>user_name()</CODE> and <CODE>remote_user()</CODE>
methods.
<LI> Fixed bugs that prevented empty strings from being recognized
as valid textfield contents.
<li> Documented the use of framesets and added a frameset example.
</OL>
<h3>Version 2.14</h3>
This was an internal experimental version that was never released.
<H3>Version 2.13</H3>
<OL>
<LI>Fixed a bug that interfered with the value "0" being entered into
text fields.
</OL>
<H3>Version 2.01</H3>
<OL>
<LI>Added -rows and -columns to the radio and checkbox groups.
No doubt this will cause much grief because it seems to
promise a level of meta-organization that it doesn't
actually provide.
<LI>Fixed a bug in the redirect() method -- it was not truly
HTTP/1.0 compliant.
</OL>
<H3>Version 2.0</H3>
The changes seemed to touch every line of code, so I decided
to bump up the major version number.
<OL>
<LI> Support for <A HREF="#named_param">named parameter
style method calls.</A> This turns out to be a
big win for extending CGI.pm when Netscape adds
new HTML "features".
<LI> Changed behavior of hidden fields back to the correct
"sticky" behavior.
<A HREF="#hidden_fields_warning">This is going to
break some programs,</A> but it is for the best in
the long run.
<LI> Netscape 2.0b2 broke the file upload feature. CGI.pm now
handles both 2.0b1 and 2.0b2-style uploading. It will
probably break again in 2.0b3.
<LI> There were still problems with library being unable to
distinguish between a form being loaded for the first time,
and a subsequent loading with all fields blank. We now
forcibly create a default name for the Submit button (if not
provided) so that there's always at least one parameter.
<LI> More workarounds to prevent annoying spurious warning messages
when run under the -w switch. -w is seriously broken in
perl 5.001!
</OL>
<H3>Version 1.57</H3>
<OL>
<LI> Support for the Netscape 2.0 "File upload" field.
<LI> The handling of defaults for selected items in scrolling lists
and multiple checkboxes is now consistent.
</OL>
<H3>Version 1.56</H3>
<OL>
<LI> Created true "pod" documentation for the module.
<LI> Cleaned up the code to avoid many of the spurious
"use of uninitialized variable" warnings when running
with the -w switch.
<LI> Added the <CODE>autoEscape()</CODE> method.
v <LI> Added string interpolation of the CGI object.
<LI> Added the ability to pass additional parameters to
the <BODY> tag.
<LI> Added the ability to specify the status code in the
HTTP header.
</OL>
<H3>Bug fixes in version 1.55</H3>
<OL>
<LI> Every time self_url() was called, the parameter list
would grow. This was a bad "feature".
<LI> Documented the fact that you can pass "-" to
radio_group() in order to prevent any button from
being highlighted by default.
</OL>
<H3>Bug fixes in version 1.54</H3>
<OL>
<LI> The user_agent() method is now documented;
<LI> A potential security hole in import() is now plugged.
<LI> Changed name of import() to import_names() for compatability
with CGI:: modules.
</OL>
<H3>Bug fixes in version 1.53</H3>
<OL>
<LI> Fixed several typos in the code that were causing the following
subroutines to fail in some circumstances
<OL>
<LI> checkbox()
<LI> hidden()
</OL>
<LI> No features added
</OL>
<H3>New features added in version 1.52</H3>
<OL>
<LI> Added backslashing, quotation marks, and other shell-style
escape sequences to the parameters passed in during debugging
off-line.
<LI> Changed the way that the hidden() method works so that the
default value always overrides the current one.
<LI> Improved the handling of sticky values in forms. It's now less
likely that sticky values will get stuck.
<LI> If you call server_name(), script_name() and several other
methods when running offline, the methods now create "dummy"
values to work with.
</OL>
<H3>Bugs fixed in version 1.51</H3>
<OL>
<LI> param() when called without arguments was returning an array of
length 1 even when there were no parameters to be had. Bad bug!
Bad!
<LI> The HTML code generated would break if input fields contained
the forbidden characters ">< or &. You can now use these characters
freely.
</OL>
<H3>New features added in version 1.50</H3>
<OL>
<LI> import() method allows all the parameters to be
imported into a namespace in one fell swoop.
<LI> Parameters are now returned in the same order in which they
were defined.
</OL>
<H3>Bugs fixed in version 1.45</H3>
<OL>
<LI> delete() method didn't work correctly. This is now fixed.
<LI> reset() method didn't allow you to set the name of the button. Fixed.
</OL>
<H3>Bugs fixed in version 1.44</H3>
<OL>
<LI>self_url() didn't include the path information. This is now
fixed.
</OL>
<H3>New features added in version 1.43</H3>
<OL>
<LI>Added the delete() method.
</OL>
<H3>New features added in version 1.42</H3>
<OL>
<LI>The image_button() method to create clickable images.
<LI>A few bug fixes involving forms embedded in <PRE> blocks.
</OL>
<H3>New features added in version 1.4</H3>
<OL>
<LI>New header shortcut methods
<UL>
<LI>redirect() to create HTTP redirection messages.
<LI>start_html() to create the HTML title, complete with
the recommended <LINK> tag that no one ever remembers
to include.
<LI>end_html() for completeness' sake.
</UL>
<LI>A new save() method that allows you to write out the state of an
script to a file or pipe.
<LI>An improved version of the new() method that allows you to restore the
state of a script from a file or pipe. With (2) this gives
you dump and restore capabilities! (Wow, you can put a
"121,931 customers served" banner at the bottom of your pages!)
<LI> A self_url() method that allows you to create state-maintaining
hypertext links. In addition to allowing you to maintain the
state of your scripts between invocations, this lets you work
around a problem that some browsers have when jumping to
internal links in a document that contains a form -- the form
information gets lost.
<LI>The user-visible labels in checkboxes, radio buttons, popup menus
and scrolling lists have now been decoupled from the values
sent to your CGI script. Your script can know a checkbox
by the name of "cb1" while the user knows it by a more
descriptive name. I've also added some parameters that were
missing from the text fields, such as MAXLENGTH.
<LI>A whole bunch of methods have been added to get at environment
variables involved in user verification and other obscure
features.
</OL>
<H3>Bug fixes</H3>
<OL>
<LI>The problems with the hidden fields have (I hope at last) been
fixed.
<LI>You can create multiple query objects and they will all be
initialized correctly. This simplifies the creation of
multiple forms on one page.
<LI>The URL unescaping code works correctly now.
</OL>
<A HREF="#contents">Table of Contents</A>
<HR>
<ADDRESS>Lincoln D. Stein, lstein@cshl.org<br>
<a href="http://www.cshl.org/">Cold Spring Harbor Laboratory</a></ADDRESS>
<P>
<!-- hhmts start -->
Last modified: Thu Nov 2 09:20:02 EST 2006
<!-- hhmts end -->
</BODY> </HTML>
|