PHP/Java
第一页 1 2 下页 最后页 [ 显示模式: 摘要 | 列表 ]

MD5 加密之 java 与 js 实现

[不指定 2024/01/09 16:45 | by 刘新修 ]

MD5 加密算法实际是一种信息摘要算法,其加密不可逆向解密;

其一般用作数据签名,来确保信息传输的完整性与安全性;

  • 完整性:传输数据完整未丢失
  • 安全性:数据未被恶意篡改

一、java 实现 MD5 加密

Java代码
  1. public class MD5Util {  
  2.   
  3.     /**
  4.      * 对字符串md5加密
  5.      *
  6.      * @param str 传入要加密的字符串
  7.      * @return MD5加密后的字符串(小写+字母)
  8.      */  
  9.     public static String getMD5LowerCase(String str) {  
  10.         try {  
  11.             // 生成一个MD5加密计算摘要  
  12.             MessageDigest md = MessageDigest.getInstance("MD5");  
  13.             // 计算md5函数  
  14.             md.update(str.getBytes());  
  15.             // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符  
  16.             // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值  
  17.             return new BigInteger(1, md.digest()).toString(16);  
  18.         } catch (Exception e) {  
  19.             e.printStackTrace();  
  20.             return null;  
  21.         }  
  22.     }  
  23.   
  24.     /**
  25.      * 对字符串md5加密
  26.      *
  27.      * @param str 传入要加密的字符串
  28.      * @return MD5加密后的字符串(大写+数字)
  29.      */  
  30.   
  31.     public static String getMD5UpperCase(String s) {  
  32.         char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
  33.                 'A', 'B', 'C', 'D', 'E', 'F' };  
  34.         try {  
  35.             byte[] btInput = s.getBytes();  
  36.             // 获得MD5摘要算法的 MessageDigest 对象  
  37.             MessageDigest mdInst = MessageDigest.getInstance("MD5");  
  38.             // 使用指定的字节更新摘要  
  39.             mdInst.update(btInput);  
  40.             // 获得密文  
  41.             byte[] md = mdInst.digest();  
  42.             // 把密文转换成十六进制的字符串形式  
  43.             int j = md.length;  
  44.             char str[] = new char[j * 2];  
  45.             int k = 0;  
  46.             for (int i = 0; i < j; i++) {  
  47.                 byte byte0 = md[i];  
  48.                 str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
  49.                 str[k++] = hexDigits[byte0 & 0xf];  
  50.             }  
  51.             return new String(str);  
  52.         } catch (Exception e) {  
  53.             e.printStackTrace();  
  54.             return null;  
  55.         }  
  56.     }  
  57.   
  58.     public static void main(String[] args) {  
  59.         String str = "\"我+Admin1234~!@#¥%……&*()\"";  
  60.         System.out.println(str);  
  61.         //"我+Admin1234~!@#¥%……&*()"  
  62.           
  63.         String s1 = getMD5LowerCase(str);  
  64.         System.out.println(s1);  
  65.         //6bb6f83c026357a15cdf12e5d6b2b310  
  66.           
  67.         String s2 = getMD5UpperCase(str);  
  68.         System.out.println(s2);  
  69.         //6BB6F83C026357A15CDF12E5D6B2B310  
  70.     }  
  71. }  

测试

db06c78d1e24cf708a14ce81c9b617ec

DB06C78D1E24CF708A14CE81C9B617EC

二、js 实现 MD5 加密

使用第三方库 crypto-js,示例代码如下:

XML/HTML代码
  1. <!DOCTYPE html>  
  2. <html lang="zh-CN">  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <title>111</title>  
  6.     <style type="text/css">  
  7.         body{background:#2C91AE;}  
  8.     </style>  
  9. </head>  
  10. <body>  
  11.   
  12. </body>  
  13. <script src="http://172.16.102.156/public/crypto/crypto-js.min.js"></script>  
  14.   
  15. <!-- 中国文书网MD5加密封装方法调用 -->  
  16. <script type="text/javascript" src="md5.js"></script>  
  17. <script type="text/javascript">  
  18. /*** 刘新修本地md5加密方法封装(大写) ***/  
  19. // function md5(string) {  
  20. //     function rotateLeft(lValue, iShiftBits) {  
  21. //         return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));  
  22. //     }  
  23. //     function addUnsigned(lX, lY) {  
  24. //         var lX4, lY4, lX8, lY8, lResult;  
  25. //         lX8 = (lX & 0x80000000);  
  26. //         lY8 = (lY & 0x80000000);  
  27. //         lX4 = (lX & 0x40000000);  
  28. //         lY4 = (lY & 0x40000000);  
  29. //         lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);  
  30. //         if (lX4 & lY4) {  
  31. //             return (lResult ^ 0x80000000 ^ lX8 ^ lY8);  
  32. //         }  
  33. //         if (lX4 | lY4) {  
  34. //             if (lResult & 0x40000000) {  
  35. //                 return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);  
  36. //             } else {  
  37. //                 return (lResult ^ 0x40000000 ^ lX8 ^ lY8);  
  38. //             }  
  39. //         } else {  
  40. //             return (lResult ^ lX8 ^ lY8);  
  41. //         }  
  42. //     }  
  43.   
  44. //     function f(x, y, z) {  
  45. //         return (x & y) | ((~x) & z);  
  46. //     }  
  47.   
  48. //     function g(x, y, z) {  
  49. //         return (x & z) | (y & (~z));  
  50. //     }  
  51.   
  52. //     function h(x, y, z) {  
  53. //         return (x ^ y ^ z);  
  54. //     }  
  55.   
  56. //     function i(x, y, z) {  
  57. //         return (y ^ (x | (~z)));  
  58. //     }  
  59.   
  60. //     function FF(a, b, c, d, x, s, ac) {  
  61. //         a = addUnsigned(a, addUnsigned(addUnsigned(f(b, c, d), x), ac));  
  62. //         return addUnsigned(rotateLeft(a, s), b);  
  63. //     }  
  64.   
  65. //     function GG(a, b, c, d, x, s, ac) {  
  66. //         a = addUnsigned(a, addUnsigned(addUnsigned(g(b, c, d), x), ac));  
  67. //         return addUnsigned(rotateLeft(a, s), b);  
  68. //     }  
  69.   
  70. //     function HH(a, b, c, d, x, s, ac) {  
  71. //         a = addUnsigned(a, addUnsigned(addUnsigned(h(b, c, d), x), ac));  
  72. //         return addUnsigned(rotateLeft(a, s), b);  
  73. //     }  
  74.   
  75. //     function II(a, b, c, d, x, s, ac) {  
  76. //         a = addUnsigned(a, addUnsigned(addUnsigned(i(b, c, d), x), ac));  
  77. //         return addUnsigned(rotateLeft(a, s), b);  
  78. //     }  
  79.   
  80. //     function convertToWordArray(string) {  
  81. //         var lWordCount;  
  82. //         var lMessageLength = string.length;  
  83. //         var lNumberOfWords_temp1 = lMessageLength + 8;  
  84. //         var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;  
  85. //         var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;  
  86. //         var lWordArray = new Array(lNumberOfWords - 1);  
  87. //         var lBytePosition = 0;  
  88. //         var lByteCount = 0;  
  89. //         while (lByteCount < lMessageLength) {  
  90. //             lWordCount = (lByteCount - (lByteCount % 4)) / 4;  
  91. //             lBytePosition = (lByteCount % 4) * 8;  
  92. //             lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));  
  93. //             lByteCount++;  
  94. //         }  
  95.   
  96. //         lWordCount = (lByteCount - (lByteCount % 4)) / 4;  
  97. //         lBytePosition = (lByteCount % 4) * 8;  
  98. //         lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);  
  99. //         lWordArray[lNumberOfWords - 2] = lMessageLength << 3;  
  100. //         lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;  
  101. //         return lWordArray;  
  102. //     }  
  103.   
  104. //     function wordToHex(lValue) {  
  105. //         var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;  
  106. //         for (lCount = 0; lCount <= 3; lCount++) {  
  107. //             lByte = (lValue >>> (lCount * 8)) & 255;  
  108. //             WordToHexValue_temp = "0" + lByte.toString(16);  
  109. //             WordToHexValueWordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);  
  110. //         }  
  111. //         return WordToHexValue;  
  112. //     }  
  113.   
  114. //     function utf8Encode(string) {  
  115. //         stringstring = string.replace(/\r\n/g, "\n");  
  116. //         var utftext = "";  
  117.   
  118. //         for (var n = 0; n < string.length; n++) {  
  119.   
  120. //             var c = string.charCodeAt(n);  
  121.   
  122. //             if (c < 128) {  
  123. //                 utftext += String.fromCharCode(c);  
  124. //             }  
  125. //             else if ((c > 127) && (c < 2048)) {  
  126. //                 utftext += String.fromCharCode((c >> 6) | 192);  
  127. //                 utftext += String.fromCharCode((c & 63) | 128);  
  128. //             }  
  129. //             else {  
  130. //                 utftext += String.fromCharCode((c >> 12) | 224);  
  131. //                 utftext += String.fromCharCode(((c >> 6) & 63) | 128);  
  132. //                 utftext += String.fromCharCode((c & 63) | 128);  
  133. //             }  
  134.   
  135. //         }  
  136.   
  137. //         return utftext;  
  138. //     }  
  139.   
  140. //     var x = [],  
  141. //         k, AA, BB, CC, DD, a, b, c, d,  
  142. //         S11 = 7, S12 = 12, S13 = 17, S14 = 22,  
  143. //         S21 = 5, S22 = 9 , S23 = 14, S24 = 20,  
  144. //         S31 = 4, S32 = 11, S33 = 16, S34 = 23,  
  145. //         S41 = 6, S42 = 10, S43 = 15, S44 = 21;  
  146.   
  147. //     string = utf8Encode(string);  
  148.   
  149. //     x = convertToWordArray(string);  
  150. //     // console.log(JSON.stringify(x))  
  151. //     // console.log(x.length)  
  152.   
  153. //     a = 0x67452301;  
  154. //     b = 0xEFCDAB89;  
  155. //     c = 0x98BADCFE;  
  156. //     d = 0x10325476;  
  157.   
  158. //     for (k = 0; k < x.length; k += 16) {  
  159. //         AA = a;  
  160. //         BB = b;  
  161. //         CC = c;  
  162. //         DD = d;  
  163. //         a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);  
  164. //         d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);  
  165. //         c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);  
  166. //         b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);  
  167. //         a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);  
  168. //         d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);  
  169. //         c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);  
  170. //         b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);  
  171. //         a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);  
  172. //         d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);  
  173. //         c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);  
  174. //         b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);  
  175. //         a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);  
  176. //         d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);  
  177. //         c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);  
  178. //         b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);  
  179. //         a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);  
  180. //         d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);  
  181. //         c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);  
  182. //         b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);  
  183. //         a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);  
  184. //         d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);  
  185. //         c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);  
  186. //         b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);  
  187. //         a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);  
  188. //         d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);  
  189. //         c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);  
  190. //         b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);  
  191. //         a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);  
  192. //         d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);  
  193. //         c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);  
  194. //         b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);  
  195. //         a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);  
  196. //         d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);  
  197. //         c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);  
  198. //         b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);  
  199. //         a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);  
  200. //         d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);  
  201. //         c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);  
  202. //         b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);  
  203. //         a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);  
  204. //         d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);  
  205. //         c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);  
  206. //         b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);  
  207. //         a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);  
  208. //         d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);  
  209. //         c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);  
  210. //         b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);  
  211. //         a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);  
  212. //         d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);  
  213. //         c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);  
  214. //         b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);  
  215. //         a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);  
  216. //         d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);  
  217. //         c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);  
  218. //         b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);  
  219. //         a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);  
  220. //         d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);  
  221. //         c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);  
  222. //         b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);  
  223. //         a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);  
  224. //         d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);  
  225. //         c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);  
  226. //         b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);  
  227. //         a = addUnsigned(a, AA);  
  228. //         b = addUnsigned(b, BB);  
  229. //         c = addUnsigned(c, CC);  
  230. //         d = addUnsigned(d, DD);  
  231. //     }  
  232.   
  233. //     var temp = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);  
  234. //     return temp.toUpperCase();  
  235. // };  
  236.   
  237. // console.log('刘新修本地封装/md5加密(--测试--)', md5('测试'))  
  238. //"DB06C78D1E24CF708A14CE81C9B617EC"  
  239.   
  240.   
  241. /*** 第三方类库CryptoJS.MD5()方法 || 和中国文书网测试结果一致(小写) ***/  
  242. console.log('刘新修/CryptoJS.MD5()-加密(--测试--)\n', CryptoJS.MD5('测试').toString())  
  243. </script>  
  244. </html>  

中网文书网/MD5加密(--测试--) db06c78d1e24cf708a14ce81c9b617ec

刘新修/CryptoJS.MD5()-加密(--测试--) db06c78d1e24cf708a14ce81c9b617ec

 

下载文件
这个文件只能在登入之后下载。请先 注册登入

遇到个很幼稚的问题,用json_encode把数组转换为json时,发现转化的值为null。怎么回事呢?查找手册:发现了下面的话:

该函数只能接受 UTF-8 编码的数据(译注:指字符/字符串类型的数据)
 
原来数组中有中文,需要转码哦,写个转换字符编码的函数吧:
PHP代码
  1. function encodeConvert($str,$fromCode,$toCode)  
  2. {  
  3. if (strtoupper($toCode) == strtoupper($fromCode)) return $str;  
  4. if (is_string($str)) {  
  5. if (function_exists('mb_convert_encoding')) {  
  6. return mb_convert_encoding($str, $toCode, $fromCode);  
  7. } else {  
  8. return iconv($fromCode, $toCode, $str);  
  9. }  
  10. } elseif (is_array($str)) {  
  11. foreach ($str as $k => $v) {  
  12. $str[$k] = encodeConvert($v, $fromCode, $toCode);  
  13. }  
  14. return $str;  
  15. }  
  16. return $str;  
  17. }  
对于数组,通过下面方式json_encode调用,一切ok。
PHP代码
  1. $json_api=json_encode(encodeConvert($json_api,'gb2312','utf-8'));  
  2. $json_api=json_decode(json_decode($json_api));  

今天数组json_encode转json的时候,输出一片空白,难道是数据量太大了?导致输出空白了?
后来检查下php程序似乎没有出错,就是json_encode的时候出现了问题,那到底是什么问题呢?

我们先来说下json_encode这个函数

C#代码
  1. (PHP 5 >= 5.2.0, PECL json >= 1.2.0, PHP 7)  
  2. json_encode — 对变量进行 JSON 编码  
  3.   
  4. 说明  
  5. -----------------------------------------------------------  
  6. string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )  
  7.   
  8. 参数  
  9. -----------------------------------------------------------  
  10. value  
  11. 待编码的 value ,除了resource 类型之外,可以为任何数据类型。  
  12. 所有字符串数据的编码必须是 UTF-8。  
  13.   
  14. options  
  15. 由以下常量组成的二进制掩码: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR。  
  16.   
  17. depth  
  18. 设置最大深度。 必须大于0。  
  19.   
  20. 返回值  
  21. -----------------------------------------------------------  
  22. 成功则返回 JSON 编码的 string 或者在失败时返回 FALSE 。  

