Archive for April, 2012

作者:AngryFox 分类: Uncategorized April 26th, 2012 暂无评论

(以下命令都在Mysql5.5中测试通过)
Mysql修改列类型语句如下:
alter table 表名 change 列名 列名 要修改的列类型;
Mysql修改列名语句如下:
alter table 表名 change 列名 要修改的列名 原来的类型;
Mysql添加一列:
alter table 表名 add column 要加的列名 要加的列名类型;
MYsql删除一列:
alter table 表名 drop column 要删除的列名;
再来说一下,Mysql函数,存储过程,触发器的那些事。
创建一个mysql函数命令如下:
create function 函数名(参数名 参数类型)returns 返回类型
begin
statement;
end;
示例如下:
create function gets(s int)returns int
begin
declare a int; //mysql中声明变量不需要@!!!跟其他数据库不太一样!!切记!!!
set @a=3; //每句之后需加一个;不然报错!!!
return @a+s; //要有返回语句!!!
end;
下面就可以直接调用了:gets(3);
再说存储过程,创建存储过程命令如下:
create procedure 存储过程名(参数名 参数类型)returns 返回类型
begin
statement;
end;
存储过程和函数里面内容差不多,不过在调用的时候,存储过程需要这样调用:
call 存储过程名;就ok了!
再多说一句,因为函数可以返回一个表对象,所以可以在sql语句中直接调用函数,而存储过程不行!!!
下面说一下触发器;
在写触发器之前先建立两个表:
create table Student(studentId int primary key auto_increment,name varchar(30))engine=’InnoDB’;
create table BorrowBook(BorrowBookId int primary key auto_increment,studentId int)engine=’InnoDB’;
在更新一个学生的学号时,学号更新相应的借书记录的学生学号;
创建更新触发器如下:
create trigger updateTrigger before update on Student for each row
begin
update BorrowBook set studentId=NEW.studentId where studentId = Student.studentId;
end
在删除一个学生记录时,需要删除相应的借书记录
create trigger deleteTrigger before delete on Student for each row
begin
delete from BorrowRecord where studentId=OLD.studentId;
end
以后只要你更新学生表或者删除学生的某个记录时,就会调用触发器程序了!!!
最后,再说一下几个数据库的一点区别:
Mysql中使用auto_increment,而在sql server中使用identity;
Mysql中需要显式调用engine=’InnoDB’来使数据库实现事务功能,而在oracle中是自动提交的!
sql server 中使用触发器时,会使用deleted和inserted表,而在mysql中是NEW 和OLD表;

作者:AngryFox 分类: Uncategorized April 25th, 2012 暂无评论
/**
 * http post
 */
function httpRequest($url, $post_string, $connectTimeout = CONNECT_TIMEOUT, $readTimeout = READ_TIMEOUT) {
    $result = "";
    if (function_exists('curl_init')) {
        $timeout = $connectTimeout + $readTimeout;
        // Use CURL if installed...
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connectTimeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_USERAGENT, '139.com API PHP5 Client 1.1 (curl) ' . phpversion());
        $result = curl_exec($ch);
        curl_close($ch);
    } else {
        // Non-CURL based version...
        $result = socketPost($url, $post_string, $connectTimeout = CONNECT_TIMEOUT, $readTimeout = READ_TIMEOUT);
    }
    echo "url:$url <br /> post_data:$post_string <br /> ret:$result";
//	echo "<pre>";
//	print_r(htmlentities($post_string) . "<br />");
//	print_r(htmlentities($result));
//	echo "</pre>";
    return $result;
}

/**
 * http post
 */
