分类目录归档:PHP

PHP编程及配置相关的技术文章

Ubuntu 14.04升级到php7.1等版本

命令如下

add-apt-repository ppa:ondrej/php
apt-get update

apt-get remove php5-fpm php5-cli php5-dev -y

apt-get install php7.1 php7.1-cgi php7.1-cli  php7.1-dev php7.1-fpm php7.1-bcmath php7.1-bz2 php7.1-common php7.1-curl php7.1-gd php7.1-gmp php7.1-imap php7.1-json php7.1-mbstring php7.1-mcrypt php7.1-mysql php7.1-odbc php7.1-readline php7.1-soap php7.1-xml php7.1-xmlrpc php7.1-zip php7.1-opcache php-redis php-memcache php-memcached -y

service php7.1-fpm restart

php curl get/post 实例(含https)

最近使用php curl使用得比较的多,get、post都有使用,每次使用,都需要baidu一下示例,太不方便。现在记录下来。供自己以后使用参考。

get 方法

$url = "http://www.stamhe.com/index.php?a=b&c=d&e=f&g=" . urlencode('全仔');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	// 要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_HEADER, 0); // 不要http header 加快效率
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$output = curl_exec($ch);
curl_close($ch);
var_dump($output);

post 方法

$url = "http://www.stamhe.com/index.php";
$params = "a=b&c=d&e=f&g=" . urlencode('全仔');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	// 要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_HEADER, 0); // 不要http header 加快效率
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_TIMEOUT, 15);

curl_setopt($ch, CURLOPT_POST, 1);	// post 提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

$output = curl_exec($ch);
curl_close($ch);
var_dump($output);

当请求https的数据时,会要求证书,这时候,加上下面这两个参数,规避ssl的证书检查

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);	// https请求 不验证证书和hosts
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

php msgpack 试用

在@Laruence 的 http://www.laruence.com/2012/09/15/2779.html 这篇文章最后,看到他提到的msgpack已经进入pecl库进行维护,立马进行了试用。
安装

pecl install msgpack

这样安装会报如下的错误

Failed to download pecl/msgpack within preferred state "stable", latest release is version 0.5.2, stability "beta", use "channel://pecl.php.net/msgpack-0.5.2" to install

这是由于msgpack还没有稳定版本,使用错误提示中channel就可以了,如下:

pecl install  channel://pecl.php.net/msgpack-0.5.2

看到【You should add “extension=msgpack.so” to php.ini】这样的提示,即表示安装msgpack扩展成功,在php.ini加入

extension  = "msgpack.so"

重启php-fpm

kill -SIGUSR2  12345

测试例子

 'hequan',
	'key2' => 'stamhe',
	'key3' => '全!@#$%^&*()":?><|}{[]仔',
);

$packdata = msgpack_serialize($data);
var_dump($packdata);
printf("pack = [%s]\n", $packdata);

$new_data = msgpack_unserialize($packdata);
var_dump($new_data);

【转】给Eclipse PDT加入CodeIgniter框架的自动完成支持——支持CodeIgniter 2.1.0

给Eclipse PDT加入codeigniter框架的自动完成支持
http://blog.k-res.net/%E8%BD%AF%E4%BB%B6%E4%BD%BF%E7%94%A8/%E7%BB%99eclipse-pdt%E5%8A%A0%E5%85%A5codeigniter%E6%A1%86%E6%9E%B6%E7%9A%84%E8%87%AA%E5%8A%A8%E5%AE%8C%E6%88%90%E6%94%AF%E6%8C%81.html

1.给你的WEB项目加入:右键项目->Configure->Add PHP Support…

2.给CI_Model基类和CI_Controller基类加入以下代码,这两个文件的位置在2.1.0版本里是在system/core下,注意,注释部分不可无视!

/**
  * @var CI_Config
  */
 var $config;
 /**
  * @var CI_DB_active_record
  */
 var $db;
 /**
  * @var CI_Email
  */
 var $email;
 /**
  * @var CI_Form_validation
  */
 var $form_validation;
 /**
  * @var CI_Input
  */
 var $input;
 /**
  * @var CI_Loader
  */
 var $load;
 /**
  * @var CI_Router
  */
 var $router;
 /**
  * @var CI_Session
  */
 var $session;
 /**
  * @var CI_Table
  */
 var $table;
 /**
  * @var CI_Unit_test
  */
 var $unit;
 /**
  * @var CI_URI
  */
 var $uri;
 /**
  * @var CI_Pagination
  */
 var $pagination;