注意:上面对参数明确说明(所有字符串数据的编码必须是 UTF-8)

可能正是因为这一点导致我输出错误,但是我怎么知道,会是这个错误呢?因为我发现有一个这个函数json_last_error

我们看下这个函数

C#代码
  1. (PHP 5 >= 5.3.0, PHP 7)  
  2. json_last_error — 返回最后发生的错误  
  3.   
  4. 说明  
  5. -----------------------------------------------------------  
  6. int json_last_error ( void )  
  7. 如果有,返回 JSON 编码解码时最后发生的错误。  
  8.   
  9. 参数  
  10. -----------------------------------------------------------  
  11. 此函数没有参数。  
  12.   
  13. 返回值  
  14. -----------------------------------------------------------  
  15. 返回一个整型(integer),这个值会是以下的常量之一:  
C#代码
  1. 例如:  
  2. echo json_encode(array('error' => '0''message' => '没有错误'));  
  3. var_dump(json_last_error());  
  4. //这里也可以是json_decode  
  5.   
  6. //错误码对照  
  7. 0 JSON_ERROR_NONE  
  8. 1 JSON_ERROR_DEPTH  
  9. 2 JSON_ERROR_STATE_MISMATCH  
  10. 3 JSON_ERROR_CTRL_CHAR  
  11. 4 JSON_ERROR_SYNTAX  
  12. 5 JSON_ERROR_UTF8  
  13. 6 JSON_ERROR_RECURSION  
  14. 7 JSON_ERROR_INF_OR_NAN  
  15. 8 JSON_ERROR_UNSUPPORTED_TYPE  