function socketPost($url, $post_string, $connectTimeout = CONNECT_TIMEOUT, $readTimeout = READ_TIMEOUT){
    $urlInfo = parse_url($url);
    $urlInfo["path"] = ($urlInfo["path"] == "" ? "/" : $urlInfo["path"]);
    $urlInfo["port"] = ($urlInfo["port"] == "" ? 80 : $urlInfo["port"]);
    $hostIp = gethostbyname($urlInfo["host"]);

    $urlInfo["request"] =  $urlInfo["path"]	.
        (empty($urlInfo["query"]) ? "" : "?" . $urlInfo["query"]) .
        (empty($urlInfo["fragment"]) ? "" : "#" . $urlInfo["fragment"]);

    $fsock = fsockopen($hostIp, $urlInfo["port"], $errno, $errstr, $connectTimeout);
    if (false == $fsock) {
        return false;
    }
    /* begin send data */
    $in = "POST " . $urlInfo["request"] . " HTTP/1.0\r\n";
    $in .= "Accept: */*\r\n";
    $in .= "User-Agent: 139.com API PHP5 Client 1.1 (non-curl)\r\n";
    $in .= "Host: " . $urlInfo["host"] . "\r\n";
    $in .= "Content-type: application/x-www-form-urlencoded\r\n";
    $in .= "Content-Length: " . strlen($post_string) . "\r\n";
    $in .= "Connection: Close\r\n\r\n";
    $in .= $post_string . "\r\n\r\n";

    stream_set_timeout($fsock, $readTimeout);
    if (!fwrite($fsock, $in, strlen($in))) {
        fclose($fsock);
        return false;
    }
    unset($in);

    //process response
    $out = "";
    while ($buff = fgets($fsock, 2048)) {
        $out .= $buff;
    }
    //finish socket
    fclose($fsock);
    $pos = strpos($out, "\r\n\r\n");
    $head = substr($out, 0, $pos);		//http head
    $status = substr($head, 0, strpos($head, "\r\n"));		//http status line
    $body = substr($out, $pos + 4, strlen($out) - ($pos + 4));		//page body
    if (preg_match("/^HTTP\/\d\.\d\s([\d]+)\s.*$/", $status, $matches)) {
        if (intval($matches[1]) / 100 == 2) {//return http get body
            return $body;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
作者:AngryFox 分类: Uncategorized April 18th, 2012 暂无评论

memcache存储空数组的问题;出现灵异数据;
Curl中开启SSL
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);

memcache中设置超过30天时,时间会变成unix初始时间戳,导致缓存失败

作者:AngryFox 分类: Uncategorized April 9th, 2012 暂无评论
header('Expires: 0');
header('Last-Modified: '. gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cahe, must-revalidate');
//ie专用
header('Cache-Control: post-chedk=0, pre-check=0', false);
//for HTTP/1.0
header('Pragma: no-cache');
作者:AngryFox 分类: Uncategorized April 9th, 2012 暂无评论
<?
class cryption {

	function en($str,$key) {
		$ret='';
		$str = base64_encode ($str);
		for ($i=0; $i<=strlen($str)-1; $i++){
			$d_str=substr($str, $i, 1);
			$int =ord($d_str);
			$int=$int^$key;
			$hex=strtoupper(dechex($int));
			$ret.=$hex;
		}
		return $ret;
	}

	function de($str,$key) {
		$ret='';
		for ($i=0; $i<=strlen($str)-1; 0){
			$hex=substr($str, $i, 2);
			$dec=hexdec($hex);
			$dec=$dec^$key;
			$ret.=chr($dec);
			$i=$i+2;
		}
		return base64_decode($ret);
	}

}

$cryption=new cryption;
?>
作者:AngryFox 分类: Uncategorized April 9th, 2012 暂无评论
1. exec执行系统命令

exec("ls -a", $out);

print_r($out);

2. php验证字段,验证邮箱

filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)

3.判断是否在集合中出现

in_array("hello", array("good","bad","hello"))//结果 true,找不到返回false

4. file_get_contents

读取文件内容,将文件内所有内容读入到串中。同样可以读入url,用于下载网页内容。

$res = file_get_contents(http://www.baidu.com);

5. str_replace

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

字符串替换echo str_replace("world","John","Hello world!")

输出 Hello John
作者:AngryFox 分类: Uncategorized April 9th, 2012 暂无评论
<?php
$file = get_file_address();// 文件的真实地址(支持url,不过不建议用url)   

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>
作者:AngryFox 分类: Uncategorized April 9th, 2012 暂无评论
<?
    function seo_uri (){
        $uri_arr = explode("/",trim($_SERVER['REQUEST_URI'],'/'));
        $web_root_str = strtr(WEB_ROOT,'/','\\');
        $root_path_arr = explode('\\',trim($web_root_str,'\\'));
        $root_path_count = count($root_path_arr);
        foreach($uri_arr as $key=>$val){
            if($val==$root_path_arr[$root_path_count-1]){
                $uri_arr_start = $key;
            }
        }
        if($uri_arr_start>='0'){
            $uri_new = array_slice($uri_arr,$uri_arr_start+1);
        }else{
            $uri_new = $uri_arr;
        }
        $uri['mod']=isset($_GET['mod'])?$_GET['mod']:(isset($uri_new['0'])?(!empty($uri_new['0'])?$uri_new['0']:"index"):"index");
        $uri['act']=isset($_GET['act'])?$_GET['act']:(isset($uri_new['1'])?(!empty($uri_new['1'])?$uri_new['1']:"index"):"index");
        if(count($uri_new)>2){
            $uri['uri'] = array_slice($uri_new,1);
        }
        return $uri;
    }
?>
作者:AngryFox 分类: Uncategorized April 9th, 2012 暂无评论

传说比mb_substr、mb_strlen效率高

主要原理是根据UTF-8的编码特点
0xxxxxxx
110xxxxx 10xxxxxx
1110xxxx 10xxxxxx 10xxxxxx
11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
来获取字符边界,从而确定一个字所占字节数,并处理成数组。
function str_split_utf8($str) {
	// place each character of the string into and array
	$split = 1;
	$array = array(); $len = strlen($str);
	for ( $i = 0; $i < $len; ){
		$value = ord($str[$i]);
		if($value > 0x7F){
			if($value >= 0xC0 && $value <= 0xDF)
				$split = 2;
			elseif($value >= 0xE0 && $value <= 0xEF)
				$split = 3;
			elseif($value >= 0xF0 && $value <= 0xF7)
				$split = 4;
			elseif($value >= 0xF8 && $value <= 0xFB)
				$split = 5;
			elseif($value >= 0xFC)
				$split = 6; 

		} else {
			$split = 1;
		}
		$key = '';
		for ( $j = 0; $j < $split; ++$j, ++$i ) {
			$key .= $str[$i];
		}
		$array[] = $key;
	}
	return $array;
} 
作者:AngryFox 分类: Uncategorized April 9th, 2012 暂无评论
function get_domain() {
    /* 协议 */
    $protocol = (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';

    /* 域名或IP地址 */
    if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
        $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
    } elseif (isset($_SERVER['HTTP_HOST'])) {
        $host = $_SERVER['HTTP_HOST'];
    } else {
        /* 端口 */
        if (isset($_SERVER['SERVER_PORT'])) {
            $port = ':' . $_SERVER['SERVER_PORT'];
            if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol)) {
                $port = '';
            }
        } else {
            $port = '';
        }

        if (isset($_SERVER['SERVER_NAME'])) {
            $host = $_SERVER['SERVER_NAME'] . $port;
        } elseif (isset($_SERVER['SERVER_ADDR'])) {
            $host = $_SERVER['SERVER_ADDR'] . $port;
        }
    }

    return $protocol . $host;
}