MD5 加密之 java 与 js 实现
MD5 加密算法实际是一种信息摘要算法,其加密不可逆向解密;
其一般用作数据签名,来确保信息传输的完整性与安全性;
- 完整性:传输数据完整未丢失
- 安全性:数据未被恶意篡改
一、java 实现 MD5 加密
- public class MD5Util {
- /**
- * 对字符串md5加密
- *
- * @param str 传入要加密的字符串
- * @return MD5加密后的字符串(小写+字母)
- */
- public static String getMD5LowerCase(String str) {
- try {
- // 生成一个MD5加密计算摘要
- MessageDigest md = MessageDigest.getInstance("MD5");
- // 计算md5函数
- md.update(str.getBytes());
- // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
- // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
- return new BigInteger(1, md.digest()).toString(16);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- /**
- * 对字符串md5加密
- *
- * @param str 传入要加密的字符串
- * @return MD5加密后的字符串(大写+数字)
- */
- public static String getMD5UpperCase(String s) {
- char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
- 'A', 'B', 'C', 'D', 'E', 'F' };
- try {
- byte[] btInput = s.getBytes();
- // 获得MD5摘要算法的 MessageDigest 对象
- MessageDigest mdInst = MessageDigest.getInstance("MD5");
- // 使用指定的字节更新摘要
- mdInst.update(btInput);
- // 获得密文
- byte[] md = mdInst.digest();
- // 把密文转换成十六进制的字符串形式
- int j = md.length;
- char str[] = new char[j * 2];
- int k = 0;
- for (int i = 0; i < j; i++) {
- byte byte0 = md[i];
- str[k++] = hexDigits[byte0 >>> 4 & 0xf];
- str[k++] = hexDigits[byte0 & 0xf];
- }
- return new String(str);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- public static void main(String[] args) {
- String str = "\"我+Admin1234~!@#¥%……&*()\"";
- System.out.println(str);
- //"我+Admin1234~!@#¥%……&*()"
- String s1 = getMD5LowerCase(str);
- System.out.println(s1);
- //6bb6f83c026357a15cdf12e5d6b2b310
- String s2 = getMD5UpperCase(str);
- System.out.println(s2);
- //6BB6F83C026357A15CDF12E5D6B2B310
- }
- }
测试
db06c78d1e24cf708a14ce81c9b617ec
DB06C78D1E24CF708A14CE81C9B617EC
二、js 实现 MD5 加密
使用第三方库 crypto-js,示例代码如下:
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="utf-8">
- <title>111</title>
- <style type="text/css">
- body{background:#2C91AE;}
- </style>
- </head>
- <body>
- </body>
- <script src="http://172.16.102.156/public/crypto/crypto-js.min.js"></script>
- <!-- 中国文书网MD5加密封装方法调用 -->
- <script type="text/javascript" src="md5.js"></script>
- <script type="text/javascript">
- /*** 刘新修本地md5加密方法封装(大写) ***/
- // function md5(string) {
- // function rotateLeft(lValue, iShiftBits) {
- // return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
- // }
- // function addUnsigned(lX, lY) {
- // var lX4, lY4, lX8, lY8, lResult;
- // lX8 = (lX & 0x80000000);
- // lY8 = (lY & 0x80000000);
- // lX4 = (lX & 0x40000000);
- // lY4 = (lY & 0x40000000);
- // lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
- // if (lX4 & lY4) {
- // return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
- // }
- // if (lX4 | lY4) {
- // if (lResult & 0x40000000) {
- // return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
- // } else {
- // return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
- // }
- // } else {
- // return (lResult ^ lX8 ^ lY8);
- // }
- // }
- // function f(x, y, z) {
- // return (x & y) | ((~x) & z);
- // }
- // function g(x, y, z) {
- // return (x & z) | (y & (~z));
- // }
- // function h(x, y, z) {
- // return (x ^ y ^ z);
- // }
- // function i(x, y, z) {
- // return (y ^ (x | (~z)));
- // }
- // function FF(a, b, c, d, x, s, ac) {
- // a = addUnsigned(a, addUnsigned(addUnsigned(f(b, c, d), x), ac));
- // return addUnsigned(rotateLeft(a, s), b);
- // }
- // function GG(a, b, c, d, x, s, ac) {
- // a = addUnsigned(a, addUnsigned(addUnsigned(g(b, c, d), x), ac));
- // return addUnsigned(rotateLeft(a, s), b);
- // }
- // function HH(a, b, c, d, x, s, ac) {
- // a = addUnsigned(a, addUnsigned(addUnsigned(h(b, c, d), x), ac));
- // return addUnsigned(rotateLeft(a, s), b);
- // }
- // function II(a, b, c, d, x, s, ac) {
- // a = addUnsigned(a, addUnsigned(addUnsigned(i(b, c, d), x), ac));
- // return addUnsigned(rotateLeft(a, s), b);
- // }
- // function convertToWordArray(string) {
- // var lWordCount;
- // var lMessageLength = string.length;
- // var lNumberOfWords_temp1 = lMessageLength + 8;
- // var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
- // var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
- // var lWordArray = new Array(lNumberOfWords - 1);
- // var lBytePosition = 0;
- // var lByteCount = 0;
- // while (lByteCount < lMessageLength) {
- // lWordCount = (lByteCount - (lByteCount % 4)) / 4;
- // lBytePosition = (lByteCount % 4) * 8;
- // lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
- // lByteCount++;
- // }
- // lWordCount = (lByteCount - (lByteCount % 4)) / 4;
- // lBytePosition = (lByteCount % 4) * 8;
- // lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
- // lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
- // lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
- // return lWordArray;
- // }
- // function wordToHex(lValue) {
- // var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
- // for (lCount = 0; lCount <= 3; lCount++) {
- // lByte = (lValue >>> (lCount * 8)) & 255;
- // WordToHexValue_temp = "0" + lByte.toString(16);
- // WordToHexValueWordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
- // }
- // return WordToHexValue;
- // }
- // function utf8Encode(string) {
- // stringstring = string.replace(/\r\n/g, "\n");
- // var utftext = "";
- // for (var n = 0; n < string.length; n++) {
- // var c = string.charCodeAt(n);
- // if (c < 128) {
- // utftext += String.fromCharCode(c);
- // }
- // else if ((c > 127) && (c < 2048)) {
- // utftext += String.fromCharCode((c >> 6) | 192);
- // utftext += String.fromCharCode((c & 63) | 128);
- // }
- // else {
- // utftext += String.fromCharCode((c >> 12) | 224);
- // utftext += String.fromCharCode(((c >> 6) & 63) | 128);
- // utftext += String.fromCharCode((c & 63) | 128);
- // }
- // }
- // return utftext;
- // }
- // var x = [],
- // k, AA, BB, CC, DD, a, b, c, d,
- // S11 = 7, S12 = 12, S13 = 17, S14 = 22,
- // S21 = 5, S22 = 9 , S23 = 14, S24 = 20,
- // S31 = 4, S32 = 11, S33 = 16, S34 = 23,
- // S41 = 6, S42 = 10, S43 = 15, S44 = 21;
- // string = utf8Encode(string);
- // x = convertToWordArray(string);
- // // console.log(JSON.stringify(x))
- // // console.log(x.length)
- // a = 0x67452301;
- // b = 0xEFCDAB89;
- // c = 0x98BADCFE;
- // d = 0x10325476;
- // for (k = 0; k < x.length; k += 16) {
- // AA = a;
- // BB = b;
- // CC = c;
- // DD = d;
- // a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
- // d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
- // c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
- // b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
- // a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
- // d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
- // c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
- // b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
- // a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
- // d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
- // c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
- // b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
- // a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
- // d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
- // c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
- // b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
- // a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
- // d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
- // c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
- // b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
- // a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
- // d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
- // c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
- // b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
- // a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
- // d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
- // c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
- // b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
- // a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
- // d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
- // c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
- // b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
- // a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
- // d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
- // c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
- // b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
- // a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
- // d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
- // c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
- // b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
- // a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
- // d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
- // c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
- // b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
- // a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
- // d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
- // c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
- // b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
- // a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
- // d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
- // c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
- // b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
- // a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
- // d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
- // c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
- // b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
- // a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
- // d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
- // c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
- // b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
- // a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
- // d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
- // c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
- // b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
- // a = addUnsigned(a, AA);
- // b = addUnsigned(b, BB);
- // c = addUnsigned(c, CC);
- // d = addUnsigned(d, DD);
- // }
- // var temp = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
- // return temp.toUpperCase();
- // };
- // console.log('刘新修本地封装/md5加密(--测试--)', md5('测试'))
- //"DB06C78D1E24CF708A14CE81C9B617EC"
- /*** 第三方类库CryptoJS.MD5()方法 || 和中国文书网测试结果一致(小写) ***/
- console.log('刘新修/CryptoJS.MD5()-加密(--测试--)\n', CryptoJS.MD5('测试').toString())
- </script>
- </html>
中网文书网/MD5加密(--测试--) db06c78d1e24cf708a14ce81c9b617ec
刘新修/CryptoJS.MD5()-加密(--测试--) db06c78d1e24cf708a14ce81c9b617ec
php json 处理gbk转码utf-8问题( json_encode转换数组,值为null)
遇到个很幼稚的问题,用json_encode把数组转换为json时,发现转化的值为null。怎么回事呢?查找手册:发现了下面的话:
- function encodeConvert($str,$fromCode,$toCode)
- {
- if (strtoupper($toCode) == strtoupper($fromCode)) return $str;
- if (is_string($str)) {
- if (function_exists('mb_convert_encoding')) {
- return mb_convert_encoding($str, $toCode, $fromCode);
- } else {
- return iconv($fromCode, $toCode, $str);
- }
- } elseif (is_array($str)) {
- foreach ($str as $k => $v) {
- $str[$k] = encodeConvert($v, $fromCode, $toCode);
- }
- return $str;
- }
- return $str;
- }
- $json_api=json_encode(encodeConvert($json_api,'gb2312','utf-8'));
- $json_api=json_decode(json_decode($json_api));
今天数组json_encode转json的时候,输出一片空白,难道是数据量太大了?导致输出空白了?
后来检查下php程序似乎没有出错,就是json_encode的时候出现了问题,那到底是什么问题呢?
我们先来说下json_encode这个函数
- (PHP 5 >= 5.2.0, PECL json >= 1.2.0, PHP 7)
- json_encode — 对变量进行 JSON 编码
- 说明
- -----------------------------------------------------------
- string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
- 参数
- -----------------------------------------------------------
- value
- 待编码的 value ,除了resource 类型之外,可以为任何数据类型。
- 所有字符串数据的编码必须是 UTF-8。
- options
- 由以下常量组成的二进制掩码: 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。
- depth
- 设置最大深度。 必须大于0。
- 返回值
- -----------------------------------------------------------
- 成功则返回 JSON 编码的 string 或者在失败时返回 FALSE 。
注意:上面对参数明确说明(所有字符串数据的编码必须是 UTF-8)
可能正是因为这一点导致我输出错误,但是我怎么知道,会是这个错误呢?因为我发现有一个这个函数json_last_error
我们看下这个函数
- (PHP 5 >= 5.3.0, PHP 7)
- json_last_error — 返回最后发生的错误
- 说明
- -----------------------------------------------------------
- int json_last_error ( void )
- 如果有,返回 JSON 编码解码时最后发生的错误。
- 参数
- -----------------------------------------------------------
- 此函数没有参数。
- 返回值
- -----------------------------------------------------------
- 返回一个整型(integer),这个值会是以下的常量之一:
- 例如:
- echo json_encode(array('error' => '0', 'message' => '没有错误'));
- var_dump(json_last_error());
- //这里也可以是json_decode
- //错误码对照
- 0 JSON_ERROR_NONE
- 1 JSON_ERROR_DEPTH
- 2 JSON_ERROR_STATE_MISMATCH
- 3 JSON_ERROR_CTRL_CHAR
- 4 JSON_ERROR_SYNTAX
- 5 JSON_ERROR_UTF8
- 6 JSON_ERROR_RECURSION
- 7 JSON_ERROR_INF_OR_NAN
- 8 JSON_ERROR_UNSUPPORTED_TYPE
我返回的是 int 5,对照返回错误码,自然而然就是(异常的 UTF-8 字符,也许是因为不正确的编码)这个错误了,知道错误后,然后检查你要返回的数据,再做下处理就OK了。
实例化php类的时候如何传参
当我们实例化一个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();//田妞要吃饭
?>
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 |
CORS||跨域资源共享||PHP版本实现
使用PHP实现CORS 跨域资源共享,可传参origin通过限制,代码如下:
- <?php
- /******** 定义Response返回header头格式及编码 ********/
- header('Content-type: application/json; charset=utf-8');
- /******** 回调参数设置 ********/
- $param="origin";
- $origin_URL=$_REQUEST[$param];
- /******** json_encode 转成=> encode_json *******/
- function encode_json($str){
- return urldecode(json_encode(url_encode($str)));
- }
- function url_encode($str){
- if(is_array($str)){
- foreach($str as $key=>$value){
- $str[urlencode($key)]=url_encode($value);
- }
- }else{
- $str=urlencode($str);
- }
- return $str;
- }
- /**************** \/\/反转义范例 ********************/
- function stripslashes_deep($value){
- $value=is_array($value)?
- array_map('stripslashes_deep',$value):
- stripslashes($value);
- return $value;
- }
- /******************** Example ******************************/
- $array=array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
- $array=stripslashes_deep($array);
- /******************** Output *******************************/
- //echo encode_json(array('china'=>'钓鱼岛是中国的!','Japan'=>array('name'=>'日本狗!')));
- /************ 定义Post过来什么数据就返回什么数据 ***********/
- $res=array(
- 'status'=>-1,
- 'name'=>isset($_POST['name'])?$_POST['name']:'',
- 'gender'=>isset($_POST['gender'])?$_POST['gender']:''
- );
- $arr=array(
- "status"=>1,
- "url"=>"http://www.liuxinxiu.com/",
- "dataList"=>array(
- "siteId"=>"1",
- "title"=>urldecode('我的博客'),
- "images"=>"http://192.168.9.100/upload/2015/06/20/moren.gif",
- "indexNum"=>10,
- "pageNum"=>"300",
- "tagNum"=>"20",
- "linkType"=>"linkTaobao",
- "publishTime"=>"20:00:00"
- )
- );
- $arr['dataList']['images']="http://www.liuxinxiu.com/upload/2015/06/20/moren.gif";
- //print_r($arr);
- /*************** 定义错误信息 ***************/
- $errStr='{"status":-1,"info":"Request Error"}';
- $errJson=json_decode($errStr,true); //json_decode转成了array数组
- //print_r($errJson) //转成了array数组
- /************** 获取客户端的Origin域名 **************/
- $origin=isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:'';
- /******** 定义符合规则的域名数组 ********/
- $allow_origin=array(
- 'http://liuxinxiu.com',
- 'http://code.liuxinxiu.com',
- 'http://test.liuxinxiu.com'
- );
- /****************** 判断如果有POST过来数据 *********************/
- if(isset($_POST['name'])&&isset($_POST['gender'])){
- /********** 只要是POST请求过来无论合法与否都要正常通信 **********/
- header('Access-Control-Allow-Methods:POST');
- header('Access-Control-Allow-Headers:x-requested-with,content-type');
- /******** 匹配客户端域名是否在数组列表中 ******/
- if(in_array($origin,$allow_origin)){
- header('Access-Control-Allow-Origin:'.$origin);
- $res['status']=1;
- $res['getUser']=$arr;
- echo json_encode($res);
- }
- else if(!in_array($origin,$allow_origin)){
- /******** 如有设置就取设置URL返回头信息 ********/
- if(isset($origin_URL)){
- header('Access-Control-Allow-Origin:'.$origin_URL);
- $res['status']=1;
- $res['getUser']=$arr;
- echo encode_json($res);
- //echo json_encode("中文", JSON_UNESCAPED_UNICODE);
- }
- /******** 如没有设置URL就返回错误信息 ********/
- else{
- header('Access-Control-Allow-Origin:'.$origin);
- $errJson['status']=-1;
- $errJson['info']="You don't have permission to submit!";
- echo encode_json($errJson);
- }
- }
- }
- /************ 没有所匹配的POST提交数据 ***********/
- else{
- if($GLOBALS['HTTP_RAW_POST_DATA']){
- header('Access-Control-Allow-Origin:'.$origin);
- $errJson['status']=-1;
- $errJson['info']="Syntax error in parameters or arguments.";
- echo encode_json($errJson);
- }
- else{
- header("Content-type: text/html; charset=utf-8");
- echo 'It is forbidden for the URL request!';
- }
- }
- ?>
PHP数据提交接口地址 (禁止使用GET访问):http://code.liuxinxiu.com/php/Interface/server.php
配合HTML代码如下:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8"/>
- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
- <meta name="format-detection"content="telephone=no">
- <meta name="apple-mobile-web-app-capable" content="yes" />
- <meta name="apple-mobile-web-app-status-bar-style" content="black" />
- <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>
- <title>跨域测试</title>
- </head>
- <body>
- <h1 id="show"></h1>
- <input type="button" value="Click me" onclick="msg()" />
- </body>
- <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
- <script type='text/javascript'>
- /********** 获取URL参数 **********/
- function getQueryString(name){
- var reg=new RegExp("(^|&)"+name+"=([^&]*)(&|$)","i");
- var r=window.location.search.substr(1).match(reg);
- if (r!=null) return unescape(r[2]); return null;
- }
- /********** 发起Ajax请求 **********/
- function msg(){
- /******* 动态切换提交数据 *******/
- if(_origin){
- if(_name&&_gender){
- var data={name:_name,gender:_gender,origin:_origin};
- }
- else{
- var data={name:"xiaoming",gender:"male",origin:_origin};
- }
- }
- else if(_error==null){
- var data={name:"xiaoming",gender:"male"};
- }
- else if(_error){
- var data={xxx:111};
- }
- /******* 动态设置提交URL *******/
- if(_url){
- var urlPath=_url;
- }
- else{
- var urlPath='http://code.liuxinxiu.com/php/Interface/server.php';
- }
- $.ajax({
- type:'post',
- url:urlPath,
- data:data,
- cache:false,
- dataType:'json',
- success:function(data){
- if(data.name){
- document.getElementById("show").innerHTML=data.name+' '+data.gender;
- }
- else if(data.status!=1){
- document.getElementById("show").innerHTML=data.info;
- }
- },
- error:function(){
- console.log("请求错误//")
- }
- });
- };
- /***********************************************************************************************
- $.post("http://www.server.com/server.php",{name:"fdipzone",gender:"male"}).done(function(data){
- document.getElementById("show").innerHTML=data.name+' '+data.gender;
- });
- **********************************************************************************************/
- </script>
- </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
PHP处理HTTP请求的几种方式
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']中。
php [urlencode urldecode] 函数
urlencode()编码:对字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数,空格则编码为加号(+)。
php基于GD库,绘制PNG图像Demo
- <?php
- //创建画布,返回一个资源类型的变量$image,并在内存中开辟一个临时区域
- $image = imagecreatetruecolor(400,400); //创建画布大小为400x400
- //设置图像中所需的颜色,相当于在画画时准备的染料盒
- $white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); //为图像分配颜色为白色
- $gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0); //为图像分配颜色为灰色
- $darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90); //为图像分配颜色为暗灰色
- $navy = imagecolorallocate($image, 0x00, 0x00, 0x80); //为图像分配颜色为深蓝色
- $darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50); //为图像分配颜色为暗深蓝色
- $red = imagecolorallocate($image, 0xFF, 0x00, 0x00); //为图像分配颜色为红色
- $darkred = imagecolorallocate($image, 0x90, 0x00, 0x00); //为图像分配颜色为暗红色
- imagefill($image, 0, 0, $white); //为画布背景填充背景颜色
- //动态制作3D效果
- for ($i=220;$i>200;$i--){ //循环10次画出立体效果
- imagefilledarc($image, 200, $i, 400, 200, -160, 40, $darknavy, IMG_ARC_PIE);
- imagefilledarc($image, 200, $i, 400, 200, 40, 75, $darkgray, IMG_ARC_PIE);
- imagefilledarc($image, 200, $i, 400, 200, 75, 200, $darkred, IMG_ARC_PIE);
- }
- imagefilledarc($image, 200, 200, 400, 200, -160, 40, $navy, IMG_ARC_PIE); //画一椭圆弧且填充
- imagefilledarc($image, 200, 200, 400, 200, 40 , 75, $gray, IMG_ARC_PIE); //画一椭圆弧且填充
- imagefilledarc($image, 200, 200, 400, 200, 75, 200, $red, IMG_ARC_PIE); //画一椭圆弧且填充
- imagestring($image, 20, 100, 230, '34.7%', $white); //水平地画一行字符串,依次是F/X/Y/--数值越大向右、向下
- imagestring($image, 20, 200, 150, '55.5%', $white); //水平地画一行字符串,依次是F/X/Y/--数值越大向右、向下
- //向浏览器中输出一个GIF格式的图片
- header('Content-type:image/png'); //使用头函数告诉浏览器以图像方式处理以下输出
- imagepng($image); //向浏览器输出
- imagedestroy($image); //销毁图像释放资源
- //header("Content-type: text/html; charset=utf-8");
- //$str="<div>'$image'</div>";
- //echo $str;
- ?>
gd-png.php
- <?php
- //创建画布,返回一个资源类型的变量$image,并在内存中开辟一个临时区域
- $image = imagecreatetruecolor(375,375); //创建画布大小为375x375 iPhone6 375X627
- //设置图像中所需的颜色,相当于在画画时准备的染料盒
- $white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); //为图像分配颜色为白色
- $gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0); //为图像分配颜色为灰色
- $darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90); //为图像分配颜色为暗灰色
- $navy = imagecolorallocate($image, 0x00, 0x00, 0x80); //为图像分配颜色为深蓝色
- $darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50); //为图像分配颜色为暗深蓝色
- $red = imagecolorallocate($image, 0xFF, 0x00, 0x00); //为图像分配颜色为红色
- $darkred = imagecolorallocate($image, 0x90, 0x00, 0x00); //为图像分配颜色为暗红色
- imagefill($image, 0, 0, $white); //为画布背景填充背景颜色
- //动态制作3D效果
- for ($i=200;$i>180;$i--){ //循环10次画出立体效果
- imagefilledarc($image, 187, $i, 360, 180, -160, 40, $darknavy, IMG_ARC_PIE); //
- imagefilledarc($image, 187, $i, 360, 180, 40, 75, $darkgray, IMG_ARC_PIE);
- imagefilledarc($image, 187, $i, 360, 180, 75, 200, $darkred, IMG_ARC_PIE);
- }
- imagefilledarc($image, 187, 180, 360, 180, -160, 40, $navy, IMG_ARC_PIE); //画一椭圆弧且填充,第一个187-180 是错开7像素
- imagefilledarc($image, 187, 180, 360, 180, 40 , 75, $gray, IMG_ARC_PIE); //画一椭圆弧且填充
- imagefilledarc($image, 187, 180, 360, 180, 75, 200, $red, IMG_ARC_PIE); //画一椭圆弧且填充
- imagestring($image, 20, 180, 130, '55.5%', $white); //水平地画一行字符串,依次是F/X/Y/--数值越大向右、向下
- imagestring($image, 20, 100, 200, '34.7%', $white); //水平地画一行字符串,依次是F/X/Y/--数值越大向右、向下
- //向浏览器中输出一个GIF格式的图片
- //header("Content-type:text/html;charset=utf-8"); // 设置页面的编码风格
- header('Content-type:image/png'); //使用头函数告诉浏览器以图像方式处理以下输出--通知浏览器输出的是图像
- imagepng($image); //向浏览器输出
- imagedestroy($image); //销毁图像释放资源
- //header("Content-type: text/html; charset=utf-8");
- //$str="<div>'$image'</div>";
- //echo $str;
- ?>
JAVA循环数组输出HTML代码片段并对字符串进行base64编码
- <%@page trimDirectiveWhitespaces="true"%>
- <%@page language="java" pageEncoding="utf-8"%>
- <%@page import="sun.misc.*"%>
- <%@page import="java.io.*"%>
- <%@page import="java.util.*"%>
- <%
- List<String> htmltempList=new ArrayList<String>();
- //String[][] students = {{'小明','1101','23','52819911'},{'夏利','1101','23','52819911'},{'小强','1102','21','52819901'}};
- //创建6行4列二位数组
- String[][] book=new String [6][4];
- book[0]=new String[]{"风清扬","1101","23","52819911"};
- book[1]=new String[]{"许志飞","1101","23","52819911"};
- book[2]=new String[]{"令狐冲","1102","21","52819901"};
- book[3]=new String[]{"任我行","1103","22","52819991"};
- book[4]=new String[]{"任盈盈","1104","24","52819981"};
- book[5]=new String[]{"东方不败","1105","26","52819981"};
- String[][] arr1={{"11","22"},{"aaa","bbb"},{"AAA","BBB"}};
- String[][] arr2=new String[3][2];
- for(int i=0;i<book.length;i++){
- htmltempList.add("<ul>");
- for(int j=0;j<book[i].length;j++){
- //out.println(book[i][j]);
- htmltempList.add("<li>" +book[i][j]+"</li>");
- }
- htmltempList.add("</ul>");
- }
- /*
- int [][]a=new int[8][8];
- for (int i=0;i<8;i++){
- for(int j=0;j<8;j++){
- a[i][j]=i+j;
- out.println(a[i][j]+"---");
- }
- }*/
- //out.println("---");
- %>
- <%
- for (int i=0;i<9;i++){
- //htmltempList.add("<li><span>" + i+"</span></li>");
- }
- /*
- for (int i=0; i<htmltempList.size();i++){
- out.print(htmltempList.get(i));
- }
- out.print(testCol(htmltempList) + "====================");
- */
- %>
- <%
- response.setContentType("text/json");
- response.setCharacterEncoding("utf-8");
- String callback=request.getParameter("Jsoncallback");
- if(callback!=null&&!"".equals(callback)){
- out.print(callback+"({\"dataList\":\"" +testColCon(htmltempList) + "\"})");
- }
- %>
- <%!
- public static int testCol(List<String> testList){
- return testList.size();
- }
- public static String testColCon(List<String> testList){
- String str="";
- 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>";
- for (int i=0; i<testList.size();i++){
- str+=testList.get(i);
- }
- html+=str;
- byte[] b=null;
- String s=null;
- try{
- b=html.getBytes("utf-8");
- }catch(UnsupportedEncodingException e){
- e.printStackTrace();
- }
- if (b!=null){
- s=new BASE64Encoder().encode(b);
- s=s.replaceAll("\r\n","");
- s=s.replaceAll("\n","");
- // s = s.replaceAll("","");
- //s="PGxpPjxzcGFuPjA8L3NwYW4+PC9saT48bGk+PHNwYW4+MTwvc3Bhbj48L2xpPjxsaT48c3Bhbj4yPC9zcGFuPjwvbGk+PGxpPjxzcGFuPjM8L3NwYW4+PC9saT48bGk+PHNwYW4+NDwvc3Bhbj48L2xpPjxsaT48c3Bhbj41PC9zcGFuPjwvbGk+PGxpPjxzcGFuPjY8L3NwYW4+PC9saT48bGk+PHNwYW4+Nzwvc3Bhbj48L2xpPjxsaT48c3Bhbj44PC9zcGFuPjwvbGk+";
- }
- return s;
- }
- %>
php循环数组输出HTML代码片段并对字符串进行base64编码
- <?php
- //公共声明
- header('Content-type: text/json');
- html_entity_decode($string, ENT_QUOTES, 'UTF-8');
- //回调参数设置
- $param="Jsoncallback";
- $callback=$_REQUEST[$param];
- $students=array(
- array("风清扬","1101","23","52819911"),
- array("许志飞","1101","23","52819911"),
- array("令狐冲","1102","21","52819901"),
- array("任我行","1103","22","52819991"),
- array("任盈盈","1104","24","52819981"),
- array("东方不败","1105","26","52819981")
- );
- $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>';
- foreach($students as $v){
- $tempBegin.='
- <ul>
- <li>'.$v[0].'</li>
- <li>'.$v[1].'</li>
- <li>'.$v[2].'</li>
- <li>'.$v[3].'</li>
- </ul>
- ';
- }
- $tempEnd=$tempBegin.'</div>';
- //echo $tempEnd;
- $str1=base64_encode($tempEnd);
- $str2='{"dataList":"'.$str1.'"}';
- $jsonStr=$callback."(".$str2.")";
- //判断请求参数存在就会输出Json数据
- //if(isset($callback)&&!empty($callback)){
- if(isset($callback)){
- echo $jsonStr;
- }
- //判断请求参数不存在就输出错误信息
- if(!isset($callback)){
- header("Content-type: text/html; charset=utf-8");
- $str="<h1>400 Required String parameter '{$param}' is not present</h1><hr /><small>http Request with error params: none callback function</small>";
- echo $str;
- }
- ?>