我返回的是 int 5,对照返回错误码,自然而然就是(异常的 UTF-8 字符,也许是因为不正确的编码)这个错误了,知道错误后,然后检查你要返回的数据,再做下处理就OK了。

  当我们实例化一个php类的时候,要怎么传递参数呢?这取决于该类的构造方法。

  例:

  person.class.php

  

  class person{

  var $name;

  var $color;

  var $sex;

  var $age;

  function __construct($name,$age='',$sex='boy'){

  $this->name = $name;

  $this->age = $age;

  $this->sex = $sex;

  $this->color = 'yello';

  }

  function eat(){

  echo $this->name.'要吃饭';

  }

  function xinxi(){

  echo $this->name.' is '.$this->sex.' and age is '.$this->age.' fuse is '.$this->color;

  }

  }

  ?>

  son.php

  

  include('person.class.php');

  $son = new person('cuihua',25,'girl');//此处的参数传递要和类的构造方法里面的参数顺序对应

  //$son->xinxi();//cuihua is girl and age is 25 fuse is yello

  $son->name = '田妞';

  $son->eat();//田妞要吃饭

  ?>

有时我们想截取最后一个斜杠'/'后面的数字;

有时我们又需要截取第一个斜杠'/'前面的内容判断用户输入的url链接带不带http://等等;

字符串的截取php内置函数就有很多种;简单的写几个示例;

1
$str='123/456/789/abc';

截取第一个斜杠前面的内容可以这样来:

1
echo substr($str,0,strpos($str'/'))

    或者

1
2
3
$array=explode('/'$str);
echo $array[0];
// 输出 123

截取第一个斜杠后面的内容可以这样来:

1
2
echo substr($str,strpos($str,'/')+1);
//输出 456/789/abc

 

截取最后一个斜杠后面的内容可以这样来:

1
echo trim(strrchr($str'/'),'/');

    或者如果知道斜杠的个数

1
2
3
$array=explode('/'$str);
echo $array[3];
//输出 abc

 

但是问题来了;如果不知道有多少个斜杠呢?如果想要第二个斜杠和第三个斜杠中间的内容呢?

下面我写的这个函数就可以轻松解决如上 所有问题;

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
/**
 * 按符号截取字符串的指定部分
 * @param string $str 需要截取的字符串
 * @param string $sign 需要截取的符号
 * @param int $number 如是正数以0为起点从左向右截  负数则从右向左截
 * @return string 返回截取的内容
 */
 
function cut_str($str,$sign,$number){
    $array=explode($sign$str);
    $length=count($array);
    if($number<0){
        $new_array=array_reverse($array);
        $abs_number=abs($number);
        if($abs_number>$length){
            return 'error';
        }else{
            return $new_array[$abs_number-1];
        }
    }else{
        if($number>=$length){
            return 'error';
        }else{
            return $array[$number];
        }
    }
}

示例:

1
2
3
4
echo cut_str($str,'/',0); //输出 123
echo cut_str($str,'/',2); //输出 789
echo cut_str($str,'/',-1);//输出 abc
echo cut_str($str,'/',-3);//输出 456
Tags: ,

使用PHP实现CORS 跨域资源共享,可传参origin通过限制,代码如下:

PHP代码
  1. <?php  
  2. /******** 定义Response返回header头格式及编码 ********/  
  3. header('Content-type: application/json; charset=utf-8');  
  4.   
  5. /******** 回调参数设置 ********/  
  6. $param="origin";  
  7. $origin_URL=$_REQUEST[$param];  
  8.   
  9.   
  10. /******** json_encode 转成=> encode_json *******/  
  11. function encode_json($str){  
  12.     return urldecode(json_encode(url_encode($str)));  
  13. }  
  14. function url_encode($str){  
  15.     if(is_array($str)){  
  16.         foreach($str as $key=>$value){  
  17.             $str[urlencode($key)]=url_encode($value);  
  18.         }  
  19.     }else{  
  20.         $str=urlencode($str);  
  21.     }  
  22.     return $str;  
  23. }  
  24.   
  25. /**************** \/\/反转义范例 ********************/  
  26. function stripslashes_deep($value){  
  27.     $value=is_array($value)?  
  28.                 array_map('stripslashes_deep',$value):  
  29.                 stripslashes($value);  
  30.     return $value;  
  31. }  
  32.   
  33. /******************** Example ******************************/  
  34. $array=array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));  
  35. $array=stripslashes_deep($array);  
  36.   
  37. /******************** Output *******************************/  
  38.   
  39. //echo encode_json(array('china'=>'钓鱼岛是中国的!','Japan'=>array('name'=>'日本狗!')));  
  40.   
  41.   
  42. /************ 定义Post过来什么数据就返回什么数据 ***********/  
  43. $res=array(  
  44.     'status'=>-1,
  45.     'name'=>isset($_POST['name'])?$_POST['name']:'',
  46.     'gender'=>isset($_POST['gender'])?$_POST['gender']:''
  47. );
  48. $arr=array(
  49.      "status"=>1,
  50.      "url"=>"http://www.liuxinxiu.com/",
  51.      "dataList"=>array(
  52.           "siteId"=>"1",
  53.           "title"=>urldecode('我的博客'),
  54.           "images"=>"http://192.168.9.100/upload/2015/06/20/moren.gif",
  55.           "indexNum"=>10,
  56.           "pageNum"=>"300",
  57.           "tagNum"=>"20",
  58.           "linkType"=>"linkTaobao",
  59.           "publishTime"=>"20:00:00"
  60.       )
  61. );
  62. $arr['dataList']['images']="http://www.liuxinxiu.com/upload/2015/06/20/moren.gif";
  63. //print_r($arr);
  64. /*************** 定义错误信息 ***************/
  65. $errStr='{"status":-1,"info":"Request Error"}';
  66. $errJson=json_decode($errStr,true); //json_decode转成了array数组
  67. //print_r($errJson) //转成了array数组
  68. /************** 获取客户端的Origin域名 **************/
  69. $origin=isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:'';
  70. /******** 定义符合规则的域名数组 ********/
  71. $allow_origin=array(
  72.     'http://liuxinxiu.com',  
  73.     'http://code.liuxinxiu.com',  
  74.     'http://test.liuxinxiu.com'  
  75. );  
  76.   
  77. /****************** 判断如果有POST过来数据 *********************/  
  78. if(isset($_POST['name'])&&isset($_POST['gender'])){
  79.     /********** 只要是POST请求过来无论合法与否都要正常通信 **********/
  80.      header('Access-Control-Allow-Methods:POST');
  81.      header('Access-Control-Allow-Headers:x-requested-with,content-type');
  82.     /******** 匹配客户端域名是否在数组列表中 ******/
  83.     if(in_array($origin,$allow_origin)){
  84.         header('Access-Control-Allow-Origin:'.$origin);
  85.         $res['status']=1;
  86.         $res['getUser']=$arr;
  87.         echo json_encode($res);
  88.     }
  89.     else if(!in_array($origin,$allow_origin)){
  90.         /******** 如有设置就取设置URL返回头信息 ********/
  91.         if(isset($origin_URL)){
  92.             header('Access-Control-Allow-Origin:'.$origin_URL);
  93.             $res['status']=1;
  94.             $res['getUser']=$arr;
  95.             echo encode_json($res);
  96.             //echo json_encode("中文", JSON_UNESCAPED_UNICODE);
  97.         }
  98.         /******** 如没有设置URL就返回错误信息  ********/
  99.         else{
  100.             header('Access-Control-Allow-Origin:'.$origin);
  101.             $errJson['status']=-1;
  102.             $errJson['info']="You don't have permission to submit!";  
  103.             echo encode_json($errJson);  
  104.         }  
  105.     }  
  106. }  
  107. /************ 没有所匹配的POST提交数据 ***********/  
  108. else{  
  109.     if($GLOBALS['HTTP_RAW_POST_DATA']){  
  110.             header('Access-Control-Allow-Origin:'.$origin);  
  111.             $errJson['status']=-1;  
  112.             $errJson['info']="Syntax error in parameters or arguments.";  
  113.             echo encode_json($errJson);  
  114.     }  
  115.     else{  
  116.         header("Content-type: text/html; charset=utf-8");  
  117.         echo 'It is forbidden for the URL request!';  
  118.     }  
  119. }  
  120. ?>  

PHP数据提交接口地址 (禁止使用GET访问):http://code.liuxinxiu.com/php/Interface/server.php

配合HTML代码如下:

XML/HTML代码
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8"/>  
  5.   
  6.     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>  
  8.     <meta name="format-detection"content="telephone=no">  
  9.     <meta name="apple-mobile-web-app-capable" content="yes" />  
  10.     <meta name="apple-mobile-web-app-status-bar-style" content="black" />  
  11.     <style>body,html {background:#fff;font-family: "Lucida Grande",Calibri,Arial;font-size:12pt;color: #333;background: #f8f8f8;text-align:center;}*{margin:0;padding:0;}h1{line-height:1.6em;font-size:24px;text-indent:.5em;padding-top:.6em}i{line-height:2em;font-size:18px;color:#999;}.line{height:10px;border-bottom:1px solid #ccc;font-size:0;overflow:hidden;}</style>  
  12.     <title>跨域测试</title>  
  13. </head>  
  14. <body>  
  15. <h1 id="show"></h1>  
  16. <input type="button" value="Click me" onclick="msg()" />  
  17.   
  18. </body>  
  19. <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>  
  20. <script type='text/javascript'>  
  21. /********** 获取URL参数 **********/  
  22. function getQueryString(name){  
  23. var reg=new RegExp("(^|&)"+name+"=([^&]*)(&|$)","i");  
  24. var r=window.location.search.substr(1).match(reg);  
  25. if (r!=null) return unescape(r[2]); return null;  
  26. }  
  27.   
  28.   
  29. /********** 发起Ajax请求 **********/  
  30. function msg(){  
  31.     /******* 动态切换提交数据 *******/  
  32.     if(_origin){  
  33.         if(_name&&_gender){  
  34.             var data={name:_name,gender:_gender,origin:_origin};  
  35.         }  
  36.         else{  
  37.             var data={name:"xiaoming",gender:"male",origin:_origin};  
  38.         }  
  39.     }  
  40.     else if(_error==null){  
  41.         var data={name:"xiaoming",gender:"male"};  
  42.     }  
  43.     else if(_error){  
  44.         var data={xxx:111};  
  45.     }  
  46.     /******* 动态设置提交URL *******/  
  47.     if(_url){  
  48.         var urlPath=_url;  
  49.     }  
  50.     else{  
  51.         var urlPath='http://code.liuxinxiu.com/php/Interface/server.php';  
  52.     }  
  53.     $.ajax({  
  54.        type:'post',  
  55.        url:urlPath,  
  56.        data:data,  
  57.        cache:false,  
  58.        dataType:'json',  
  59.        success:function(data){  
  60.            if(data.name){  
  61.                 document.getElementById("show").innerHTML=data.name+' '+data.gender;  
  62.            }  
  63.            else if(data.status!=1){  
  64.                 document.getElementById("show").innerHTML=data.info;  
  65.            }  
  66.        },  
  67.        error:function(){  
  68.            console.log("请求错误//")  
  69.        }  
  70.     });  
  71. };  
  72.   
  73. /***********************************************************************************************  
  74. $.post("http://www.server.com/server.php",{name:"fdipzone",gender:"male"}).done(function(data){  
  75.     document.getElementById("show").innerHTML=data.name+' '+data.gender;  
  76. });  
  77. **********************************************************************************************/  
  78. </script>  
  79. </html>  

HTML访问地址 (测试跨域) ==> http://test1.liuxinxiu.com/php/Interface/html/server.html?n=php

HTML访问地址 (非法参数) ==> http://test1.liuxinxiu.com/php/Interface/html/server.html?error=php

Tags: ,

PHP处理HTTP请求的几种方式

[不指定 2016/09/05 17:48 | by 刘新修 ]

GET,一般是明文的,比如XXX.php?a=1&b=2,这里的a,b就必须用GET方式接收,接收代码如下:
$a = $_GET['a'];
$b = $_GET['b'];
//接收a,b两个变量
POST,一般是隐藏的非明文的,一般表单设置成POST的,接收方式如下:
//比如有个表单,表单中有两个文本框,name 分别是 a,b,那么代码如下:
$a = $_POST['a'];
$b = $_POST['b'];
另外:$_REQUEST,可以同时接收GET、POST的变量,用法如:
$_REQUEST['a'];//接收变量a,a可以是GET的也可以是POST的

另外说说PHP获取POST请求的几种方式:

方法1、最常见的方法是:$_POST['fieldname'];
说明:只能接收Content-Type: application/x-www-form-urlencoded提交的数据
解释:也就是表单POST过来的数据

方法2、file_get_contents(“php://input”);
说明:
允许读取 POST 的原始数据。
和 $HTTP_RAW_POST_DATA 比起来,它给内存带来的压力较小,并且不需要任何特殊的 php.ini 设置。
php://input 不能用于 enctype=”multipart/form-data”。
解释:
对于未指定 Content-Type 的POST数据,则可以使用file_get_contents(“php://input”);来获取原始数据。
事实上,用PHP接收POST的任何数据都可以使用本方法。而不用考虑Content-Type,包括二进制文件流也可以。
所以用方法二是最保险的方法。

方法3、$GLOBALS['HTTP_RAW_POST_DATA'];
说明:
总是产生 $HTTP_RAW_POST_DATA  变量包含有原始的 POST 数据。
此变量仅在碰到未识别 MIME 类型的数据时产生。
$HTTP_RAW_POST_DATA  对于 enctype=”multipart/form-data”  表单数据不可用
如果post过来的数据不是PHP能够识别的,可以用 $GLOBALS['HTTP_RAW_POST_DATA']来接收,
比如 text/xml 或者 soap 等等
解释:
$GLOBALS['HTTP_RAW_POST_DATA']存放的是POST过来的原始数据。
$_POST或$_REQUEST存放的是 PHP以key=>value的形式格式化以后的数据。
但$GLOBALS['HTTP_RAW_POST_DATA']中是否保存POST过来的数据取决于centent-Type的设置,即POST数据时 必须显式示指明Content-Type: application/x-www-form-urlencoded,POST的数据才会存放到 $GLOBALS['HTTP_RAW_POST_DATA']中。
Tags:

php [urlencode urldecode] 函数

[不指定 2016/03/29 13:28 | by 刘新修 ]

 urlencode()编码:对字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数,空格则编码为加号(+)。

urldecode()解码:还原 URL 编码字符串。
示例:
<?php
header("Content-Type:text/html; charset=utf-8");
//对参数值进行编码
$parm=urlencode("演示php-mysql");
 
//拼接url
$url="decode.php?par=".$parm;
?>
 
<a href="<?php echo $url;?>">urlencode演示</a>
 
点击连接后地址栏中汉字被编码了:
http://localhost/decode.php?par=%E6%BC%94%E7%A4%BAphp-mysql
------------------------------------------------------------------------
 
//decode.php
<?php
//获取参数值
$parValue=$_GET['par'];
 
//解码
echo urldecode($parValue);
//运行结果:演示php-mysql
?>
PHP代码
  1. <?php  
  2.     //创建画布,返回一个资源类型的变量$image,并在内存中开辟一个临时区域  
  3.     $image = imagecreatetruecolor(400,400);                //创建画布大小为400x400  
  4.   
  5.     //设置图像中所需的颜色,相当于在画画时准备的染料盒  
  6.     $white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);          //为图像分配颜色为白色  
  7.     $gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);           //为图像分配颜色为灰色  
  8.     $darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90);       //为图像分配颜色为暗灰色  
  9.     $navy = imagecolorallocate($image, 0x00, 0x00, 0x80);           //为图像分配颜色为深蓝色  
  10.     $darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50);       //为图像分配颜色为暗深蓝色  
  11.     $red = imagecolorallocate($image, 0xFF, 0x00, 0x00);           //为图像分配颜色为红色  
  12.     $darkred = imagecolorallocate($image, 0x90, 0x00, 0x00);       //为图像分配颜色为暗红色  
  13.   
  14.     imagefill($image, 0, 0, $white);            //为画布背景填充背景颜色  
  15.     //动态制作3D效果  
  16.     for ($i=220;$i>200;$i--){                //循环10次画出立体效果  
  17.         imagefilledarc($image, 200, $i, 400, 200, -160, 40, $darknavy, IMG_ARC_PIE);  
  18.         imagefilledarc($image, 200, $i, 400, 200, 40, 75, $darkgray, IMG_ARC_PIE);  
  19.         imagefilledarc($image, 200, $i, 400, 200, 75, 200, $darkred, IMG_ARC_PIE);  
  20.     }  
  21.   
  22.     imagefilledarc($image, 200, 200, 400, 200, -160, 40, $navy, IMG_ARC_PIE);      //画一椭圆弧且填充  
  23.     imagefilledarc($image, 200, 200, 400, 200, 40 , 75, $gray, IMG_ARC_PIE);      //画一椭圆弧且填充  
  24.     imagefilledarc($image, 200, 200, 400, 200, 75, 200, $red, IMG_ARC_PIE);      //画一椭圆弧且填充  
  25.   
  26.     imagestring($image, 20, 100, 230, '34.7%', $white);                //水平地画一行字符串,依次是F/X/Y/--数值越大向右、向下  
  27.     imagestring($image, 20, 200, 150, '55.5%', $white);                //水平地画一行字符串,依次是F/X/Y/--数值越大向右、向下  
  28.   
  29.     //向浏览器中输出一个GIF格式的图片  
  30.     header('Content-type:image/png');       //使用头函数告诉浏览器以图像方式处理以下输出  
  31.     imagepng($image);                       //向浏览器输出  
  32.     imagedestroy($image);                   //销毁图像释放资源  
  33.   
  34.     //header("Content-type: text/html; charset=utf-8");  
  35.     //$str="<div>'$image'</div>";  
  36.     //echo $str;  
  37. ?>  