3.一切OK,试一下->应该有反应了。

codeigniter 2.0 添加自定义的类库以支持memcache

codeigniter 2.0 添加自定义的类库以支持memcache
1、将下面的代码文件放置到application/system/libraries/目录下

 array(
			'host'	=> '192.168.117.100',
			'port'	=> 11211,
		),
		'u'	=> array(
			'host'	=> '192.168.117.100',
			'port'	=> 11211,
		),
	);
	
	private $mem = NULL;
	
	function __construct()
	{
		$this->mem = new Memcache();
	}
	
	/**获取数据
	 * @param	key		键值(string,array('key1', 'key2')
	 * @param	type	业务类别(r,u)
	 * @return	false or string or array(
	 * 		'key1'	=> data1,
	 * 		'key2'	=> data2,
	 * )
	 * 
	 */
	function get($key, $type)
	{
		if(empty($key) || empty($type))
			return false;
			
		$this->mem->connect($this->server_list[$type]['host'], $this->server_list[$type]['port']);
		
		$ret_data = $this->mem->get($key);
		$this->mem->close();
		return $ret_data;
	}
	
	/** 设置cache
	 * @param	key		键(如果为数组,则表示设置多条cache,要求格式为array('key1' => data1, 'key2' => data2...),此时value不用设置)
	 * @param	type	业务类型(r/u/...)
	 * @param	value	值
	 * @param	expire	过期时间(秒)
	 * @return	true/false
	 */
	function  set($key, $type, $value  = NULL, $expire = 60)
	{
		if(empty($key) || empty($type) || (! is_array($key) && empty($value)))
			return false;
		
		$this->mem->connect($this->server_list[$type]['host'], $this->server_list[$type]['port']);
		if(is_array($key))
		{
			foreach ($key as $k => $v)
			{
				$this->mem->set($k, $v, 0, $expire);
			}
		}
		else
		{
			$this->mem->set($key, $value, 0, $expire);
		}
		
		$this->mem->close();
		return true;
	}
	
	/** 删除cache
	 * @param	key		键值(string,array('key1', 'key2'))
	 * @param	type	业务类型
	 * @param	timeout	超时时间
	 * @return	true/false
	 */
	function  del($key, $type, $timeout = 0)
	{
		if(empty($key) || empty($type))
			return false;
			
		$this->mem->connect($this->server_list[$type]['host'], $this->server_list[$type]['port']);
		if(is_array($key))
		{
			foreach ($key as $v)
			{
				$this->mem->delete($key, $timeout);
			}
		}
		else
			$this->mem->delete($key, $timeout);
			
		$this->mem->close();
		return true;
	}
	
}

2、在application/controllers下添加Cachetest类测试Cacheop类库

load->library('cacheop');
		$this->cacheop->set('1-stamhe', 'u', 'stamhe1', 86400);
		$this->cacheop->set('2-stamhe', 'u', 'stamhe2', 86400);
		$this->cacheop->set('3-stamhe', 'u', 'stamhe3', 86400);
		$this->cacheop->set(array('4-stamhe' => 'stamhe4', '5-stamhe' => 'stamhe5'), 'u', NULL, 86400);
	}
	
	function  get()
	{
		$this->load->library('cacheop');
		print_r($this->cacheop->get(array('1-stamhe', '2-stamhe', '3-stamhe', '4-stamhe', '5-stamhe'), 'u'));
	}
}

3、访问url【http://192.168.4.112/?c=cachetest&m=get】测试

codeigniter 2.0.2 中使用jquery ajax 框架

codeigniter 2.0.2 中使用jquery ajax 框架
http://www.ryantetek.com/2009/12/how-to-create-a-simple-ajax-post-in-codeigniter-using-jquery/
1、新增一个Ajax_post控制器,代码如下

load->helper(array('url'));
	}
	
	function index()
	{
		$data['baseurl'] = $this->config->item('base_url');
		$this->load->view('ajax_post', $data);
	}
	
	function post_action()
	{
		$message = "";
		$bg_color = "";
		if(($_POST['username'] == "") || ($_POST['password'] == ''))
		{
			$message = "Please fill up blank fields.";
			$bg_color = "#ffebe8";
		}
		else if($_POST['username'] != 'stamhe' || $_POST['password'] != '123456')
		{
			$message = "Username or Password do not match";
			$bg_color = "#ffebe8";
		}
		else
		{
			$message = "Username and Password matched";
			$bg_color = "FFA";
		}

		$output = array(
			'message'	=> $message,
			'bg_color'	=> $bg_color
		);
		
		echo json_encode($output);
	}
}

2、根据上面的控制器代码,新建名为ajax_post.php的视图文件,代码如下



	
		
		ci ajax demo
		
		
		
	
	
		

This is the demo page ofr the simple AJAX post in CodeIgniter Using jQuery

Username: stamhe | Password: 123456

Try to enter nothing in the fields and click the submit button.
Try to mismatch the username and/or password and click the submit button.

Username/Email:*

Password:*

3、在js目录下,新建名为ajax_post.js的javascript脚本文件,代码如下:

$(document).ready(function(){
	$("#login_submit").click(function(){
		var username = $("#username").val();
		var password = $("#password").val();
		
		$.ajax({
			type: 'post',
			dataType: 'json',
			cache: false,
			url: "http://192.168.4.112/ajax_post/post_action",
			data: 'username=' + username + '&password=' + password,
			success:
				function(data){
					$("#form_message").html(data.message).css({"background-color": data.bg_color}).fadeIn('slow');
				}
		});
		return false;
	});
});

4、访问http://192.168.4.112/?c=ajax_post&m=index进行测试

使codeigniter支持$_GET

使codeigniter支持$_GET
http://codeigniter.com/wiki/QUERY_STRING_GET/

1、打开config.php文件,将【url_protocol】设置为PATH_INFO,将【enable_query_strings】设置为TRUE

vim   application/config/config.php
$config['uri_protocol'] = 'PATH_INFO';
$config['enable_query_strings'] = TRUE;

2、在需要使用$_GET之前,添加上下面的代码即可使用$_GET来获取参数了

parse_str($_SERVER['QUERY_STRING'], $_GET);

示例:
http://192.168.4.112/?c=blog&m=loadget1&username=stamhe&pwd=123456
调用controller为blog的loadget1函数,在其中像下面这样获取username与pwd的分段参数

parse_str($_SERVER['QUERY_STRING'], $_GET);
echo "username: ".$_GET['username']."
"; echo "pwd: ".$_GET['pwd']."
";

PHP对MongoDB的基本操作

PHP对MongoDB的基本操作

selectDB($dbname);
	$collect=$db->selectCollection($tbname);

	$cursor=$collect->find();
	$num=1;
	foreach($cursor as $obj)
	{
		print "Num = $num"." user_id:".$obj["user_id"]." create_time:".$obj["create_time"]." msg_id:".$obj["msg_id"]."\n";
			
	}
	
	$conn->close();
	print "TOTAL TIME : ".(microtime(true)-$start)."\n";

Mongo类的基本成员函数接口
MongoClass

 TRUE) ]] )
	public array dropDB ( mixed $db )
	public MongoDB __get ( string $dbname )
	public array getHosts ( void )
	public string getSlave ( void )
	public bool getSlaveOkay ( void )
	public array listDBs ( void )
	public MongoCollection selectCollection ( string $db , string $collection )
	public MongoDB selectDB ( string $name )
	public bool setSlaveOkay ([ bool $ok ] )
	public string switchSlave ( void )
	public string __toString ( void )
}

php 手工安装MongoDB扩展

php安装mongodb扩展

git	clone	https://github.com/mongodb/mongo-php-driver.git
cd	mongo-php-driver
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make
make install

在/usr/local/php/etc/php.ini下添加

extension="mongo.so"

重启WEB服务器
查看mongo扩展信息,可以看到【MongoDB Support =>enabled】的字样

php -i|grep -i mongo

使用下面的测试脚本测试mongo的php扩展是否可用

	error_reporting(E_ALL|E_STRICT);
	ini_set("display_errors","on");
	
	// 开始时间
	$start=microtime(true);

	// 数据库前缀,表名
	define("MONGODB","10.245.75.74");
	define("MONGOPORT",65431);

	// 连接Mongo
	$server="mongodb://".MONGODB.":".MONGOPORT;
	$conn=new Mongo($server);
	if($conn===false)
	{
		print "Mongo() fail\n";
		exit(-1);
	}

	$dbname="db2_si_0_0";
	$tbname="t_si_0";
	$db=$conn->selectDB($dbname);
	$collect=$db->selectCollection($tbname);

	$cursor=$collect->find();
	$num=1;
	foreach($cursor as $obj)
	{
		print "Num = $num"." user_id:".$obj["user_id"]." create_time:".$obj["create_time"]." msg_id:".$obj["msg_id"]."\n";
			
	}
	
	$conn->close();
	print "TOTAL TIME : ".(microtime(true)-$start)."\n";