首页 > 编程技术 > php

PHP进程锁类PHPLock程序代码

发布时间:2016-11-25 15:40

为了更好的控制php程序同时操作的一些问题我整理了一个进程锁的类我们可以利用这个进程锁实现程序的控制

程序代码如下

 代码如下 复制代码

<?php
//+----------------------------------------------
//|    Usage:
//+----------------------------------------------
//|    public function _initialize(){
//|        import('@.Util.PHPLock');
//|
//|        if(PHPLock::islocked()){
//|            echo "[+] Status: Locked\n";
//|            echo "[+] Exit\n";
//|            exit();
//|        }else{
//|            echo "[+] Status: Unlocked\n";
//|            echo "[-] Locking Now\n";
//|            PHPLock::lock();
//|        }
//|    }
//|
//|    function __destruct(){
//|        if(true === PHPLock::unlock()){
//|            echo "[+] Unlock Success\n";
//|        }
//|    }
//+----------------------------------------------
class PHPLock
{
    const PHPLOCK_TIMEOUT = 1200;
    static private $pid = null;
   
    static public function lock(){
        $key = self::__getKey();
        self::$pid = time();
        F($key, self::$pid);
        return true;
    }
   
    static public function unlock(){
        $key = self::__getKey();
        if(self::$pid){
            F($key, null);
            return true;
        }
        return;
    }
   
    static public function islocked(){
        $key = self::__getKey();
        $time = F($key);

        if(!$time){
            return false;
        }elseif(time() - $time >= self::getTimeout()){
            self::unlock();
            return false;
        }else{
            return true;
        }
    }
   
    static public function getTimeout(){
        $key = str_replace(self::__getKey(), '_Lock', '_TIMEOUT');
        $expire = C($key) ? C($key) : self::PHPLOCK_TIMEOUT;
        return $expire;
    }
   
    static private function __getKey(){
        return (defined('GROUP_NAME') ? GROUP_NAME.'_' : '') . MODULE_NAME . '_' . ACTION_NAME . '_Lock';
    }
}
?>

网页返回状态代码很多站长会去查自己网站状态码是不是200或错误页面是不是404代码了,那么我们使用最多的查看方法就是使用站长工具或ff浏览器来查,但有很多朋友不知道可以自己写一个查看状态代码的功能哦。

方法一,使用 fsockopen

严重鄙视curl_getinfo!

 代码如下 复制代码

function get_http_code($url="localhost", $port=80, $fsock_timeout=10){
    set_time_limit(0);
    ignore_user_abort(true);
 
    // 记录开始时间
    list($usec, $sec) = explode(" ", microtime(true));
    $timer['start'] = (float)$usec + (float)$sec;
 
    // 校验URL
    if(!preg_match("/^https?:\/\//i", $url)){
        $url = "http://".$url;
    }
    // 支持HTTPS
    if(preg_match("/^https:\/\//i", $url)){
        $port = 443;
    }
 
    // 解析URL
    $urlinfo = parse_url($url);
    if(empty($urlinfo['path'])){
        $urlinfo['path'] = '/';
    }
    $host = $urlinfo['host'];
    $uri = $urlinfo['path'] . (empty($urlinfo['query'])?'':$urlinfo['query']);
 
    // 通过fsock打开连接
    if(!$fp = fsockopen($host, $port, $errno, $error, $fsock_timeout)){
        list($usec, $sec) = explode(" ", microtime(true));
        $timer['end'] = (float)$usec + (float)$sec;
        $usetime = (float)$timer['end'] - (float)$timer['start'];
 
        return array('code'=>-1, 'usetime'=>$usetime);
    }
 
    // 提交请求
    $status = socket_get_status($fp);
    $out = "GET {$uri} HTTP/1.1\r\n";
    $out .= "Host: {$host}\r\n";
    $out .= "Connection: Close\r\n\r\n";
    $write = fwrite($fp, $out);
    if(!$write){
        list($usec, $sec) = explode(" ", microtime(true));
        $timer['end'] = (float)$usec + (float)$sec;
        $usetime = (float)$timer['end'] - (float)$timer['start'];
 
        return array('code'=>-2, 'usetime'=>$usetime);
    }
 
    $ret = fgets($fp, 1024);
    preg_match("/http\/\d\.\d\s(\d+)/i", $ret, $m);
    $code = $m[1];
    fclose($fp);
 
    list($usec, $sec) = explode(" ", microtime(true));
    $timer['end'] = (float)$usec + (float)$sec;
    $usetime = (float)$timer['end'] - (float)$timer['start'];
 
    return array('code'=>$code, 'usetime'=>$usetime);
}