gd-png.php

PHP代码
  1. <?php  
  2.     //创建画布,返回一个资源类型的变量$image,并在内存中开辟一个临时区域  
  3.     $image = imagecreatetruecolor(375,375);                //创建画布大小为375x375 iPhone6 375X627  
  4.   
  5.     //设置图像中所需的颜色,相当于在画画时准备的染料盒  
  6.     $white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);          //为图像分配颜色为白色  
  7.     $gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);           //为图像分配颜色为灰色  
  8.     $darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90);       //为图像分配颜色为暗灰色  
  9.     $navy = imagecolorallocate($image, 0x00, 0x00, 0x80);           //为图像分配颜色为深蓝色  
  10.     $darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50);       //为图像分配颜色为暗深蓝色  
  11.     $red = imagecolorallocate($image, 0xFF, 0x00, 0x00);           //为图像分配颜色为红色  
  12.     $darkred = imagecolorallocate($image, 0x90, 0x00, 0x00);       //为图像分配颜色为暗红色  
  13.   
  14.     imagefill($image, 0, 0, $white);            //为画布背景填充背景颜色  
  15.     //动态制作3D效果  
  16.     for ($i=200;$i>180;$i--){                //循环10次画出立体效果  
  17.         imagefilledarc($image, 187, $i, 360, 180, -160, 40, $darknavy, IMG_ARC_PIE);   //  
  18.         imagefilledarc($image, 187, $i, 360, 180, 40, 75, $darkgray, IMG_ARC_PIE);  
  19.         imagefilledarc($image, 187, $i, 360, 180, 75, 200, $darkred, IMG_ARC_PIE);  
  20.     }  
  21.   
  22.     imagefilledarc($image, 187, 180, 360, 180, -160, 40, $navy, IMG_ARC_PIE);      //画一椭圆弧且填充,第一个187-180 是错开7像素  
  23.     imagefilledarc($image, 187, 180, 360, 180, 40 , 75, $gray, IMG_ARC_PIE);      //画一椭圆弧且填充  
  24.     imagefilledarc($image, 187, 180, 360, 180, 75, 200, $red, IMG_ARC_PIE);      //画一椭圆弧且填充  
  25.   
  26.     imagestring($image, 20, 180, 130, '55.5%'$white);                //水平地画一行字符串,依次是F/X/Y/--数值越大向右、向下  
  27.     imagestring($image, 20, 100, 200, '34.7%'$white);                //水平地画一行字符串,依次是F/X/Y/--数值越大向右、向下  
  28.   
  29.   
  30.     //向浏览器中输出一个GIF格式的图片  
  31.     //header("Content-type:text/html;charset=utf-8"); // 设置页面的编码风格  
  32.     header('Content-type:image/png');       //使用头函数告诉浏览器以图像方式处理以下输出--通知浏览器输出的是图像  
  33.     imagepng($image);                       //向浏览器输出  
  34.     imagedestroy($image);                   //销毁图像释放资源  
  35.   
  36.     //header("Content-type: text/html; charset=utf-8");  
  37.     //$str="<div>'$image'</div>";  
  38.     //echo $str;  
  39. ?>  
Java代码
  1. <%@page trimDirectiveWhitespaces="true"%>  
  2. <%@page language="java" pageEncoding="utf-8"%>  
  3. <%@page import="sun.misc.*"%>  
  4. <%@page import="java.io.*"%>  
  5. <%@page import="java.util.*"%>  
  6. <%  
  7. List<String> htmltempList=new ArrayList<String>();  
  8. //String[][] students = {{'小明','1101','23','52819911'},{'夏利','1101','23','52819911'},{'小强','1102','21','52819901'}};  
  9.   
  10. //创建6行4列二位数组  
  11. String[][] book=new String [6][4];  
  12. book[0]=new String[]{"风清扬","1101","23","52819911"};  
  13. book[1]=new String[]{"许志飞","1101","23","52819911"};  
  14. book[2]=new String[]{"令狐冲","1102","21","52819901"};  
  15. book[3]=new String[]{"任我行","1103","22","52819991"};  
  16. book[4]=new String[]{"任盈盈","1104","24","52819981"};  
  17. book[5]=new String[]{"东方不败","1105","26","52819981"};  
  18.   
  19. String[][] arr1={{"11","22"},{"aaa","bbb"},{"AAA","BBB"}};  
  20. String[][] arr2=new String[3][2];  
  21. for(int i=0;i<book.length;i++){  
  22.     htmltempList.add("<ul>");  
  23.     for(int j=0;j<book[i].length;j++){  
  24.         //out.println(book[i][j]);  
  25.         htmltempList.add("<li>" +book[i][j]+"</li>");  
  26.     }  
  27.     htmltempList.add("</ul>");  
  28. }  
  29.   
  30. /*
  31. int [][]a=new int[8][8];
  32. for (int i=0;i<8;i++){
  33.    for(int j=0;j<8;j++){
  34.     a[i][j]=i+j;
  35.     out.println(a[i][j]+"---");
  36.    }
  37. }*/  
  38. //out.println("---");  
  39.   
  40. %>  
  41.   
  42. <%  
  43. for (int i=0;i<9;i++){  
  44. //htmltempList.add("<li><span>" + i+"</span></li>");  
  45. }  
  46. /*
  47. for (int i=0; i<htmltempList.size();i++){
  48. out.print(htmltempList.get(i));
  49. }
  50. out.print(testCol(htmltempList) + "====================");
  51. */  
  52. %>  
  53. <%  
  54. response.setContentType("text/json");  
  55. response.setCharacterEncoding("utf-8");  
  56. String callback=request.getParameter("Jsoncallback");  
  57. if(callback!=null&&!"".equals(callback)){  
  58.     out.print(callback+"({\"dataList\":\"" +testColCon(htmltempList) + "\"})");  
  59. }  
  60.   
  61. %>  
  62. <%!  
  63. public static int testCol(List<String> testList){  
  64. return testList.size();  
  65. }  
  66. public static String testColCon(List<String> testList){  
  67. String str="";  
  68. String html="<style>*{margin:0;padding:0;}h1{font-size:16px;text-align:center; line-height:45px;}body{color:#333;font-size:14px;font-family:'MicrosoftYahei';background:#B7CACC;}div{border:1px solid #405E7B; border-bottom:0; width:95%; margin:0 auto;background:#fff;content:'';display:table;clear:both}li{line-height:35px;list-style:none;width:25%;text-align:center;border-bottom:1px solid #405E7B;float:left;}</style><h1>最近风云人员名单</h1><div>";  
  69. for (int i=0; i<testList.size();i++){  
  70.     str+=testList.get(i);  
  71. }  
  72. html+=str;  
  73.         byte[] b=null;  
  74.         String s=null;  
  75.         try{    
  76.             b=html.getBytes("utf-8");  
  77.         }catch(UnsupportedEncodingException e){  
  78.             e.printStackTrace();    
  79.         }    
  80.         if (b!=null){  
  81.             s=new BASE64Encoder().encode(b);    
  82.               
  83.             s=s.replaceAll("\r\n","");  
  84.             s=s.replaceAll("\n","");  
  85. //          s = s.replaceAll("","");  
  86.             //s="PGxpPjxzcGFuPjA8L3NwYW4+PC9saT48bGk+PHNwYW4+MTwvc3Bhbj48L2xpPjxsaT48c3Bhbj4yPC9zcGFuPjwvbGk+PGxpPjxzcGFuPjM8L3NwYW4+PC9saT48bGk+PHNwYW4+NDwvc3Bhbj48L2xpPjxsaT48c3Bhbj41PC9zcGFuPjwvbGk+PGxpPjxzcGFuPjY8L3NwYW4+PC9saT48bGk+PHNwYW4+Nzwvc3Bhbj48L2xpPjxsaT48c3Bhbj44PC9zcGFuPjwvbGk+";  
  87.         }    
  88.         return s;  
  89.               
  90. }  
  91.   
  92. %>  
