php脚本读写文件发送短信记录结果

main.php

<?php

include 'config.php';

$myfile = fopen("Content.txt", "r") or die("Unable to open file!");
$content = fread($myfile,filesize("Content.txt"));
fclose($myfile);

$fp = fopen('TelephoneNumber.txt', 'r');
$myfile = fopen("Result.txt", "w") or die("Unable to open file!");

while (!feof($fp)) {
    $number = trim(fgets($fp));
    $res = send_sms(YUN_PIAN_API_KEY, $content, $number);
    echo $res;
    $res = json_decode($res, true);
    $writeResult = '';

    if ($res["code"] != 0) {
        $writeResult = $number . ' : ' . "fail to send message!\n";
    } else {
        $writeResult = $number . ' : ' . "send message successfully!\n";
    }

    fwrite($myfile, $writeResult);
}
fclose($myfile);
fclose($fp);

/**
* 智能匹配模版接口发短信
* apikey 为云片分配的apikey
* text 为短信内容
* mobile 为接受短信的手机号
*/
function send_sms($apikey, $text, $mobile){
    $encoded_text = urlencode("$text");
    $mobile = urlencode("$mobile");
    $post_string="apikey=$apikey&text=$encoded_text&mobile=$mobile";
    return sock_post(YUN_PIAN_URL, $post_string);
}

/**
* url 为服务的url地址
* query 为请求串
*/
function sock_post($url,$query){
    $data = "";
    $info=parse_url($url);
    $fp=fsockopen($info["host"],80,$errno,$errstr,30);
    if(!$fp){
        return $data;
    }
    $head="POST ".$info['path']." HTTP/1.0\r\n";
    $head.="Host: ".$info['host']."\r\n";
    $head.="Referer: http://".$info['host'].$info['path']."\r\n";
    $head.="Content-type: application/x-www-form-urlencoded\r\n";
    $head.="Content-Length: ".strlen(trim($query))."\r\n";
    $head.="\r\n";
    $head.=trim($query);
    $write=fputs($fp,$head);
    $header = "";
    while ($str = trim(fgets($fp,4096))) {
        $header.=$str;
    }
    while (!feof($fp)) {
        $data .= fgets($fp,4096);
    }
    return $data;
}

?>


config.php

<?php

define('YUN_PIAN_API_KEY', 'your api key');
define('YUN_PIAN_URL', 'http://yunpian.com/v1/sms/send.json');

?>


TelephoneNumber.txt

your phone number (one line one number)


Content.txt

【UFS】恭喜您成功註冊。立即回答2個問題,可獲得25元蛋糕券!?


最后打开终端切换至相应目录下输入 php main.php

你可能感兴趣的:(PHP,读写文件,发送短信)