file_get_contents 是 fsockopen 功能的简单打包,效率稍低些,但是抓取成功率很高,所以在 snoopy 出问题的时候我一般那他来。5.0.0 添加了对 context 的支持,有了context,他也可以发送 header 信息,自定义用户 agent, referer, cookies 都不在话下。5.1.0 添加了 offset 和 maxlen 参数,可以只读文件的一部分内容。

方法二,使用snoopy.class.php

Snoopy是一个php类,用来模拟浏览器的功能,可以获取网页内容,发送表单。

 代码如下 复制代码

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.spiegel.de/');
curl_setopt($ch, CURLOPT_RANGE, '0-500');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
/**
*But as noted before if the server doesn't honor this header but sends the whole file curl will download all of it. E.g. http://www.111cn.net ignores the header. But you can (in addition) set a write function callback and abort the request when more data is received, e.g.
* php 5.3+ only
* use function writefn($ch, $chunk) { ... } for earlier versions
*/
$writefn = function($ch, $chunk) {
  static $data='';
  static $limit = 500; // 500 bytes, it's only a test
  $len = strlen($data) + strlen($chunk);
  if ($len >= $limit ) {
    $data .= substr($chunk, 0, $limit-strlen($data));
    echo strlen($data) , ' ', $data;
    return -1;
  }
  $data .= $chunk;
  return strlen($chunk);
};
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.111cn.net/');
curl_setopt($ch, CURLOPT_RANGE, '0-500');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $writefn);
$result = curl_exec($ch);
curl_close($ch);

一些常见的状态码为:

200 - 服务器成功返回网页
404 - 请求的网页不存在
503 - 服务器超时
301 - 页面重定向

$_FILES与move_uploaded_file就可以在php代码中实现文件或图片上传了,这个比起很多编程语言来讲php上传功能是最简单最好用的了,下面来看个上传图片工作代码。
 代码如下 复制代码