PHP代码
  1. <?php  
  2. //公共声明  
  3. header('Content-type: text/json');  
  4. html_entity_decode($string, ENT_QUOTES, 'UTF-8');  
  5.   
  6. //回调参数设置  
  7. $param="Jsoncallback";  
  8. $callback=$_REQUEST[$param];  
  9.   
  10. $students=array(  
  11.     array("风清扬","1101","23","52819911"),  
  12.     array("许志飞","1101","23","52819911"),  
  13.     array("令狐冲","1102","21","52819901"),  
  14.     array("任我行","1103","22","52819991"),  
  15.     array("任盈盈","1104","24","52819981"),  
  16.     array("东方不败","1105","26","52819981")  
  17. );  
  18. $tempBegin='<style>*{margin:0;padding:0;}h1{font-size:16px;text-align:center; line-height:45px;}body{color:#333;font-size:14px;font-family:"MicrosoftYahei";background:#B7CACC;}div{border:1px solid #405E7B; border-bottom:0; width:95%; margin:0 auto;background:#fff;content:"";display:table;clear:both}li{line-height:35px;list-style:none;width:25%;text-align:center;border-bottom:1px solid #405E7B;float:left;}</style><h1>最近风云人员名单</h1><div>';  
  19. foreach($students as $v){  
  20.     $tempBegin.='
  21.     <ul>
  22.         <li>'.$v[0].'</li>
  23.         <li>'.$v[1].'</li>
  24.         <li>'.$v[2].'</li>
  25.         <li>'.$v[3].'</li>
  26.     </ul>
  27.     ';  
  28. }  
  29. $tempEnd=$tempBegin.'</div>';  
  30. //echo $tempEnd;  
  31.   
  32. $str1=base64_encode($tempEnd);  
  33. $str2='{"dataList":"'.$str1.'"}';  
  34. $jsonStr=$callback."(".$str2.")";  
  35.   
  36. //判断请求参数存在就会输出Json数据  
  37. //if(isset($callback)&&!empty($callback)){  
  38. if(isset($callback)){  
  39.     echo $jsonStr;  
  40. }  
  41.   
  42. //判断请求参数不存在就输出错误信息  
  43. if(!isset($callback)){  
  44.     header("Content-type: text/html; charset=utf-8");  
  45.     $str="<h1>400 Required String parameter '{$param}' is not present</h1><hr /><small>http Request with error params: none callback function</small>";  
  46.     echo $str;  
  47. }  
  48.   
  49. ?>  
第一页 1 2 下页 最后页 [ 显示模式: 摘要 | 列表 ]