php 发送手机短信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq635968970/article/details/43154919

原理:使用别的提过的接口发送手机短信

第一步.  在http://www.ihuyi.com/申请一个账号密码

第二步, 上代码

<?php

class NMobile{
	private $_user;
	private $_pwd;
	private $_type;
	private $_url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
	/**
	* 初始化用户密码
	* @access public
	* @param  string  $user   用户名
	* @param  string  $pwd    密码
	* @param  int     $type   0:post ,非0:get
	*/
	public function __construct($user, $pwd, $type = 0){
		$this->_user = $user;
		$this->_pwd  = $pwd;
		$this->_type = $type;
	}
	/**
	* 说明及描述
	* @access public
	* @param  int         $mobile   手机号码
	* @param  string,int  $msg       消息 跟模板对应
	* @return string   操作结果
	*/
	public function send($mobile, $msg){
		if(!function_exists('curl_init')){
			return '请先开启curl扩展';
		}
		$url = $this->_url;
		$mobile = ceil($mobile);
		$user = $this->_user;
		$pwd  = $this->_pwd;
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_HEADER, false);
		$data = "account={$user}&password={$pwd}&mobile=".$mobile."&content=".rawurlencode("您的验证码是:".$msg."。请不要把验证码泄露给其他人。");;
		//--------------post方式---
		if(!$this->_type){
			curl_setopt($curl, CURLOPT_NOBODY, true);
			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}else{ //---------get方式
			$url .= '&'.$data;
		}
		curl_setopt($curl, CURLOPT_URL, $url);
		$xml = curl_exec($curl);
		curl_close($curl);
		var_dump($xml);
		$result = $this->xml_to_array($xml);
		return $result['SubmitResult']['msg'];
	}
	/**
	* 官方xml解析
	* @access public
	* @param  string   $xml   xml数据
	* @return string   结果
	*/
	private function xml_to_array($xml){
		$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
		if(preg_match_all($reg, $xml, $matches)){
			$count = count($matches[0]);
			for($i = 0; $i < $count; $i++){
			$subxml= $matches[2][$i];
			$key = $matches[1][$i];
				if(preg_match( $reg, $subxml )){
					$arr[$key] = $this->xml_to_array( $subxml );
				}else{
					$arr[$key] = $subxml;
				}
			}
		}
		return $arr;
	}
}
header('Content-type:text/html; charset=utf-8');
$obj = new NMobile('你的账号', '你的密码'); //设置网站账户密码
echo $obj->send(13004868899, 1000, 1);	//发送消息
?>




猜你喜欢

转载自blog.csdn.net/qq635968970/article/details/43154919