<?php
 session_start();
 ?>
 <html xmlns="http://www.111cn.net/ 1999/xhtml">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>PHP上传文件</title>
 <style>
 * {margin:0; padding:0; list-style:none;}
 .content {width:400px; height:200px; margin:0 auto; margin-top:60px;

background:#ffd3b6; border:dashed 1px #f90}
 .content h1 { width:400px; height: 30px; line-height:30px; text-align:

center; font-family:"微软雅黑"; font-size:14px; color:#000}
 .content .error {width:300px; height:30px; line-height:30px;

text-align:center; margin:0 auto; color:#f00}
 .content .con {width:340px; height:auto; margin:0 auto; font-size:12px;}
 .content #file { width:280px; height:20px; border:solid 1px #ccc;

background:#fff; margin:10px 0px 6px 0; font-size:12px;}
 .content #send { width:60px; height:22px; border:solid 1px #ccc;

background:#fff; font-size:12px; margin-top:10px;}
 </style>
 </head>

<body>
 <div>
 <h1>文件上传</h1>
 <div>
 <div>
 <?php
 if ($_GET['up']==up) {
 if ($_SESSION['file']==$_GET['irand']) {
 $_size=20000;                    //设置限制文件大小
 $_dir='phone/';                   //文件保存目录
 function size($_size) {
 //判断文件大小是否大于1024bit 如果大于,则将大小取值为KB
 if ($_size>1024*1024) {
 return round($_size/1024/1024,2).' MB';
 }else if ($_size>1024) {
 $_size=$_size/1024;
 return ceil($_size).'KB';
 }else {
 return $_size.' bit';
 }
 }
 //设置上传图片的类型,设置图片上传大小
 $_upfiles = array('image/jpeg','image/pjpeg','image/png','image/x-png','image/gif');
 if (is_array($_upfiles)) {
 if (!in_array($_FILES['userfile']['type'],$_upfiles)) {
 exit('请上传格式为:jpg,png,gif的文件<br /><a href="upload.php">返回</a>');
 }
 }
 if ($_FILES['userfile']['size']>$_size) {
 exit('上传文件不能超过:'.size($_size));
 }
 if ($_FILES['userfile']['error']>0) {
 switch ($_FILES['userfile']['error']) {
 case 1: echo '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
 break;
 case 2: echo '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
 break;
 case 3: echo '文件只有部分被上传';
 break;
 case 4: echo '没有文件被上传';
 break;
 case 6: echo '找不到临时文件夹';
 break;
 case 7: echo '文件写入失败';
 break;
 }
 exit;
 }
 //获取文件扩展名
 if (!is_dir($_dir)) {
 mkdir($_dir,0700);
 }
 $_rand=mt_rand(0,100000);
 $_n=explode('.',$_FILES['userfile']['name']);  //将文件名分割
 $_file_len=count($_n);         //返回数组长度
 $_name=$_dir.time().'_'.$_rand.'.'.$_n[$_file_len-1];

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
 if (!@move_uploaded_file($_FILES['userfile']['tmp_name'],$_name)) {
 exit('文件移动失败');
 }else {
 echo '文件上传成功<br />';
 echo '文件路径:'.$_name.'<br />';
 echo '文件大小:'.size(filesize($_name));
 echo '<br /><a href="upload.php">返回继续上传</a>';
 }
 }else {
 exit('上传的临时文件不存在,无法将文件移动到指定文件夹');
 }
 //销毁session变量,有几种方法
 //第一种,销毁所有session变量:session_destroy();
 //第二种:销毁单个如:$_SESSION['file']=''
 session_destroy();
 exit;
 }else {
 exit('您已经提交过了,不能重复提交<br /><a href="upload.php">返回</a>');
 }
 }
 ?>
 </div>
 <?php $_irand=mt_rand(0,1000000); $_SESSION['file']=$_irand; ?>
 <form action="?up=up&irand=<?php echo $_irand; ?>" method="post" enctype="multipart/form-data">
 <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
 <input type="file" name="userfile" id="file"/><br />
 <input type="submit" name="send" value=" 点击上传 " id="send"/>
 </form>
 </div>
 </div>
 </body>
 </html>

清除字符串中空白或空格我们可以使用ereg_replace函数进行替换了,下面给大家整理了一个页面希望对各位有帮助。

去除所有空白

 代码如下 复制代码
function delete($str) {
    $str = trim($str);
    $str = ereg_replace("\t","",$str);
    $str = ereg_replace("\r\n","",$str);
    $str = ereg_replace("\r","",$str);
    $str = ereg_replace("\n","",$str);
    $str = ereg_replace("    ","",$str);
    return trim($str);
}

去除所有注释用preg_replace()函数把注释替换成空(是空,不是空格)。
 去掉字符串中的空格 str_replace(' ','',$cat_name)

 代码如下 复制代码
 
$str = ” This line contains\tliberal \r\n use of   whitespace.\n\n”;
$str = trim($str);// 首先去掉头尾空格
$str = preg_replace(’/\s(?=\s)/’, ‘’, $str);// 接着去掉两个空格以上的
$str = preg_replace(’/[\n\r\t]/’, ‘ ‘, $str);// 最后将非空格替换为一个空格

使用上面的例子可以去掉所有多余的空格。
首先使用TRim()去头尾空格,
接着用preg_replace()去掉重复的空格。
当中的(?=)表示只匹配后面的空格跟随前面的空格的空格。
 

 代码如下 复制代码

<?php
$str1="   tt 七夕快乐!nr"; //这里定义一个字符变量,其中包括"空格","t", 水平制表符,"n",换行符
//这里主要调用trim()函数去除空格等,trim()函数用于去除字符中的""空格,"t"水平制表符"n"换行符,"r"回车符
//"\0"字符串结束符,"xOB"垂直制表符。如果想通过此函数过滤掉特殊的字符,可以制定第二个参数。
echo trim($str1)."<br>";
//这里是去除$str1变量中带有tt的字符
echo trim($str1," tt")."<br>";
//定义变量$str2其中包括"."和空格
$str2="... 情人节快乐!...   中国...";
//调用trim()函数去除$str2变量中的空格
echo trim($str2)."<br>";
//ltrim()函数用于去除字符串左边的空格或指定字符串,其默认的字符同trim一样。因为这里指定了第二个参数,
//所以只去除$str2变量中左边的"."
echo ltrim($str2,".")."<br>";
//ltrim()函数用于去除字符串(右)边的空格或指定字符串,其默认的字符同trim一样。因为这里指定了第二个参数,
//所以只去除$str2变量中左边的"."
echo rtrim($str2,".")."<br>";
?>

<?php
echo substr("today is father day!",0)."<br>";
echo substr("today is father day!",6,2)."<br>";//这里只截取字符串中第6字符开始截取,并只截取2个字符
echo substr("today is father day!",-5,5)."<br>";//这里从字符串的倒数第5个字符开始截取,截取5个字符
echo substr("today is father day!",0,-5)."<br>";//这里只截取字符串中的首个字符开始截取,截取到字符串的倒数第5个
echo substr("today is father day!",-5,-1)."<br>";//这里从字符串的倒数第5个字符开始截取,截取倒数第一个字符
?>

补充一个:php注释和去除空格

 代码如下 复制代码


/**
 * 去除代码中的空白和注释
 * @param string $content 代码内容
 * @return string
 */
function strip_whitespace($content) {
    $stripStr   = '';
    //分析php源码
    $tokens     = token_get_all($content);
    $last_space = false;
    for ($i = 0, $j = count($tokens); $i < $j; $i++) {
        if (is_string($tokens[$i])) {
            $last_space = false;
            $stripStr  .= $tokens[$i];
        } else {
            switch ($tokens[$i][0]) {
                //过滤各种PHP注释
                case T_COMMENT:
                case T_DOC_COMMENT:
                    break;
                //过滤空格
                case T_WHITESPACE:
                    if (!$last_space) {
                        $stripStr  .= ' ';
                        $last_space = true;
                    }
                    break;
                case T_START_HEREDOC:
                    $stripStr .= "<<<THINK\n";
                    break;
                case T_END_HEREDOC:
                    $stripStr .= "THINK;\n";
                    for($k = $i+1; $k < $j; $k++) {
                        if(is_string($tokens[$k]) && $tokens[$k] == ';') {
                            $i = $k;
                            break;
                        } else if($tokens[$k][0] == T_CLOSE_TAG) {
                            break;
                        }
                    }
                    break;
                default:
                    $last_space = false;
                    $stripStr  .= $tokens[$i][1];
            }
        }
    }
    return $stripStr;
}

大多数据站长做留言板功能都会与数据库连接起来了,今天我们给大家分享一个基于xml留言板程序了。

php中操作xml文档我们会使用SimpleXMLElement函数,我们先了解一下SimpleXMLElement函数用法
SimpleXML 函数允许您把 XML 转换为对象。
通过普通的属性选择器或数组迭代器,可以处理这个对象,就像处理任何其他对象一样。

例子

xml文档格式

 代码如下 复制代码

<?php
error_reporting(E_ALL ^ E_NOTICE);
$op=$_GET['op'];
$op || $op='list';

$filename='guestbook.xml';
if(is_file($filename)){
 $gb=simplexml_load_file($filename);
}else{
 $gb=new SimpleXMLElement("<?xml version='1.0' encoding='utf-8'?><guestbook></guestbook>");
}
if($op=='list'){
 header("Content-Type:text/html;charset=utf-8");
 if(is_object($gb)){
echo "<table>";
echo "<tr><th>ID</th><th>用户</th><th>标题</th><th>标题</th><th>内容</th><th>时间</th><th>IP</th></tr>";
foreach($gb->item as $v){
 echo "<tr>";
 echo "<td>".htmlspecialchars($v->id)."</td><td>".htmlspecialchars($v->user)."</td><td>".htmlspecialchars($v->title)."</td><td>".htmlspecialchars($v->content)."</td><td>".date("Y-m-d H:i",intval($v->time))."</td><td>".htmlspecialchars($v->ip)."</td>";
}
echo '<table>';
 }
 echo "<div><a href='guestbook.php?op=add'>添加</a></div>";
}elseif($op=='save'){
 if(@$_POST['user']){
$user=$_POST['user'];
$title=$_POST['title'];
$content=$_POST['content'];

/*
$id=@count($gb->item);
$nextid=$id+1;
*/
$nextid=1;
foreach($gb->item as $v){
 $idarr[]=(int)$v->id;
}
$nextid=max($idarr)+1;
$item=$gb->addChild('item');
$item->addChild("id",$nextid);
$item->addChild('user',$user);
$item->addChild('title',$title);
$item->addChild('content',$content);
$item->addChild('time',time());
$item->addChild('ip',$_SERVER['REMOTE_ADDR']);
$gb->asXML($filename);
//跳转页,中间页
header("Location: guestbook.php?op=list");
die;
 }
}elseif($op=='add'){
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
 <title>Document</title>
</head>
<body>
<form action="guestbook.php?op=save" method="post">
<div>用户:<input type="text" name="user"></div>
<div>标题:<input type="text" name="title"></div>
<div>留言:<textarea name="content" id="" cols="30" rows="10"></textarea></div>
<div><input type="submit"  value="提交留言"></div>
</form>
</body>
</html>
<?php
}
?>

标签:[!--infotagslink--]

您可能感兴趣的文章: