<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PHP &#8211; LPC影子技术分享</title>
	<atom:link href="https://www.mudbest.com/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.mudbest.com</link>
	<description>行影不离,忘之却步.</description>
	<lastBuildDate>Thu, 16 Nov 2023 09:37:45 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.2</generator>
	<item>
		<title>php5.4升php7.3踩坑之路</title>
		<link>https://www.mudbest.com/php5-4%e5%8d%87php7-3%e8%b8%a9%e5%9d%91%e4%b9%8b%e8%b7%af/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Fri, 12 Mar 2021 18:24:51 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[分享]]></category>
		<category><![CDATA[Mysql]]></category>
		<category><![CDATA[mysql5.7]]></category>
		<category><![CDATA[php5升级php7]]></category>
		<category><![CDATA[php7]]></category>
		<guid isPermaLink="false">https://www.mudbest.com/?p=2200</guid>

					<description><![CDATA[6年没有更新博客了，近期计划内项目有一些web服务底层基于php7+、mysql5.7+开发的，而服务器的ph ... <a title="php5.4升php7.3踩坑之路" class="read-more" href="https://www.mudbest.com/php5-4%e5%8d%87php7-3%e8%b8%a9%e5%9d%91%e4%b9%8b%e8%b7%af/" aria-label="阅读 php5.4升php7.3踩坑之路">阅读更多</a>]]></description>
										<content:encoded><![CDATA[
<blockquote class="wp-block-quote is-style-default is-layout-flow wp-block-quote-is-layout-flow">
<p>6年没有更新博客了，近期计划内项目有一些web服务底层基于php7+、mysql5.7+开发的，而服务器的php版本停留在了5.4一直未更新(mysql.5.5)，导致环境无法部署，考虑到运行的服务比较关键致使升级的计划一而再被拖延。</p>
</blockquote>

<p>&nbsp;</p>
<p>&nbsp;</p>

<p class="wp-block-paragraph">这次决定将php5.4和mysql5.5升级至php7.3和mysq5.7做个记录，希望能帮助到其他类似需要升级的人。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>先说一下版本情况：</p>
<cite>centos6.8，php5.4，mysql5.7</cite></blockquote>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph"><strong>升级php7.3过程比较简单。</strong></p>



<p class="wp-block-paragraph">1、安装epel源</p>


<pre><pre class="brush: bash; title: ; notranslate">
yum install epel-release
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">2、加载remirepo的php源(注意：centos7不是用这个源)</p>


<pre><pre class="brush: bash; title: ; notranslate">
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">2、安装php7.3</p>


<pre><pre class="brush: bash; title: ; notranslate">
yum --enablerepo=remi-php73 install php
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">3、安装主要扩展包</p>


<pre><pre class="brush: bash; title: ; notranslate">
yum --enablerepo=remi-php73 install php-xml php-soap php-xmlrpc php-mbstring php-json php-gd php-mcrypt php-fpm
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">4、安装完成后，重启php-fpm</p>


<pre><pre class="brush: bash; title: ; notranslate">
kill -USR2 `cat /var/run/php-fpm/php-fpm.pid`
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">5、以下非必要</p>


<pre><pre class="brush: bash; title: ; notranslate">
yum update
</pre>



<p class="wp-block-paragraph">至此，php7.3安装完成，此处我遇到1个关于mysqli扩展的问题，默认php-fpm的配置是加载了mysqli的，但是不知道为什么我查看phpinfo是没有mysqli扩展信息的，后来在php.ini里开启了mysqli扩展才识别了，不知道其他人有没有遇到。</p>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph"><strong>接着就是升级mysql5.4至mysql5.7了。</strong></p>



<p class="wp-block-paragraph">首先备份数据库，升级MySQL通常不会丢失数据，但保险起见，我们需要做这一步。</p>



<p class="wp-block-paragraph">这种方式备份的侧重点是库与表，备份文件里面会有use db_name这样的语句，方便于恢复数据时知道要把表创建到哪个数据库。</p>


<pre><pre class="brush: bash; title: ; notranslate">
mysqldump -uroot -p &#x5B;--no-data] --databases db_name1 db_name2 &amp;amp;amp;amp;gt; /dir/backup.sql;  //--no-data指不备份数据，只备份库与表结构。
</pre>


<pre><pre class="brush: bash; title: ; notranslate">
mysqldump -u xxx -h xxx -P 3306 -p --all-databases &amp;amp;amp;amp;gt; databases.sql;   // 备份所有库
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">1、备份完数据库之后，开始卸载旧版本 MySQL</p>


<pre><pre class="brush: bash; title: ; notranslate">
yum remove mysql mysql-*
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">2、确认mysql是否卸载完全</p>


<pre><pre class="brush: bash; title: ; notranslate">
yum list installed | grep mysql
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">3、上面的情况是没有未删除部分，如果有的话可通过下面的命令删除：</p>


<pre><pre class="brush: bash; title: ; notranslate">
yum remove mysql－libs
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">4、查看系统版本</p>


<pre><pre class="brush: bash; title: ; notranslate">
&#x5B;root@iZbp18bpfv23id1yoiv3f0Z include]# uname -r
2.6.32-754.35.1.el6.x86_64
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">5、mysql官方源太慢了，这里用第三方源(<a href="http://mirrors.sohu.com/mysql/MySQL-5.7/" target="_blank" rel="noreferrer noopener" data-type="URL" data-id="http://mirrors.sohu.com/mysql/MySQL-5.7/">传送门</a>)</p>



<p class="wp-block-paragraph">//贴图</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="824" height="635" class="wp-image-2203" src="https://www.mudbest.com/wp-content/uploads/2021/03/mysql-1.png" alt="" srcset="https://www.mudbest.com/wp-content/uploads/2021/03/mysql-1.png 824w, https://www.mudbest.com/wp-content/uploads/2021/03/mysql-1-558x430.png 558w, https://www.mudbest.com/wp-content/uploads/2021/03/mysql-1-768x592.png 768w" sizes="(max-width: 824px) 100vw, 824px" /></figure>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">6、然后根据自己系统配置选择对应的 rpm 包(我这里下载的是5.7.23)，鼠标右键打开复制链接，然后到软件包目录执行下载命令</p>


<pre><pre class="brush: bash; title: ; notranslate">
wget http://mirrors.sohu.com/mysql/MySQL-5.7/mysql-5.7.23-1.el6.x86_64.rpm-bundle.tar
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">7、解压包</p>


<pre><pre class="brush: bash; title: ; notranslate">
tar -zcvf mysql-5.7.23-1.el6.x86_64.rpm-bundle.tar
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">8、安装rpm以及相关依赖</p>


<pre><pre class="brush: bash; title: ; notranslate">
yum localinstall mysql-community-common-5.7.23-1.el6.x86_64.rpm
</pre>


<pre><pre class="brush: bash; title: ; notranslate">
yum localinstall mysql-community-libs-5.7.23-1.el6.x86_64.rpm
</pre>


<pre><pre class="brush: bash; title: ; notranslate">
yum localinstall mysql-community-client-5.7.23-1.el6.x86_64.rpm
</pre>


<pre><pre class="brush: bash; title: ; notranslate">
yum localinstall mysql-community-server-5.7.23-1.el6.x86_64.rpm
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">9、OK安装完成，查看版本</p>


<pre><pre class="brush: bash; title: ; notranslate">
&#x5B;root@*** include]# mysql -V
mysql  Ver 14.14 Distrib 5.7.23, for Linux (x86_64) using  EditLine wrapper
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">10、重启mysql</p>


<pre><pre class="brush: bash; title: ; notranslate">
service mysqld start
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">11、如果重启mysql失败，初始化数据库。</p>


<pre><pre class="brush: bash; title: ; notranslate">
mysqld --initialize
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">12、基于mysql5.7的安全机制有变更，默认mysql是有密码的，查看默认密码。</p>


<pre><pre class="brush: bash; title: ; notranslate">
&#x5B;root@******************* include]# grep 'temporary password' /var/log/mysqld.log
2021-03-09T10:52:05.394381Z 1 &#x5B;Note] A temporary password is generated for root@localhost: *****?4#v
2021-03-09T10:54:04.766642Z 1 &#x5B;Note] A temporary password is generated for root@localhost: *****zyc6/(
2021-03-09T10:55:15.770123Z 1 &#x5B;Note] A temporary password is generated for root@localhost: *****Vy!y0!h
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">13、还是基于安全，默认登录到mysql命令控制台，执行任何有效命令都会提示重新设置密码。</p>


<pre><pre class="brush: bash; title: ; notranslate">
mysql -&amp;amp;amp;amp;amp;gt; select host from mysql.user where User='root';
ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">14、修改密码(5.7的密码验证要求高，密码过于简单会提示错误)</p>


<pre><pre class="brush: bash; title: ; notranslate">
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('123456');
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">15、密码过于简单报错</p>


<pre><pre class="brush: bash; title: ; notranslate">
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">16、最后让修改生效执行</p>


<pre><pre class="brush: bash; title: ; notranslate">
flush privileges;
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">至此，mysql的安装以及配置完成，剩下就是进入控制台 source导入上面备份的数据库就行了。</p>



<p class="wp-block-paragraph">==================================================我是分割线</p>



<p class="wp-block-paragraph">踩坑开始：</p>



<p class="wp-block-paragraph">由于论坛(<a href="https://bbs.mudbest.com" target="_blank" rel="noreferrer noopener">https://bbs.mudbest.com</a>)是基于discuz7.2开发的，很多函数在php7.3被废弃了甚至会报错，php7.3和mysql5.7升级完成之后，然后一脸懵逼。。论坛挂了。。。无法访问。</p>



<p class="wp-block-paragraph">现在回过头看discuz7的代码(无法言喻。。)，打开php-fpm的运行错误，在php-fpm.conf内添加以下内容，然后打开error_log就可以看到运行的错误信息了</p>


<pre><pre class="brush: bash; title: ; notranslate">
&#x5B;www]
catch_workers_output = yes
</pre>



<p class="wp-block-paragraph">坑整理：<br />1、set_magic_quotes_runtime 报致命错误。<br />2、ob_start('ob_gzhandler') 报致命错误。<br />3、preg_replace 带evel的 报致命错误。<br />4、php7 session不能传递的解决方案<br />5、….各种告警(修了70%，剩下30%不想修了，直接改告警登记屏蔽了，哈哈)</p>



<p class="wp-block-paragraph"><strong>关于问题3、4 的解决方式：</strong><br />1、针对 preg_replace evel替代方案就是将 全站用到 evel的换成preg_replace_callback，来个例子。</p>


<pre><pre class="brush: php; title: ; notranslate">
$message = preg_replace(&quot;/\s?&#x5B;code](.+?)&#x5B;\/code]\s?/ies&quot;, &quot;codedisp('\1')&quot;, $message);
</pre>



<p class="wp-block-paragraph">改写成</p>


<pre><pre class="brush: php; title: ; notranslate">
$message = preg_replace_callback(
&quot;/\s?&#x5B;code](.+?)&#x5B;\/code]\s?/is&quot;,
function ($matches) {
return codedisp($matches&#x5B;1]);
},
$message
);
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph"><em>扩展知识：</em></p>


<pre><pre class="brush: php; title: ; notranslate">
//适合单一任务
$template = preg_replace_callback( //处理eval
    &quot;/&#x5B;\n\r\t]*\{eval\s+(.+?)\}&#x5B;\n\r\t]*/is&quot;,
    function ($matches) { return str_replace(&quot;\\\&quot;&quot;, &quot;\&quot;&quot;, preg_replace(&quot;/\&amp;amp;amp;amp;amp;lt;\?\=(\\\$.+?)\?\&amp;amp;amp;amp;amp;gt;/s&quot;, &quot;\\1&quot;, &quot;&amp;amp;amp;amp;amp;lt;? $matches&#x5B;1] ?&amp;amp;amp;amp;amp;gt;&quot;)); },
    $template
);
 
//需要同一正则处理多个任务时  &#x5B;推荐]
function stripvtags($expr) {
    $expr = str_replace(&quot;\\\&quot;&quot;, &quot;\&quot;&quot;, preg_replace(&quot;/\&amp;amp;amp;amp;amp;lt;\?\=(\\\$.+?)\?\&amp;amp;amp;amp;amp;gt;/s&quot;, &quot;\\1&quot;, $expr));
    return $expr;
}
$template = preg_replace_callback( //处理eval
    &quot;/&#x5B;\n\r\t]*\{eval\s+(.+?)\}&#x5B;\n\r\t]*/is&quot;,
    function ($matches) { return stripvtags(&quot;&amp;amp;amp;amp;amp;lt;? $matches&#x5B;1] ?&amp;amp;amp;amp;amp;gt;&quot;); },
    $template
);
$template = preg_replace_callback( //处理echo
    &quot;/&#x5B;\n\r\t]*\{echo\s+(.+?)\}&#x5B;\n\r\t]*/is&quot;,
    function ($matches) { return stripvtags(&quot;&amp;amp;amp;amp;amp;lt;? echo $matches&#x5B;1] ?&amp;amp;amp;amp;amp;gt;&quot;); },
    $template
);
 
//与第一种差不多, 只不过是分开写
class Template {
    public function test() {
        $template = preg_replace_callback( //处理eval
            &quot;/&#x5B;\n\r\t]*\{eval\s+(.+?)\}&#x5B;\n\r\t]*/is&quot;,
            array($this, 'stripvtagsEval'),
            $template
        );
    }
    protected function stripvtagsEval($matches) {
        return str_replace(&quot;\\\&quot;&quot;, &quot;\&quot;&quot;, preg_replace(&quot;/\&amp;amp;amp;amp;amp;lt;\?\=(\\\$.+?)\?\&amp;amp;amp;amp;amp;gt;/s&quot;, &quot;\\1&quot;, &quot;&amp;amp;amp;amp;amp;lt;? $matches&#x5B;1] ?&amp;amp;amp;amp;amp;gt;&quot;)); 
    }
}
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">2、session问题只需要将php.ini内的session.use_trans_sid设置为1，并且将存放session的目录权限改为可写入。</p>


<pre><pre class="brush: bash; title: ; notranslate">
session.use_trans_sid=0
</pre>



<p class="wp-block-paragraph">&nbsp;</p>



<p class="wp-block-paragraph">改为</p>


<pre><pre class="brush: bash; title: ; notranslate">
session.use_trans_sid=1
</pre>

<p>&nbsp;</p>

<p class="wp-block-paragraph">&nbsp;</p>

<p>验证码无法显示的原因，可以看查看一下session.save_path目录的权限，默认这个目录是给apache，如果nginx启动用户非apache则无法写入session 默认session.save_page目录为/var/lib/php</p>
<pre><pre class="brush: bash; title: ; notranslate">
drwxrwx--- 2 root apache   6 Aug  4 02:40 opcache
drwxr-xr-x 2 root root   116 Nov 15 16:43 peclxml
drwxrwx--- 2 root apache   6 Aug  4 02:40 session
drwxrwx--- 2 root apache   6 Aug  4 02:40 wsdlcache
</pre></pre>
<p>我这里nginx改了启动用户，将www改成自己配置的用户组即可。20231116</p>
<pre><pre class="brush: bash; title: ; notranslate">
chown www:www /var/lib/php -R
</pre></pre>

<p class="wp-block-paragraph">至此，从升级配置直至填坑恢复，用了2天，又掉了不少头发，赶紧洗洗睡了。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>redis的hGetAll函数的性能问题</title>
		<link>https://www.mudbest.com/redis%e7%9a%84hgetall%e5%87%bd%e6%95%b0%e7%9a%84%e6%80%a7%e8%83%bd%e9%97%ae%e9%a2%98/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Wed, 14 Jan 2015 07:58:51 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[分享]]></category>
		<category><![CDATA[hGetAll]]></category>
		<category><![CDATA[redis]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=2112</guid>

					<description><![CDATA[在没关注这个函数之前，一直用的Memcache的数据存储方式，但是自从更换了redis之后，对于一个hash的 ... <a title="redis的hGetAll函数的性能问题" class="read-more" href="https://www.mudbest.com/redis%e7%9a%84hgetall%e5%87%bd%e6%95%b0%e7%9a%84%e6%80%a7%e8%83%bd%e9%97%ae%e9%a2%98/" aria-label="阅读 redis的hGetAll函数的性能问题">阅读更多</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">在没关注这个函数之前，一直用的Memcache的数据存储方式，但是自从更换了redis之后，对于一个hash的数据存与取 对于Memcache方便甚多，但是问题来了，一个hash的列表如果量不大的情况，用hGetAll函数几乎看不出问题，一旦这个列表超过50或者更多时，此时用hGetAll函数便能很直观的看到性能问题，这里就不作数据分析了。<br><br>Redis是单线程的！当它处理一个请求时其他的请求只能等着。通常请求都会很快处理完，但是当我们使用HGETALL的时候，必须遍历每个字段来获取数据，这期间消耗的CPU资源和字段数成正比，如果还用了PIPELINING，无疑更是雪上加霜。</p>



<span id="more-2112"></span>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
PERFORMANCE = CPUs / OPERATIONs
</pre></div>


<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">也就是说，此场景下为了提升性能，要么增加运算过程中的CPU数量；要么降低运算过程中的操作数量。在为了继续使用hash结构的数据，又要解决此问题，比较方便的方法就是将hash以序列化字符串存储，取的时候先取出反序列化的数据，再用hGet(key,array(hash..))。</p>



<p class="wp-block-paragraph">例如：</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
$arrKey = array(&#039;dbfba184bef630526a75f2cd073a6098&#039;,&#039;dbfba184bef630526a75f2cd0dswet98&#039;)
$strKey = &#039;test&#039;;
$obj-&gt;hmGet($strKey,$arrKey);
</pre></div>


<p class="wp-block-paragraph">把原本的hGetAll操作简化为hGet，也就是说，不再需要遍历hash中的每一个字段，因此即便不能让多个CPU参与运算，但是却大幅降低了操作数量，所以性能的提升仍然是显著的；当然劣势也很明显，和所有的冗余方式一样，此方案浪费了大量的内存。</p>



<p class="wp-block-paragraph">有人会问，这样虽然没有了遍历字段的过程，但是却增加了反序列化的过程，而反序列化的成本往往也是很高的，难道这样也能提升性能？问题的关键在于开始我们遍历字段的操作是在一个cpu上完成的，后来反序列化的操作，不管是什么语言，都可以通过多进程或多线程来保证是在多个cpu上完成的，所以性能总体上是提升的。</p>



<p class="wp-block-paragraph">另外，很多人直觉是通过运行redis多实例来解决问题。确实，这样可以增加运算过程中的CPU数量，有助于提升性能，但是需要注意的是，hGetAll和PIPELINING往往会让运算过程中的操作数量呈几何级爆炸式增长，相比之下，我们能增加的redis多实例数量简直就是杯水车薪，所以本例中这种方法不能彻底解决问题。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>PHP下的Redis使用与总结</title>
		<link>https://www.mudbest.com/php%e4%b8%8b%e7%9a%84redis%e4%bd%bf%e7%94%a8%e4%b8%8e%e6%80%bb%e7%bb%93/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Thu, 24 Apr 2014 04:21:44 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[分享]]></category>
		<category><![CDATA[redis]]></category>
		<category><![CDATA[缓存]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=2033</guid>

					<description><![CDATA[关于redis的介绍这里就不写了，百科就能查到，Redis是一个开源的使用ANSI C语言编写、支持网络、可基 ... <a title="PHP下的Redis使用与总结" class="read-more" href="https://www.mudbest.com/php%e4%b8%8b%e7%9a%84redis%e4%bd%bf%e7%94%a8%e4%b8%8e%e6%80%bb%e7%bb%93/" aria-label="阅读 PHP下的Redis使用与总结">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>关于redis的介绍这里就不写了，百科就能查到，Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库，并提供多种语言的API。</p>
<p><strong>一、利用PHP自带的libredis扩展库进行连接操作</strong><br />
<span id="more-2033"></span><br />
例一：</p>
<pre class="brush: php; title: ; notranslate">
$libredis = Libredis ();
$connection = $libredis-&gt;get_connection ( &quot;127.0.0.1&quot; );
// set a key
$batch = $libredis-&gt;create_batch ();
$batch-&gt;set ( 'hello', 'world' );
$batch-&gt;execute ( $connection );
// now fetch the key
$batch = $libredis-&gt;create_batch ();
$batch-&gt;get ( 'hello' );
$batch-&gt;execute ( $connection );
while ( $batch-&gt;next_reply ( $reply_type, $reply_value, $reply_length ) ) {
	echo $reply_value, PHP_EOL;
}
</pre>
<p>例二：</p>
<pre class="brush: php; title: ; notranslate">
$libredis = Libredis ();
$connection1 = $libredis-&gt;get_connection ( &quot;127.0.0.1:6379&quot; );
$connection2 = $libredis-&gt;get_connection ( &quot;127.0.0.1:6380&quot; );
$batch1 = $libredis-&gt;create_batch ();
$batch1-&gt;set ( 'hello', 'world' ); // add a 'set' command to batch1
$batch2 = $libredis-&gt;create_batch ();
$batch2-&gt;set ( 'hello2', 'world2' );
$executor = $libredis-&gt;create_executor ();
$executor-&gt;add ( $connection1, $batch1 ); // associate connection1 with batch1
$executor-&gt;add ( $connection2, $batch2 ); // associate connection2 with batch2
                                       // execute all batches against their corresponding connections in parallel, with a
                                       // 500 ms timeout on the whole operation.
$executor-&gt;execute ( 500 );
</pre>
<p><strong>二、远程连接redis并给redis加锁</strong></p>
<p>用法：redis-cli [OPTIONS] [cmd [arg [arg &#8230;]]]<br />
-h <主机ip>，默认是127.0.0.1<br />
-p <端口>，默认是6379<br />
-a <密码>，如果redis加锁，需要传递密码<br />
&#8211;help，显示帮助信息</p>
<p>通过对rendis-cli用法介绍，在192.168.99.44上连接192.168.99.39应该很简单：</p>
<pre class="brush: bash; title: ; notranslate">
&#x5B;root@hkshadow001 ~]# redis-cli -h 192.168.99.39 -p 6379 
redis 192.168.1.103:6379&gt; 
</pre>
<p>在192.168.99.44上对192.168.99.39设置个个string值 user.1.name=hkshadow</p>
<pre class="brush: bash; title: ; notranslate">
redis 192.168.1.103:6379&gt; set user.1.name hkshadow 
OK 
</pre>
<p>看到ok，表明设置成功了。然后直接在192.168.99.39上登陆，看能不能获取到这个值。</p>
<pre class="brush: bash; title: ; notranslate">
&#x5B;root@hkshadow001 ~]# redis-cli 
redis 127.0.0.1:6379&gt; get user.1.name 
&quot;hkshadow&quot; 
</pre>
<p>查看链接的用户这里显示的是hkshadow，说明192.168.99.44已经链接上了192.168.99.36，一般在内网进行redis链接相对是安全的，但在外网时需要加一个验证才是比较安全的，在这里设置一个账号验证。</p>
<pre class="brush: bash; title: ; notranslate">
&#x5B;root@hkshadow001 ~]# vim /etc/redis/6379.conf 
</pre>
<p>找到# requirepass foobared，去掉前面的注释&#8221;#&#8221;，并把foobared 替换为你自己的密码：&#8221;hi,redis&#8221;。<br />
保存配置文件之后，重启redis服务。</p>
<pre class="brush: bash; title: ; notranslate">
&#x5B;root@hkshadow001 ~]# /etc/init.d/redis_6379 stop  
Stopping ...  
Waiting for Redis to shutdown ...  
Redis stopped  
&#x5B;root@hkshadow001 ~]# /etc/init.d/redis_6379 start  
Starting Redis server... 
</pre>
<p>这时候再使用192.168.99.44连接192.168.99.39并获取user.1.name的值，看看发生什么。</p>
<pre class="brush: bash; title: ; notranslate">
&#x5B;root@linuxidc001 ~]# redis-cli -h 192.168.1.103 -p 6379  
redis 192.168.1.103:6379&gt; get user.1.name  
(error) ERR operation not permitted  
redis 192.168.1.103:6379&gt; 
</pre>
<p>报错了，因为刚刚增加了一个验证信息，需要以下操作。</p>
<pre class="brush: bash; title: ; notranslate">
redis 192.168.99.39:6379&gt; quit  
&#x5B;root@linuxidc001 ~]# redis-cli -h 192.168.1.103 -p 6379 -a &quot;hi,redis&quot;  //这里的之前配置里改的值
redis 192.168.99.39:6379&gt; get user.1.name  
&quot;hkshadow&quot; 
</pre>
<p><strong>三、redis-cli的使用</strong></p>
<p>TYPE key — 用来获取某key的类型<br />
KEYS pattern — 匹配所有符合模式的key，比如KEYS * 就列出所有的key了，当然，复杂度O(n)<br />
RANDOMKEY &#8211; 返回随机的一个key<br />
RENAME oldkey newkey — 改变key的名字<br />
SELECT: ./redis-cli select 6<br />
# 表示切换到数据库6  </p>
<pre class="brush: bash; title: ; notranslate">
SET: ./redis-cli -n 0 set nid 123456789 
# 表示向数据库0中插入字符串key为nid，value值为123456789  
</pre>
<pre class="brush: bash; title: ; notranslate">
GET: ./redis-cli -n 0 get nid 或者 ./redis-cli get nid 
# 表示获取数据库为0，key为nid的字符串，在不指定数据编号的情况下，默认连接的是0数据库，所以可以省略-n参数 
</pre>
<pre class="brush: bash; title: ; notranslate">
GETSET: ./redis-cli getset nid 987654321 
# 表示返回指定key的原始值，并指定一个新值给他 
</pre>
<pre class="brush: bash; title: ; notranslate">
MGET: ./redis-cli mget nid uid … 
# 表示获取多个key的值 
</pre>
<pre class="brush: bash; title: ; notranslate">
SETNX: ./redis-cli setnx nnid 888888 
# 表示当一个指定的key不存在时，设置这个key指定的value，如果存在，则设置不成功 
</pre>
<pre class="brush: bash; title: ; notranslate">
SETEX: ./redis-cli setex nid 5 666666 
# 表示设置一个key指定的value保存5秒后失效，设置key/value的有效期 
</pre>
<pre class="brush: bash; title: ; notranslate">
MSET: ./redis-cli mset nid0001 &quot;0001&quot; nid0002 &quot;0002&quot; nid0003 &quot;0003&quot;
# 表示多键值对的数据保存 
</pre>
<pre class="brush: bash; title: ; notranslate">
INCR: ./redis-cli incr count 
# 表示对给定key的value进行递增(+1)的操作,当然value必须是一个integer 
</pre>
<pre class="brush: bash; title: ; notranslate">
INCRBY: ./redis-cli incrby count 5 
# 表示对给定key的value进行指定步长的递增操作 
</pre>
<pre class="brush: bash; title: ; notranslate">
DECR: ./redis-cli decr count 
# 表示对给定key的value进行递减(-1)的操作 
</pre>
<pre class="brush: bash; title: ; notranslate">
DECRBY: ./redis-cli decrby count 7 
# 表示对给定key的value进行指定步长的递减操作 
</pre>
<pre class="brush: bash; title: ; notranslate">
APPEND: ./redis-cli append content &quot;bad&quot;   或者  ./redis-cli append content &quot;good&quot;
# 表示追加一个value到指定的key中，如果key不存在，则新建key 
</pre>
<pre class="brush: bash; title: ; notranslate">
SUBSTR: ./redis-cli substr content 0 4 
# 表示返回指定key的value的部分字符串
</pre>
<p># 列表操作，精华<br />
RPUSH key string — 将某个值加入到一个key列表末尾<br />
LPUSH key string — 将某个值加入到一个key列表头部<br />
LLEN key — 列表长度<br />
LRANGE key start end — 返回列表中某个范围的值，相当于mysql里面的分页查询那样<br />
LTRIM key start end — 只保留列表中某个范围的值<br />
LINDEX key index — 获取列表中特定索引号的值，要注意是O(n)复杂度<br />
LSET key index value — 设置列表中某个位置的值<br />
RPOP key </p>
<p># 集合操作<br />
SADD key member — 增加元素<br />
SREM key member — 删除元素<br />
SCARD key — 返回集合大小<br />
SISMEMBER key member — 判断某个值是否在集合中<br />
SINTER key1 key2 &#8230; keyN — 获取多个集合的交集元素<br />
SMEMBERS key — 列出集合的所有元素 </p>
<p><strong>四、删除redis所有KEY</strong><br />
Redis 中有删除单个 Key 的指令 DEL，但好像没有批量删除 Key 的指令，不过我们可以借助 Linux 的 xargs 指令来完成这个动作。</p>
<pre class="brush: bash; title: ; notranslate">
redis-cli keys &quot;*&quot; | xargs redis-cli del
//如果redis-cli没有设置成系统变量，需要指定redis-cli的完整路径
//如：/opt/redis/redis-cli keys &quot;*&quot; | xargs /opt/redis/redis-cli del
</pre>
<p>如果要指定 Redis 数据库访问密码，使用下面的命令：</p>
<pre class="brush: bash; title: ; notranslate">
redis-cli -a password keys &quot;*&quot; | xargs redis-cli -a password del
</pre>
<p>如果要访问 Redis 中特定的数据库，使用下面的命令：</p>
<pre class="brush: bash; title: ; notranslate">
//下面的命令指定数据序号为0，即默认数据库
redis-cli -n 0 keys &quot;*&quot; | xargs redis-cli -n 0 del
</pre>
<p>删除所有Key，可以使用Redis的flushdb和flushall命令</p>
<pre class="brush: bash; title: ; notranslate">
//删除当前数据库中的所有Key
flushdb
//删除所有数据库中的key
flushall
</pre>
<p>注：keys 指令可以进行模糊匹配，但如果 Key 含空格，就匹配不到了，暂时还没发现好的解决办法。</p>
<p><strong>五、redis-cli 命令总结</strong><br />
Redis提供了丰富的命令（command）对数据库和各种数据类型进行操作，这些command可以在Linux终端使用。<br />
在编程时，比如使用Redis 的Java语言包，这些命令都有对应的方法。下面将Redis提供的命令做一总结。</p>
<p><em>1、连接操作相关的命令</em><br />
quit：关闭连接（connection）<br />
auth：简单密码认证</p>
<p><em>2、对value操作的命令</em><br />
exists(key)：确认一个key是否存在<br />
del(key)：删除一个key<br />
type(key)：返回值的类型<br />
keys(pattern)：返回满足给定pattern的所有key<br />
randomkey：随机返回key空间的一个key<br />
rename(oldname, newname)：将key由oldname重命名为newname，若newname存在则删除newname表示的key<br />
dbsize：返回当前数据库中key的数目<br />
expire：设定一个key的活动时间（s）<br />
ttl：获得一个key的活动时间<br />
select(index)：按索引查询<br />
move(key, dbindex)：将当前数据库中的key转移到有dbindex索引的数据库<br />
flushdb：删除当前选择数据库中的所有key<br />
flushall：删除所有数据库中的所有key</p>
<p><em>3、对String操作的命令</em><br />
set(key, value)：给数据库中名称为key的string赋予值value<br />
get(key)：返回数据库中名称为key的string的value<br />
getset(key, value)：给名称为key的string赋予上一次的value<br />
mget(key1, key2,…, key N)：返回库中多个string（它们的名称为key1，key2…）的value<br />
setnx(key, value)：如果不存在名称为key的string，则向库中添加string，名称为key，值为value<br />
setex(key, time, value)：向库中添加string（名称为key，值为value）同时，设定过期时间time<br />
mset(key1, value1, key2, value2,…key N, value N)：同时给多个string赋值，名称为key i的string赋值value i<br />
msetnx(key1, value1, key2, value2,…key N, value N)：如果所有名称为key i的string都不存在，则向库中添加string，<br />
名称key i赋值为value i<br />
incr(key)：名称为key的string增1操作<br />
incrby(key, integer)：名称为key的string增加integer<br />
decr(key)：名称为key的string减1操作<br />
decrby(key, integer)：名称为key的string减少integer<br />
append(key, value)：名称为key的string的值附加value<br />
substr(key, start, end)：返回名称为key的string的value的子串</p>
<p><em>4、对List操作的命令</em><br />
rpush(key, value)：在名称为key的list尾添加一个值为value的元素<br />
lpush(key, value)：在名称为key的list头添加一个值为value的 元素<br />
llen(key)：返回名称为key的list的长度<br />
lrange(key, start, end)：返回名称为key的list中start至end之间的元素（下标从0开始，下同）<br />
ltrim(key, start, end)：截取名称为key的list，保留start至end之间的元素<br />
lindex(key, index)：返回名称为key的list中index位置的元素<br />
lset(key, index, value)：给名称为key的list中index位置的元素赋值为value<br />
lrem(key, count, value)：删除count个名称为key的list中值为value的元素。<br />
count为0，删除所有值为value的元素，count>0从头至尾删除count个值为value的元素，count<0从尾到头删除|count|个值为value的元素。 
lpop(key)：返回并删除名称为key的list中的首元素 rpop(key)：返回并删除名称为key的list中的尾元素 
blpop(key1, key2,… key N, timeout)：lpop命令的block版本。
即当timeout为0时，若遇到名称为key i的list不存在或该list为空，则命令结束。
如果timeout>0，则遇到上述情况时，等待timeout秒，如果问题没有解决，则对keyi+1开始的list执行pop操作。<br />
brpop(key1, key2,… key N, timeout)：rpop的block版本。参考上一命令。<br />
rpoplpush(srckey, dstkey)：返回并删除名称为srckey的list的尾元素，并将该元素添加到名称为dstkey的list的头部</p>
<p><em>5、对Set操作的命令</em><br />
sadd(key, member)：向名称为key的set中添加元素member<br />
srem(key, member) ：删除名称为key的set中的元素member<br />
spop(key) ：随机返回并删除名称为key的set中一个元素<br />
smove(srckey, dstkey, member) ：将member元素从名称为srckey的集合移到名称为dstkey的集合<br />
scard(key) ：返回名称为key的set的基数<br />
sismember(key, member) ：测试member是否是名称为key的set的元素<br />
sinter(key1, key2,…key N) ：求交集<br />
sinterstore(dstkey, key1, key2,…key N) ：求交集并将交集保存到dstkey的集合<br />
sunion(key1, key2,…key N) ：求并集<br />
sunionstore(dstkey, key1, key2,…key N) ：求并集并将并集保存到dstkey的集合<br />
sdiff(key1, key2,…key N) ：求差集<br />
sdiffstore(dstkey, key1, key2,…key N) ：求差集并将差集保存到dstkey的集合<br />
smembers(key) ：返回名称为key的set的所有元素<br />
srandmember(key) ：随机返回名称为key的set的一个元素</p>
<p><em>6、对zset（sorted set）操作的命令</em><br />
zadd(key, score, member)：向名称为key的zset中添加元素member，score用于排序。如果该元素已经存在，则根据score更新该元素的顺序。<br />
zrem(key, member) ：删除名称为key的zset中的元素member<br />
zincrby(key, increment, member) ：如果在名称为key的zset中已经存在元素member，则该元素的score增加increment；<br />
否则向集合中添加该元素，其score的值为increment<br />
zrank(key, member) ：返回名称为key的zset（元素已按score从小到大排序）中member元素的rank（即index，从0开始），<br />
若没有member元素，返回“nil”<br />
zrevrank(key, member) ：返回名称为key的zset（元素已按score从大到小排序）中member元素的rank（即index，从0开始），<br />
若没有member元素，返回“nil”<br />
zrange(key, start, end)：返回名称为key的zset（元素已按score从小到大排序）中的index从start到end的所有元素<br />
zrevrange(key, start, end)：返回名称为key的zset（元素已按score从大到小排序）中的index从start到end的所有元素<br />
zrangebyscore(key, min, max)：返回名称为key的zset中score >= min且score <= max的所有元素 
zcard(key)：返回名称为key的zset的基数 zscore(key, element)：返回名称为key的zset中元素element的
score zremrangebyrank(key, min, max)：删除名称为key的zset中rank >= min且rank <= max的所有元素 
zremrangebyscore(key, min, max) ：删除名称为key的zset中score >= min且score <= max的所有元素
zunionstore / zinterstore(dstkeyN, key1,…,keyN, WEIGHTS w1,…wN, AGGREGATE SUM|MIN|MAX)：对N个zset求并集和交集，
并将最后的集合保存在dstkeyN中。对于集合中每一个元素的score，在进行AGGREGATE运算前，都要乘以对于的WEIGHT参数。
如果没有提供WEIGHT，默认为1。默认的AGGREGATE是SUM，即结果集合中元素的score是所有集合对应元素进行SUM运算的值，而MIN和MAX是指，
结果集合中元素的score是所有集合对应元素中最小值和最大值。

<em>7、对Hash操作的命令</em><br />
hset(key, field, value)：向名称为key的hash中添加元素field<—>value<br />
hget(key, field)：返回名称为key的hash中field对应的value<br />
hmget(key, field1, …,field N)：返回名称为key的hash中field i对应的value<br />
hmset(key, field1, value1,…,field N, value N)：向名称为key的hash中添加元素field i<—>value i<br />
hincrby(key, field, integer)：将名称为key的hash中field的value增加integer<br />
hexists(key, field)：名称为key的hash中是否存在键为field的域<br />
hdel(key, field)：删除名称为key的hash中键为field的域<br />
hlen(key)：返回名称为key的hash中元素个数<br />
hkeys(key)：返回名称为key的hash中所有键<br />
hvals(key)：返回名称为key的hash中所有键对应的value<br />
hgetall(key)：返回名称为key的hash中所有的键（field）及其对应的value</p>
<p><em>8、持久化</em><br />
save：将数据同步保存到磁盘<br />
bgsave：将数据异步保存到磁盘<br />
lastsave：返回上次成功将数据保存到磁盘的Unix时戳<br />
shundown：将数据同步保存到磁盘，然后关闭服务</p>
<p><em>9、远程服务控制</em><br />
info：提供服务器的信息和统计<br />
monitor：实时转储收到的请求<br />
slaveof：改变复制策略设置<br />
config：在运行时配置Redis服务器</p>
<p>redis操作手册下载:<a href="http://www.mudbest.com/php%e4%b8%8b%e7%9a%84redis%e4%bd%bf%e7%94%a8%e4%b8%8e%e6%80%bb%e7%bb%93/php-redis%e4%b8%ad%e6%96%87%e5%b8%ae%e5%8a%a9%e6%89%8b%e5%86%8c/" rel="attachment wp-att-2036">php-redis中文帮助手册</a></p>
<p>相关文章：<br />
<a href="http://timyang.net/data/redis-misunderstanding/" title="Redis几个认识误区" target="_blank">Redis几个认识误区</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>使用google验证码防止注册机/发帖机for discuz7.2</title>
		<link>https://www.mudbest.com/%e4%bd%bf%e7%94%a8google%e9%aa%8c%e8%af%81%e7%a0%81for-discuz7-2/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Mon, 13 Jan 2014 09:43:37 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[分享]]></category>
		<category><![CDATA[discuz]]></category>
		<category><![CDATA[recaptcha]]></category>
		<category><![CDATA[验证码]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1986</guid>

					<description><![CDATA[http://bbs.mudbest.com目前已经采用google验证码方案，平时注册机/发帖机 盯得比较紧 ... <a title="使用google验证码防止注册机/发帖机for discuz7.2" class="read-more" href="https://www.mudbest.com/%e4%bd%bf%e7%94%a8google%e9%aa%8c%e8%af%81%e7%a0%81for-discuz7-2/" aria-label="阅读 使用google验证码防止注册机/发帖机for discuz7.2">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>http://bbs.mudbest.com目前已经采用google验证码方案，平时注册机/发帖机 盯得比较紧，点触验证码感觉还行，只是广告不太喜欢，看到google提供了一个验证码的接口。想到将将原来的discuz默认验证码更换掉成google的验证码，就是用户体验不怎么好。</p>
<p>1、首先到https://www.google.com/recaptcha/admin/create 注册应用。<br />
2、打开http://code.google.com/p/recaptcha/downloads/list?q=label:phplib-Latest ，下载接口文件。<br />
3、拿到注册应用后得到公用key和私有key。<br />
<span id="more-1986"></span><br />
<img decoding="async" src="http://www.mudbest.com/wp-content/uploads/2014/01/QQ截圖20140113191913.jpg" alt="google验证码" width="609" height="243" class="alignnone size-full wp-image-1996" /></p>
<p>代码修改部分：</p>
<pre class="brush: php; title: ; notranslate">
//打开discuz7.2的/include/common.inc.php文件。
require_once DISCUZ_ROOT.'./include/global.func.php';
//加载google验证码核心文件
//并设置好应用的 公有key 和 私有key
//&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;加载google验证码部分&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
require_once(DISCUZ_ROOT.'./include/recaptchalib.php');
$publickey = &quot;6LcC8-wSAAAAAHxRk***pMW12312krfNqscyC_C1&quot;;
$privatekey = &quot;6LcC8-wSAAAAADG***-Uy53434p0IKvgzGJG2toMD&quot;;
//&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;加载google验证码部分&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
</pre>
<p>打开discuz7.2的/include/global.func.php文件，将函数修改如下：</p>
<pre class="brush: php; title: ; notranslate">
function submitcheck($var, $allowget = 0, $seccodecheck = 0, $secqaacheck = 0) {
	$publickey = &quot;6LcC8-wSAAAAAHxRk***pMW12312krfNqscyC_C1&quot;;
        $privatekey = &quot;6LcC8-wSAAAAADG***-Uy53434p0IKvgzGJG2toMD&quot;;
	# the response from reCAPTCHA
	$resp = null;
	# the error code from reCAPTCHA, if any
	$error = null;
	
	if(empty($GLOBALS&#x5B;$var])) {
		return FALSE;
	} else {
		global $_SERVER, $seclevel, $seccode, $seccodedata, $seccodeverify, $secanswer, $_DCACHE, $_DCOOKIE, $timestamp, $discuz_uid;
		if($allowget || ($_SERVER&#x5B;'REQUEST_METHOD'] == 'POST' &amp;&amp; $GLOBALS&#x5B;'formhash'] == formhash() &amp;&amp; empty($_SERVER&#x5B;'HTTP_X_FLASH_VERSION']) &amp;&amp; (empty($_SERVER&#x5B;'HTTP_REFERER']) ||
			preg_replace(&quot;/https?:\/\/(&#x5B;^\:\/]+).*/i&quot;, &quot;\\1&quot;, $_SERVER&#x5B;'HTTP_REFERER']) == preg_replace(&quot;/(&#x5B;^\:]+).*/&quot;, &quot;\\1&quot;, $_SERVER&#x5B;'HTTP_HOST'])))) {
        		if($seccodecheck) {
                                
        				$resp = recaptcha_check_answer ($privatekey,
        						$_SERVER&#x5B;&quot;REMOTE_ADDR&quot;],
        						$_POST&#x5B;&quot;recaptcha_challenge_field&quot;],
        						$_POST&#x5B;&quot;recaptcha_response_field&quot;]);
        			
        				if (!$resp-&gt;is_valid) {
        					showmessage('submit_seccode_invalid');
        					//echo &quot;You got it!&quot;;
        				} 
        				/*
        				else {
        					# set the error code so that we can display it
        					$error = $resp-&gt;error;
        				}
        				*/
        			
        			/*
        			if(!$seclevel) {
        				$key = $seccodedata&#x5B;'type'] != 3 ? '' : $_DCACHE&#x5B;'settings']&#x5B;'authkey'].date('Ymd');
        				list($seccode, $expiration, $seccodeuid) = explode(&quot;\t&quot;, authcode($_DCOOKIE&#x5B;'secc'], 'DECODE', $key));
        				if($seccodeuid != $discuz_uid || $timestamp - $expiration &gt; 600) {
        					showmessage('submit_seccode_invalid');
        				}
        				dsetcookie('secc', '');
        			} else {
        				$tmp = substr($seccode, 0, 1);
        			}
        			seccodeconvert($seccode);
        			if(strtoupper($seccodeverify) != $seccode) {
        				showmessage('submit_seccode_invalid');
        			}
				$seclevel &amp;&amp; $seccode = random(6, 1) + $tmp * 1000000;
				
				*/
        		}
			if($secqaacheck) {
        			if(!$seclevel) {
        				list($seccode, $expiration, $seccodeuid) = explode(&quot;\t&quot;, authcode($_DCOOKIE&#x5B;'secq'], 'DECODE'));
        				if($seccodeuid != $discuz_uid || $timestamp - $expiration &gt; 600) {
        					showmessage('submit_secqaa_invalid');
        				}
        				dsetcookie('secq', '');
        			}
        			require_once DISCUZ_ROOT.'./forumdata/cache/cache_secqaa.php';
        			if(md5($secanswer) != $_DCACHE&#x5B;'secqaa']&#x5B;substr($seccode, 0, 1)]&#x5B;'answer']) {
        			        showmessage('submit_secqaa_invalid');
        			}
				$seclevel &amp;&amp; $seccode = random(1, 1) * 1000000 + substr($seccode, -6);
        		}
			return TRUE;
		} else {
			showmessage('submit_invalid');
		}
	}
}
</pre>
<p>打开discuz7.2的/templates/default/post.htm模板文件，修改以下部分：</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!--
此部分代码是由下面移到上面
--&gt;
&lt;!--{if $action != 'edit' &amp;&amp; ($secqaacheck || $seccodecheck)}--&gt;{template seccheck}&lt;!--{/if}--&gt;

&lt;button type=&quot;submit&quot; id=&quot;postsubmit&quot; prompt=&quot;post_submit&quot;  value=&quot;true&quot; name=&quot;{if $action == 'newthread'}topicsubmit{elseif $action == 'reply'}replysubmit{elseif $action == 'edit'}editsubmit{/if}&quot; tabindex=&quot;1&quot;&gt;
&lt;!--{if $action == 'newthread'}--&gt;
	&lt;!--{if $special == 0}--&gt;{lang post_newthread}
	&lt;!--{elseif $special == 1}--&gt;{lang post_newthreadpoll}
	&lt;!--{elseif $special == 2}--&gt;{lang post_newthreadtrade}
	&lt;!--{elseif $special == 3}--&gt;{lang post_newthreadreward}
	&lt;!--{elseif $special == 4}--&gt;{lang post_newthreadactivity}
	&lt;!--{elseif $special == 5}--&gt;{lang post_newthreaddebate}
	&lt;!--{elseif $special == 127}--&gt;
		&lt;!--{if $buttontext}--&gt;$buttontext&lt;!--{else}--&gt;{lang post_newthread}&lt;!--{/if}--&gt;
	&lt;!--{/if}--&gt;
&lt;!--{elseif $action == 'reply' &amp;&amp; !empty($addtrade)}--&gt;{lang trade_add_post}
&lt;!--{elseif $action == 'reply'}--&gt;{lang join_thread}
&lt;!--{elseif $action == 'edit'}--&gt;{lang edit_thread}
&lt;!--{/if}--&gt;
&lt;/button&gt;
</pre>
<p>修改seccheck.php文件，如果想以后能还原，建议备份该模板文件，该文件全部最终代码如下。</p>
<pre class="brush: xml; title: ; notranslate">
&lt;style&gt;
	#recaptcha_table{
		table-layout:auto;
	}
&lt;/style&gt;
{eval echo recaptcha_get_html($publickey)}
</pre>
<p><img decoding="async" src="http://www.mudbest.com/wp-content/uploads/2014/01/5555-610x410.jpg" alt="5555" width="610" height="410" class="alignnone size-medium wp-image-1991" srcset="https://www.mudbest.com/wp-content/uploads/2014/01/5555-610x410.jpg 610w, https://www.mudbest.com/wp-content/uploads/2014/01/5555.jpg 984w" sizes="(max-width: 610px) 100vw, 610px" /></p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2014/01/444-610x421.jpg" alt="444" width="610" height="421" class="alignnone size-medium wp-image-1990" srcset="https://www.mudbest.com/wp-content/uploads/2014/01/444-610x421.jpg 610w, https://www.mudbest.com/wp-content/uploads/2014/01/444.jpg 920w" sizes="auto, (max-width: 610px) 100vw, 610px" /></p>
<p>至此，google验证码已经在使用了。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>使用PHP将JS的unicode编码转换为可识别的汉字</title>
		<link>https://www.mudbest.com/%e4%bd%bf%e7%94%a8php%e5%b0%86js%e7%9a%84unicode%e7%bc%96%e7%a0%81%e8%bd%ac%e6%8d%a2%e4%b8%ba%e5%8f%af%e8%af%86%e5%88%ab%e7%9a%84%e6%b1%89%e5%ad%97/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Sun, 29 Dec 2013 08:14:49 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[unicode]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1943</guid>

					<description><![CDATA[今天抓数据的时候，发现js里的汉字全部为“\u738B\u6668”这样的字符串，没想到如何转到可识别的中文汉 ... <a title="使用PHP将JS的unicode编码转换为可识别的汉字" class="read-more" href="https://www.mudbest.com/%e4%bd%bf%e7%94%a8php%e5%b0%86js%e7%9a%84unicode%e7%bc%96%e7%a0%81%e8%bd%ac%e6%8d%a2%e4%b8%ba%e5%8f%af%e8%af%86%e5%88%ab%e7%9a%84%e6%b1%89%e5%ad%97/" aria-label="阅读 使用PHP将JS的unicode编码转换为可识别的汉字">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>今天抓数据的时候，发现js里的汉字全部为“\u738B\u6668”这样的字符串，没想到如何转到可识别的中文汉字，那么下面这段函数产生了……</p>
<p>直接贴code：<br />
<span id="more-1943"></span></p>
<pre class="brush: php; title: ; notranslate">
/**
 * 将js的unicode转换为中文
 * @param string $strHtml
 * @return string
 */
public function charReplace($strHtml){
	if(empty($strHtml)){
		return '';
	}
	$pregReg = '/(\\\u(&#x5B;\w]{4}))|(&#x5B;\x7f-\xff]+)/i';
	$arrTempData = array();
	preg_match_all($pregReg, $strHtml,$arrTempData);
	if(!empty($arrTempData)){
		//初始一个字符串变量
		$str = '';
		//循环处理
		for($i=0;$i&lt;count($arrTempData&#x5B;0]);$i++){
			$strTemp = $arrTempData&#x5B;0]&#x5B;$i];
			if (strpos($strTemp, '\\u') === 0){
				$strAry1 = base_convert(substr($strTemp, 2 , 2), 16, 10);
				$strAry2 = base_convert(substr($strTemp, 4), 16, 10);
				$strChr = chr($strAry1).chr($strAry2);
				//如果不是linux系统，则转换
				if(preg_match(&quot;/WIN/i&quot;,PHP_OS)){
					$strChr = iconv('UCS-2', 'UTF-8', $strChr);
				}
				//$str .= $strChr;
				$arrCharStartReplace&#x5B;] = $arrTempData&#x5B;0]&#x5B;$i];
				$arrCharEndReplace&#x5B;] = $strChr;
				//echo $arrTempData&#x5B;0]&#x5B;$i].'==='.$strCh.&quot;\r\n&quot;;
			}
		}
	}
	$strHtml = str_replace($arrCharStartReplace, $arrCharEndReplace, $strHtml);
	return $strHtml;
}
</pre>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>续PHP下webSerives的nusoap使用</title>
		<link>https://www.mudbest.com/%e7%bb%adphp%e4%b8%8bwebserives%e7%9a%84nusoap%e4%bd%bf%e7%94%a8/</link>
					<comments>https://www.mudbest.com/%e7%bb%adphp%e4%b8%8bwebserives%e7%9a%84nusoap%e4%bd%bf%e7%94%a8/#comments</comments>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Wed, 20 Nov 2013 07:03:01 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[分享]]></category>
		<category><![CDATA[nusoap]]></category>
		<category><![CDATA[soap]]></category>
		<category><![CDATA[webservices]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1908</guid>

					<description><![CDATA[呼&#8230;才发现很久没发博客了，真的实在是太忙了。平时还要抽点时间维护http://bbs.mudbes ... <a title="续PHP下webSerives的nusoap使用" class="read-more" href="https://www.mudbest.com/%e7%bb%adphp%e4%b8%8bwebserives%e7%9a%84nusoap%e4%bd%bf%e7%94%a8/" aria-label="阅读 续PHP下webSerives的nusoap使用">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>呼&#8230;才发现很久没发博客了，真的实在是太忙了。平时还要抽点时间维护http://bbs.mudbest.com 。</p>
<p>平时很少写webService，一般都是需要给第三方提供接口的时候才去写。偶然的一个机会，打开了项目里现有的webService文件，发现前人所写的webService都是以简单的创建一个类，再将类里面的函数暴露给第三方调用，连WSDL都不支持，这就不是规范的webService接口定义了。</p>
<p>开发人员应该都知道，传统的webService是有wsdl支持的，就是介绍了，传入和返回，以及webService的一些基本结构介绍信息，这能很大限度的增加接口可读性和参考性。<strong>希望所有开发者能够自我养成良好的编码习惯，开发者最忌讳的就是怕麻烦，请尊重自己的职业。</strong><span id="more-1908"></span></p>
<p>服务端demo:<br />
<a href="http://help.mudbest.com/php/demo_nusoap/webService/RefundService.php" target="__blank">http://help.mudbest.com/php/demo_nusoap/webService/RefundService.php</a></p>
<p><a href="http://help.mudbest.com/php/demo_nusoap/webService/RefundService.php?wsdl" target="__blank">http://help.mudbest.com/php/demo_nusoap/webService/RefundService.php?wsdl</a></p>
<p>下面nusoap的服务端(webService)和客户端(client)介绍一下简单实例。</p>
<p>nusoap支持类库下载地址：http://www.mudbest.com/webservicephp%E7%9A%84soap%E4%B8%8Enusoap%E6%9C%8D%E5%8A%A1%E7%AB%AF%E4%B8%8E%E5%AE%A2%E6%88%B7%E7%AB%AF%E7%9A%84%E9%80%9A%E4%BF%A1/nusoap-0-9-5/</p>
<p>1、首先创建一个服务端：</p>
<p>这里用的是注册类，而不是注册函数，建议创建webService的时候将服务结构整理清晰。</p>
<p>class.refundStatusService.php</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
/**
 * 退票状态回显服务类库
 * @author hkshadow
 */
class refundStatusService{
	private $objDb = null;
	
	public function __construct(){
		
	}
	
	public function connect(){
		
	}
	
	public function hello($person, $interface){
		$greeting = &#039;Hello111, &#039; . $person &amp;#91;&#039;firstname&#039;&amp;#93; . &#039;. It is nice to meet a &#039; . $person &amp;#91;&#039;age&#039;&amp;#93; . &#039; year old &#039; . $person &amp;#91;&#039;gender&#039;&amp;#93; . &#039;.&#039; . $interface &amp;#91;&#039;type&#039;&amp;#93;;
		$winner = &#039;Scott&#039;;
		//要返回的数据
		return array (&#039;greeting&#039; =&gt; $greeting, &#039;winner&#039; =&gt; $winner );
	}
}
?&gt;
</pre>
<p>建立服务（例如地址http://www.mudbest.com/webService.php）</p>
<pre class="brush: php; title: ; notranslate">
require_once(&#039;comm/nusoap/nusoap.php&#039;);
require_once(&#039;webservice/RefundStatusService.php&#039;);
// 新建一个soap服务
$server = new soap_server ();
// 初始化支持wsdl
$server-&gt;configureWSDL ( &#039;hellowsdl2&#039;, &#039;urn:hellowsdl2&#039; );
//设置返回时的编码
$server-&gt;soap_defencoding = &#039;UTF-8&#039;;
//是否utf8_decode()
$server-&gt;decode_utf8 = false;
//设置传入的编码
$server-&gt;xml_encoding = &#039;UTF-8&#039;;
// 定义接收的数据结构
$server-&gt;wsdl-&gt;addComplexType ( &#039;Person&#039;, &#039;complexType&#039;, &#039;struct&#039;, &#039;all&#039;, &#039;&#039;, 
		//array (&#039;type&#039; =&gt; &#039;1==2&#039; );
		array (&#039;type&#039; =&gt; array (&#039;name&#039; =&gt; &#039;type&#039;, &#039;type&#039; =&gt; &#039;xsd:string&#039; ) ),	// 后面的type定义数据的类型，这个是string
		array (&#039;firstname&#039; =&gt; array (&#039;name&#039; =&gt; &#039;firstname&#039;, &#039;type&#039; =&gt; &#039;xsd:string&#039; ), 	// 后面的type定义数据的类型，这个是string
				&#039;age&#039; =&gt; array (&#039;name&#039; =&gt; &#039;age&#039;, &#039;type&#039; =&gt; &#039;xsd:int&#039; ), 	// 后面的type定义数据的类型，这个是int
				&#039;gender&#039; =&gt; array (&#039;name&#039; =&gt; &#039;gender&#039;, &#039;type&#039; =&gt; &#039;xsd:string&#039; ) )	// 后面的type定义数据的类型，这个是string
);

//定义返回数据结构
$server-&gt;wsdl-&gt;addComplexType ( &#039;SweepstakesGreeting&#039;, &#039;complexType&#039;, &#039;struct&#039;, &#039;all&#039;, &#039;&#039;, array (&#039;greeting&#039; =&gt; array (&#039;name&#039; =&gt; &#039;greeting&#039;, &#039;type&#039; =&gt; &#039;xsd:string&#039; ), &#039;winner&#039; =&gt; array (&#039;name&#039; =&gt; &#039;winner&#039;, &#039;type&#039; =&gt; &#039;xsd:string&#039; ) ) );


/**
备注：
array (&#039;person&#039; =&gt; &#039;tns:Person&#039; )  这里声明是根据addComplexType (&#039;Person&#039;)方法定义属性，如果只需要传入字符串，则直接xsd:string即可
// 定义接收的数据结构
$server-&gt;wsdl-&gt;addComplexType ( &#039;Person&#039;, &#039;complexType&#039;, &#039;struct&#039;, &#039;all&#039;, &#039;&#039;, 
		//array (&#039;type&#039; =&gt; &#039;1==2&#039; );
		array (&#039;type&#039; =&gt; array (&#039;name&#039; =&gt; &#039;type&#039;, &#039;type&#039; =&gt; &#039;xsd:string&#039; ) ),	// 后面的type定义数据的类型，这个是string
		array (&#039;firstname&#039; =&gt; array (&#039;name&#039; =&gt; &#039;firstname&#039;, &#039;type&#039; =&gt; &#039;xsd:string&#039; ), 	// 后面的type定义数据的类型，这个是string
				&#039;age&#039; =&gt; array (&#039;name&#039; =&gt; &#039;age&#039;, &#039;type&#039; =&gt; &#039;xsd:int&#039; ), 	// 后面的type定义数据的类型，这个是int
				&#039;gender&#039; =&gt; array (&#039;name&#039; =&gt; &#039;gender&#039;, &#039;type&#039; =&gt; &#039;xsd:string&#039; ) )	// 后面的type定义数据的类型，这个是string
);
-----------------------------------------------------
array (&#039;return&#039; =&gt; &#039;tns:SweepstakesGreeting&#039; )  这里声明是根据addComplexType (&#039;SweepstakesGreeting&#039;)方法定义属性，如果只需要返回字符串，则直接xsd:string即可
//定义返回数据结构
$server-&gt;wsdl-&gt;addComplexType ( &#039;SweepstakesGreeting&#039;, &#039;complexType&#039;, &#039;struct&#039;, &#039;all&#039;, &#039;&#039;, array (&#039;greeting&#039; =&gt; array (&#039;name&#039; =&gt; &#039;greeting&#039;, &#039;type&#039; =&gt; &#039;xsd:string&#039; ), &#039;winner&#039; =&gt; array (&#039;name&#039; =&gt; &#039;winner&#039;, &#039;type&#039; =&gt; &#039;xsd:string&#039; ) ) );

*/
// 服务器定义的soap调用方法
$server-&gt;register ( &#039;refundStatusService.hello&#039;, 	// 这里注册的是类，类文件class.refundStatusService.php
		array (&#039;person&#039; =&gt; &#039;tns:Person&#039; ), 	// 客户端传来的变量
		array (&#039;return&#039; =&gt; &#039;tns:SweepstakesGreeting&#039; ), 	// 返回参数
		&#039;urn:hellowsdl2&#039;, 	// soap名
		&#039;urn:hellowsdl2#hello&#039;, 	// soap的方法名
		&#039;rpc&#039;, 	// 使用的方式
		&#039;encoded&#039;, 	// 编码
		&#039;test&#039;// 存档
		);	
		
		//请求时(试图)调用服务
		//$HTTP_RAW_POST_DATA = isset ( $HTTP_RAW_POST_DATA ) ? $HTTP_RAW_POST_DATA : &#039;&#039;;
		$HTTP_RAW_POST_DATA = isset($GLOBALS&#x5B;&#039;HTTP_RAW_POST_DATA&#039;]) ? $GLOBALS&#x5B;&#039;HTTP_RAW_POST_DATA&#039;] : &#039;&#039;;
		//处理请求并且返回响应结果(processes request and returns response)
		$server-&gt;service ( $HTTP_RAW_POST_DATA );
</pre>
<p>至此服务端已经创建完成，接下来要做的便是客户端(client)了。</p>
<p>demo.php</p>
<pre class="brush: php; title: ; notranslate">

// 包函nusoap.php
require_once(comm/nusoap/nusoap.php&#039;);
// 新建一个soap客户端，调用服务端提供的wsdl
// $client = new soapclient(&#039;http://www.mudbest.com/webService.php?wsdl&#039;, true);
$client = new nusoap_client ( &#039;http://www.mudbest.com/webService.php&#039; );

// 查看一下是不是报错
$err = $client-&gt;getError ();
if ($err) {
	// 显示错误
	echo &#039;&lt;h2&gt;Constructor error&lt;/h2&gt;&lt;pre&gt;&#039; . $err . &#039;&lt;/pre&gt;&#039;;
}
// 要向服务端要传的参数
$interface = array (&#039;type&#039; =&gt; &#039;1==2&#039; );
$person = array (&#039;firstname&#039; =&gt; &#039;Willi&#039;, &#039;age&#039; =&gt; 22, &#039;gender&#039; =&gt; &#039;male&#039; );

// 调用服务端的方法(这里注意call的名字与regisert名一样)
$result = $client-&gt;call ( &#039;refundStatusService.hello&#039;, array (&#039;userInfo&#039; =&gt; $person, &#039;interfaceType&#039; =&gt; $interface ) );

//WSDL调用服务端的方法(这里注意call的名字与regisert名一样)
//$result = $client-&gt;call ( &#039;refundStatusService.hello&#039;);
// 错误审核
if ($client-&gt;fault) {
	echo &#039;&lt;h2&gt;Fault&lt;/h2&gt;&lt;pre&gt;&#039;;
	print_r ( $result );
	echo &#039;&lt;/pre&gt;&#039;;
} else {
	$err = $client-&gt;getError ();
	if ($err) {
		echo &#039;&lt;h2&gt;Error&lt;/h2&gt;&lt;pre&gt;&#039; . $err . &#039;&lt;/pre&gt;&#039;;
	} else {
		echo &#039;&lt;h2&gt;Result&lt;/h2&gt;&lt;pre&gt;&#039;;
		print_r ( $result );
		echo &#039;&lt;/pre&gt;&#039;;
	}
}
// 显示请求信息
echo &#039;&lt;h2&gt;Request&lt;/h2&gt;&#039;;
echo &#039;&lt;pre&gt;&#039; . htmlspecialchars ( $client-&gt;request, ENT_QUOTES ) . &#039;&lt;/pre&gt;&#039;;
// 显示返回信息
echo &#039;&lt;h2&gt;Response&lt;/h2&gt;&#039;;
echo &#039;&lt;pre&gt;&#039; . htmlspecialchars ( $client-&gt;response, ENT_QUOTES ) . &#039;&lt;/pre&gt;&#039;;
// 显示调试信息
echo &#039;&lt;h2&gt;Debug&lt;/h2&gt;&#039;;
echo &#039;&lt;pre&gt;&#039; . htmlspecialchars ( $client-&gt;debug_str, ENT_QUOTES ) . &#039;&lt;/pre&gt;&#039;;
</pre>
<p>到这里，服务端以及客户端已经创建完成。</p>
<p>当在浏览器上浏览http://www.mudbest.com/webService.php时会出现结构图。<br />
<a href="http://www.mudbest.com/%e7%bb%adphp%e4%b8%8bwebserives%e7%9a%84nusoap%e4%bd%bf%e7%94%a8/soapwebservicesdemo1/" rel="attachment wp-att-1916"><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2013/11/soapWebServicesDemo1-540x370.jpg" alt="soapWebServicesDemo1" width="540" height="370" class="alignnone size-thumbnail wp-image-1916" /></a></p>
<p>当在浏览器上浏览http://www.mudbest.com/webService.php?wsdl时会出现xml格式。<br />
<a href="http://www.mudbest.com/wp-content/uploads/2013/11/soapWebServicesDemo2.jpg"><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2013/11/soapWebServicesDemo2-540x370.jpg" alt="soapWebServicesDemo2" width="540" height="370" class="alignnone size-thumbnail wp-image-1910" /></a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mudbest.com/%e7%bb%adphp%e4%b8%8bwebserives%e7%9a%84nusoap%e4%bd%bf%e7%94%a8/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>关于php在unserialize时返回false</title>
		<link>https://www.mudbest.com/%e5%85%b3%e4%ba%8ephp%e5%9c%a8unserialize%e6%97%b6%e8%bf%94%e5%9b%9efalse/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Fri, 06 Sep 2013 14:05:31 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[分享]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1900</guid>

					<description><![CDATA[今天碰到一个很畸形的问题，在进行反序列化时，结果返回了false，仔细检查了下，原来是序列化时编码与反序列化时 ... <a title="关于php在unserialize时返回false" class="read-more" href="https://www.mudbest.com/%e5%85%b3%e4%ba%8ephp%e5%9c%a8unserialize%e6%97%b6%e8%bf%94%e5%9b%9efalse/" aria-label="阅读 关于php在unserialize时返回false">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>今天碰到一个很畸形的问题，在进行反序列化时，结果返回了false，仔细检查了下，原来是序列化时编码与反序列化时编码问题。</p>
<p>平时很少注意这个，原因是编码不一致时单引号和双引号有差别。</p>
<p>以下函数进行替换可解决此问题。<br />
<span id="more-1900"></span></p>
<pre class="brush: php; title: ; notranslate">
// UTF-8
function mb_unserialize($serial_str) {
	$serial_str = str_replace ( &quot;\r&quot;, &quot;&quot;, $serial_str );
	$serial_str = preg_replace ( '!s:(\d+):&quot;(.*?)&quot;;!se', &quot;'s:'.strlen('$2').':\&quot;$2\&quot;;'&quot;, $serial_str );
	return unserialize ( $serial_str );
}

// ASC
function asc_unserialize($serial_str) {
	$serial_str = str_replace ( &quot;\r&quot;, &quot;&quot;, $serial_str );
	$serial_str = preg_replace ( '!s:(\d+):&quot;(.*?)&quot;;!se', '&quot;s:&quot;.strlen(&quot;$2&quot;).&quot;:\&quot;$2\&quot;;&quot;', $serial_str );
	return unserialize ( $serial_str );
}
</pre>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>命令行执行php可选参数</title>
		<link>https://www.mudbest.com/%e5%91%bd%e4%bb%a4%e8%a1%8c%e6%89%a7%e8%a1%8cphp%e5%8f%af%e9%80%89%e5%8f%82%e6%95%b0/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Thu, 05 Sep 2013 13:24:15 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[分享]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1898</guid>

					<description><![CDATA[在web上访问url的时候，往往只需要在执行文件后跟上“?”，&#8221;&#038;&#8221; 连接符 ... <a title="命令行执行php可选参数" class="read-more" href="https://www.mudbest.com/%e5%91%bd%e4%bb%a4%e8%a1%8c%e6%89%a7%e8%a1%8cphp%e5%8f%af%e9%80%89%e5%8f%82%e6%95%b0/" aria-label="阅读 命令行执行php可选参数">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>在web上访问url的时候，往往只需要在执行文件后跟上“?”，&#8221;&#038;&#8221; 连接符即可带上参数，而在命令行同样也能传递参数。翻看了一下php手册，有介绍关于php在命令行下执行所需要带上参数的资料。</p>
<p>$argv — 传递给脚本的参数数组</p>
<p>例如windows下，php环境在e:/server/php5.4/。</p>
<p>然后在命令行可以直接使用</p>
<p>用法1：e:/server/php5.4/php xxx.php</p>
<p>用法2：e:/server/php5.4/php xxx.php param1 param2<span id="more-1898"></span></p>
<p>param1,param2，为参数。xxx.php文件可以接受传入的这两个参数，分别用$argv[1],$argv[2]接受传入的param1和param2.。</p>
<p>php接受参数则使用$argv即可。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>PHP的fsockopen的使用</title>
		<link>https://www.mudbest.com/php%e7%9a%84fsockopen%e7%9a%84%e4%bd%bf%e7%94%a8/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Tue, 09 Jul 2013 05:30:46 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[curl]]></category>
		<category><![CDATA[fsockopen]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1881</guid>

					<description><![CDATA[打开博客，不知道是因为忙碌，还是因为自身精力。才发现自己很久没更新了。今天简单介绍下fsockoepn的一些简 ... <a title="PHP的fsockopen的使用" class="read-more" href="https://www.mudbest.com/php%e7%9a%84fsockopen%e7%9a%84%e4%bd%bf%e7%94%a8/" aria-label="阅读 PHP的fsockopen的使用">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>打开博客，不知道是因为忙碌，还是因为自身精力。才发现自己很久没更新了。今天简单介绍下fsockoepn的一些简单使用方法。</p>
<p>在我们用php写模拟登陆的时候，curl就足够了，但如果要去模拟抓取一个复杂的网站内容的时候，fsockopen是首选之备。</p>
<p>例如，获取验证码模拟登陆，模拟表单提交等等比较复杂的业务逻辑。</p>
<p>注意：PHP fsockopen需要 PHP.ini 中 allow_url_fopen 选项开启。<br />
<span id="more-1881"></span></p>
<pre class="brush: php; title: ; notranslate">
//地址，端口，错误代码，错误内容，超时时间
@fsockopen($host, $port, $this-&gt;_errno, $this-&gt;_errstr, $timeout);
</pre>
<p>返回一个socket请求。</p>
<p>实例：</p>
<pre class="brush: php; title: ; notranslate">
function test(){
	//简单封装了一下fsockopen
	require_once ('class/class.Socket.php');
	$socket = new Socket ();
	//...这里可以写参数
	//如
	//$queryString = 'name=test';
	$msg = &quot;POST /目标地址 HTTP/1.1\r\n&quot;;
	$msg .= &quot;Host: et.airchina.com.cn\r\n&quot;;
	$msg .= &quot;User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1\r\n&quot;;
	$msg .= &quot;Connection: keep-alive\r\n&quot;;
	$msg .= &quot;Content-Type: application/x-www-form-urlencoded\r\n&quot;;
	$msg .= &quot;Content-Length: &quot;.strlen($queryString).&quot;\r\n&quot;;
	$msg .= &quot;Pragma: no-cache\r\n&quot;;
	$msg .= &quot;Cache-Control: no-cache\r\n&quot;;
	$msg .= &quot;Referer: 请求url\r\n&quot;;
	$msg .= &quot;Cookie: $strTempCookie\r\n&quot;;
	$msg .= &quot;\r\n&quot;;
	$msg .= $queryString;
	$response = $socket-&gt;sendhttp($msg, 'host', 80, 10);
	if (!is_array($response)) {
		return $response;
	}
	if ('200'!=$response&#x5B;'code']) {
		return $response&#x5B;'header'];
	}
	//....
}
</pre>
<p>至此，一个简单的socket请求结束了，剩下的就是解析数据了。</p>
<p>补充点：</p>
<p>HTTP协议头部与Keep-Alive模式详解</p>
<p><strong>1、什么是Keep-Alive模式？</strong><br />
我们知道HTTP协议采用“请求-应答”模式，当使用普通模式，即非KeepAlive模式时，每个请求/应答客户和服务器都要新建一个连接，完成 之后立即断开连接（HTTP协议为无连接的协议）；当使用Keep-Alive模式（又称持久连接、连接重用）时，Keep-Alive功能使客户端到服 务器端的连接持续有效，当出现对服务器的后继请求时，Keep-Alive功能避免了建立或者重新建立连接。</p>
<p>http 1.0中默认是关闭的，需要在http头加入&#8221;Connection: Keep-Alive&#8221;，才能启用Keep-Alive；http 1.1中默认启用Keep-Alive，如果加入&#8221;Connection: close &#8220;，才关闭。目前大部分浏览器都是用http1.1协议，也就是说默认都会发起Keep-Alive的连接请求了，所以是否能完成一个完整的Keep- Alive连接就看服务器设置情况。</p>
<p>2、启用Keep-Alive的优点<br />
从上面的分析来看，启用Keep-Alive模式肯定更高效，性能更高。因为避免了建立/释放连接的开销。下面是RFC 2616 上的总结：</p>
<p>2.1、By opening and closing fewer TCP connections, CPU time is saved in routers and hosts (clients, servers, proxies, gateways, tunnels, or caches), and memory used for TCP protocol control blocks can be saved in hosts.<br />
2.2、HTTP requests and responses can be pipelined on a connection. Pipelining allows a client to make multiple requests without waiting for each response, allowing a single TCP connection to be used much more efficiently, with much lower elapsed time.<br />
2.3、Network congestion is reduced by reducing the number of packets caused by TCP opens, and by allowing TCP sufficient time to determine the congestion state of the network.<br />
2.4、Latency on subsequent requests is reduced since there is no time spent in TCP&#8217;s connection opening handshake.<br />
2.5、HTTP can evolve more gracefully, since errors can be reported without the penalty of closing the TCP connection. Clients using     future versions of HTTP might optimistically try a new feature, but if communicating with an older server, retry with old   semantics after an error is reported.</p>
<p>RFC 2616 （P47）还指出：单用户客户端与任何服务器或代理之间的连接数不应该超过2个。一个代理与其它服务器或代码之间应该使用超过2 * N的活跃并发连接。这是为了提高HTTP响应时间，避免拥塞（冗余的连接并不能代码执行性能的提升）。</p>
<p>3、回到我们的问题（即如何判断消息内容/长度的大小？）<br />
Keep-Alive模式，客户端如何判断请求所得到的响应数据已经接收完成（或者说如何知道服务器已经发生完了数据）？我们已经知道 了，Keep-Alive模式发送玩数据HTTP服务器不会自动断开连接，所有不能再使用返回EOF（-1）来判断（当然你一定要这样使用也没有办法，可 以想象那效率是何等的低）！下面我介绍两种来判断方法。</p>
<p>3.1、使用消息首部字段Conent-Length<br />
故名思意，Conent-Length表示实体内容长度，客户端（服务器）可以根据这个值来判断数据是否接收完成。但是如果消息中没有Conent-Length，那该如何来判断呢？又在什么情况下会没有Conent-Length呢？请继续往下看……<br />
3.2、使用消息首部字段Transfer-Encoding<br />
当客户端向服务器请求一个静态页面或者一张图片时，服务器可以很清楚的知道内容大小，然后通过Content-length消息首部字段告诉客户端 需要接收多少数据。但是如果是动态页面等时，服务器是不可能预先知道内容大小，这时就可以使用Transfer-Encoding：chunk模式来传输 数据了。即如果要一边产生数据，一边发给客户端，服务器就需要使用&#8221;Transfer-Encoding: chunked&#8221;这样的方式来代替Content-Length。<br />
chunk编码将数据分成一块一块的发生。Chunked编码将使用若干个Chunk串连而成，由一个标明长度为0 的chunk标示结束。每个Chunk分为头部和正文两部分，头部内容指定正文的字符总数（十六进制的数字 ）和数量单位（一般不写），正文部分就是指定长度的实际内容，两部分之间用回车换行(CRLF) 隔开。在最后一个长度为0的Chunk中的内容是称为footer的内容，是一些附加的Header信息（通常可以直接忽略）。<br />
Chunk编码的格式如下：</p>
<pre class="brush: plain; title: ; notranslate">
Chunked-Body = *chunk 
		&quot;0&quot; CRLF 
		footer 
		CRLF  
chunk = chunk-size &#x5B; chunk-ext ] CRLF 
        chunk-data CRLF
hex-no-zero = &lt;HEX excluding &quot;0&quot;&gt;
chunk-size = hex-no-zero *HEX 
chunk-ext = *( &quot;;&quot; chunk-ext-name &#x5B; &quot;=&quot; chunk-ext-value ] ) 
chunk-ext-name = token 
chunk-ext-val = token | quoted-string 
chunk-data = chunk-size(OCTET)
footer = *entity-header
</pre>
<p>即Chunk编码由四部分组成： 1、0至多个chunk块 ，2、&#8221;0&#8243; CRLF ，3、footer ，4、CRLF . 而每个chunk块由：chunk-size、chunk-ext（可选）、CRLF、chunk-data、CRLF组成。</p>
<p>4、消息长度的总结<br />
其实，上面2中方法都可以归纳为是如何判断http消息的大小、消息的数量。RFC 2616 对 消息的长度总结如下：一个消息的transfer-length（传输长度）是指消息中的message-body（消息体）的长度。当应用了 transfer-coding（传输编码），每个消息中的message-body（消息体）的长度（transfer-length）由以下几种情况 决定（优先级由高到低）：</p>
<p>4.1、任何不含有消息体的消息（如1XXX、204、304等响应消息和任何头(HEAD，首部)请求的响应消息），总是由一个空行（CLRF）结束。<br />
4.2、如果出现了Transfer-Encoding头字段 并且值为非“identity”，那么transfer-length由“chunked” 传输编码定义，除非消息由于关闭连接而终止。<br />
4.3、如果出现了Content-Length头字段，它的值表示entity-length（实体长度）和transfer-length（传输长 度）。如果这两个长度的大小不一样（i.e.设置了Transfer-Encoding头字段），那么将不能发送Content-Length头字段。并 且如果同时收到了Transfer-Encoding字段和Content-Length头字段，那么必须忽略Content-Length字段。<br />
4.4、如果消息使用媒体类型“multipart/byteranges”，并且transfer-length 没有另外指定，那么这种自定界（self-delimiting）媒体类型定义transfer-length 。除非发送者知道接收者能够解析该类型，否则不能使用该类型。<br />
4.5、由服务器关闭连接确定消息长度。（注意：关闭连接不能用于确定请求消息的结束，因为服务器不能再发响应消息给客户端了。）</p>
<p>为了兼容HTTP/1.0应用程序，HTTP/1.1的请求消息体中必须包含一个合法的Content-Length头字段，除非知道服务器兼容 HTTP/1.1。一个请求包含消息体，并且Content-Length字段没有给定，如果不能判断消息的长度，服务器应该用用400 (bad request) 来响应；或者服务器坚持希望收到一个合法的Content-Length字段，用 411 (length required)来响应。<br />
所有HTTP/1.1的接收者应用程序必须接受“chunked” transfer-coding (传输编码)，因此当不能事先知道消息的长度，允许使用这种机制来传输消息。消息不应该够同时包含 Content-Length头字段和non-identity transfer-coding。如果一个消息同时包含non-identity transfer-coding和Content-Length ，必须忽略Content-Length 。</p>
<p>5、HTTP头字段总结<br />
最后我总结下HTTP协议的头部字段。</p>
<p>5.1、 Accept：告诉WEB服务器自己接受什么介质类型，*/* 表示任何类型，type/* 表示该类型下的所有子类型，type/sub-type。<br />
5.2、 Accept-Charset： 浏览器申明自己接收的字符集。Accept-Encoding： 浏览器申明自己接收的编码方法，通常指定压缩方法，是否支持压缩，支持什么压缩方法（gzip，deflate） 。Accept-Language：浏览器申明自己接收的语言<br />
语言跟字符集的区别：中文是语言，中文有多种字符集，比如big5，gb2312，gbk等等。<br />
5.3、 Accept-Ranges：WEB服务器表明自己是否接受获取其某个实体的一部分（比如文件的一部分）的请求。bytes：表示接受，none：表示不接受。<br />
5.4、 Age：当代理服务器用自己缓存的实体去响应请求时，用该头部表明该实体从产生到现在经过多长时间了。<br />
5.5、 Authorization：当客户端接收到来自WEB服务器的 WWW-Authenticate 响应时，用该头部来回应自己的身份验证信息给WEB服务器。<br />
5.6、 Cache-Control：请求：no-cache（不要缓存的实体，要求现在从WEB服务器去取） ，max-age：（只接受 Age 值小于 max-age 值，并且没有过期的对象） ，max-stale：（可以接受过去的对象，但是过期时间必须小于 max-stale 值） ，min-fresh：（接受其新鲜生命期大于其当前 Age 跟 min-fresh 值之和的缓存对象） ，响应：public(可以用 Cached 内容回应任何用户) ，private（只能用缓存内容回应先前请求该内容的那个用户） ，no-cache（可以缓存，但是只有在跟WEB服务器验证了其有效后，才能返回给客户端） ，max-age：（本响应包含的对象的过期时间） ，ALL: no-store（不允许缓存）。<br />
5.7、 Connection：请求：close（告诉WEB服务器或者代理服务器，在完成本次请求的响应后，断开连接，不要等待本次连接的后续请求了）。 keepalive（告诉WEB服务器或者代理服务器，在完成本次请求的响应后，保持连接，等待本次连接的后续请求）。 响应：close（连接已经关闭）。 keepalive（连接保持着，在等待本次连接的后续请求）。 Keep-Alive：如果浏览器请求保持连接，则该头部表明希望 WEB 服务器保持连接多长时间（秒）。例如：Keep-Alive：300<br />
5.8、 Content-Encoding：WEB服务器表明自己使用了什么压缩方法（gzip，deflate）压缩响应中的对象。例如：Content-Encoding：gzip<br />
5.9、Content-Language：WEB 服务器告诉浏览器自己响应的对象的语言。<br />
5.10、Content-Length： WEB 服务器告诉浏览器自己响应的对象的长度。例如：Content-Length: 26012<br />
5.11、Content-Range： WEB 服务器表明该响应包含的部分对象为整个对象的哪个部分。例如：Content-Range: bytes 21010-47021/47022<br />
5.12、Content-Type： WEB 服务器告诉浏览器自己响应的对象的类型。例如：Content-Type：application/xml<br />
5.13、ETag：就是一个对象（比如URL）的标志值，就一个对象而言，比如一个 html 文件，如果被修改了，其 Etag 也会别修改，所以ETag 的作用跟 Last-Modified 的作用差不多，主要供 WEB 服务器判断一个对象是否改变了。比如前一次请求某个 html 文件时，获得了其 ETag，当这次又请求这个文件时，浏览器就会把先前获得的 ETag 值发送给WEB 服务器，然后 WEB 服务器会把这个 ETag 跟该文件的当前 ETag 进行对比，然后就知道这个文件有没有改变了。<br />
5.14、 Expired：WEB服务器表明该实体将在什么时候过期，对于过期了的对象，只有在跟WEB服务器验证了其有效性后，才能用来响应客户请求。是 HTTP/1.0 的头部。例如：Expires：Sat, 23 May 2009 10:02:12 GMT<br />
5.15、 Host：客户端指定自己想访问的WEB服务器的域名/IP 地址和端口号。例如：Host：rss.sina.com.cn<br />
5.16、 If-Match：如果对象的 ETag 没有改变，其实也就意味著对象没有改变，才执行请求的动作。<br />
5.17、 If-None-Match：如果对象的 ETag 改变了，其实也就意味著对象也改变了，才执行请求的动作。<br />
5.18、 If-Modified-Since：如果请求的对象在该头部指定的时间之后修改了，才执行请求的动作（比如返回对象），否则返回代码304，告诉浏览器 该对象没有修改。例如：If-Modified-Since：Thu, 10 Apr 2008 09:14:42 GMT<br />
5.19、 If-Unmodified-Since：如果请求的对象在该头部指定的时间之后没修改过，才执行请求的动作（比如返回对象）。<br />
5.20、 If-Range：浏览器告诉 WEB 服务器，如果我请求的对象没有改变，就把我缺少的部分给我，如果对象改变了，就把整个对象给我。浏览器通过发送请求对象的 ETag 或者 自己所知道的最后修改时间给 WEB 服务器，让其判断对象是否改变了。总是跟 Range 头部一起使用。<br />
5.21、 Last-Modified：WEB 服务器认为对象的最后修改时间，比如文件的最后修改时间，动态页面的最后产生时间等等。例如：Last-Modified：Tue, 06 May 2008 02:42:43 GMT<br />
5.22、 Location：WEB 服务器告诉浏览器，试图访问的对象已经被移到别的位置了，到该头部指定的位置去取。例如：Location：http://i0.sinaimg.cn/dy/deco/2008/0528/sinahome_0803_ws_005_text_0.gif<br />
5.23、 Pramga：主要使用 Pramga: no-cache，相当于 Cache-Control： no-cache。例如：Pragma：no-cache<br />
5.24、 Proxy-Authenticate： 代理服务器响应浏览器，要求其提供代理身份验证信息。Proxy-Authorization：浏览器响应代理服务器的身份验证请求，提供自己的身份信息。<br />
5.25、 Range：浏览器（比如 Flashget 多线程下载时）告诉 WEB 服务器自己想取对象的哪部分。例如：Range: bytes=1173546-<br />
5.26、 Referer：浏览器向 WEB 服务器表明自己是从哪个 网页/URL 获得/点击 当前请求中的网址/URL。例如：Referer：http://www.sina.com/<br />
5.27、 Server: WEB 服务器表明自己是什么软件及版本等信息。例如：Server：Apache/2.0.61 (Unix)<br />
5.28、 User-Agent: 浏览器表明自己的身份（是哪种浏览器）。例如：User-Agent：Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.14) Gecko/20080404 Firefox/2、0、0、14<br />
5.29、 Transfer-Encoding: WEB 服务器表明自己对本响应消息体（不是消息体里面的对象）作了怎样的编码，比如是否分块（chunked）。例如：Transfer-Encoding: chunked<br />
5.30、 Vary: WEB服务器用该头部的内容告诉 Cache 服务器，在什么条件下才能用本响应所返回的对象响应后续的请求。假如源WEB服务器在接到第一个请求消息时，其响应消息的头部为：Content- Encoding: gzip; Vary: Content-Encoding那么 Cache 服务器会分析后续请求消息的头部，检查其 Accept-Encoding，是否跟先前响应的 Vary 头部值一致，即是否使用相同的内容编码方法，这样就可以防止 Cache 服务器用自己 Cache 里面压缩后的实体响应给不具备解压能力的浏览器。例如：Vary：Accept-Encoding<br />
5.31、 Via： 列出从客户端到 OCS 或者相反方向的响应经过了哪些代理服务器，他们用什么协议（和版本）发送的请求。当客户端请求到达第一个代理服务器时，该服务器会在自己发出的请求里面添 加 Via 头部，并填上自己的相关信息，当下一个代理服务器收到第一个代理服务器的请求时，会在自己发出的请求里面复制前一个代理服务器的请求的Via 头部，并把自己的相关信息加到后面，以此类推，当 OCS 收到最后一个代理服务器的请求时，检查 Via 头部，就知道该请求所经过的路由。例如：Via：1.0 236.D0707195.sina.com.cn:80 (squid/2.6.STABLE13)</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>PHP针对Xss跨域攻击以及sql注入等危险字符串过滤安全模块</title>
		<link>https://www.mudbest.com/php%e8%bf%87%e6%bb%a4xss%e8%b7%a8%e5%9f%9f%e6%94%bb%e5%87%bb%e4%bb%a5%e5%8f%8asql%e7%ad%89%e5%8d%b1%e9%99%a9%e5%ad%97%e7%ac%a6%e4%b8%b2%e8%bf%87%e6%bb%a4%e5%ae%89%e5%85%a8%e6%a8%a1%e5%9d%97/</link>
					<comments>https://www.mudbest.com/php%e8%bf%87%e6%bb%a4xss%e8%b7%a8%e5%9f%9f%e6%94%bb%e5%87%bb%e4%bb%a5%e5%8f%8asql%e7%ad%89%e5%8d%b1%e9%99%a9%e5%ad%97%e7%ac%a6%e4%b8%b2%e8%bf%87%e6%bb%a4%e5%ae%89%e5%85%a8%e6%a8%a1%e5%9d%97/#comments</comments>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Wed, 10 Apr 2013 03:58:34 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[分享]]></category>
		<category><![CDATA[PHP安全模块]]></category>
		<category><![CDATA[sql注入]]></category>
		<category><![CDATA[Xss跨站攻击]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1855</guid>

					<description><![CDATA[由于该模块在项目中的要求是 不能提示任何信息，也不作断点操作，只作记录并且过滤危险参数。 主要功能：拦截攻击者 ... <a title="PHP针对Xss跨域攻击以及sql注入等危险字符串过滤安全模块" class="read-more" href="https://www.mudbest.com/php%e8%bf%87%e6%bb%a4xss%e8%b7%a8%e5%9f%9f%e6%94%bb%e5%87%bb%e4%bb%a5%e5%8f%8asql%e7%ad%89%e5%8d%b1%e9%99%a9%e5%ad%97%e7%ac%a6%e4%b8%b2%e8%bf%87%e6%bb%a4%e5%ae%89%e5%85%a8%e6%a8%a1%e5%9d%97/" aria-label="阅读 PHP针对Xss跨域攻击以及sql注入等危险字符串过滤安全模块">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>由于该模块在项目中的要求是 不能提示任何信息，也不作断点操作，只作记录并且过滤危险参数。</p>
<p>主要功能：拦截攻击者注入恶意代码，可以防御诸如跨站脚本攻击（XSS）、SQL注入攻击等恶意攻击行为。<br />
<span id="more-1855"></span></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
/**
 * 安全模块
 * Email:zhangyuan@tieyou.com
 * 主要针对xss跨站攻击、sql注入等敏感字符串进行过滤
 * @author hkshadow
 */
class safeMode{
	
	/**
	 * 执行过滤
	 * @param 1 linux/2 http/3 Db/ $group
	 * @param 保存路径以及文件名/文件名/null $projectName
	 */
	public function xss($group = 1,$projectName = NULL){
		//正则条件
		$referer = empty ( $_SERVER &#x5B;'HTTP_REFERER'] ) ? array () : array ($_SERVER &#x5B;'HTTP_REFERER'] );
		$getfilter = &quot;'|&lt;&#x5B;^&gt;]*?&gt;|^\\+\/v(8|9)|\\b(and|or)\\b.+?(&gt;|&lt;|=|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|&lt;\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)&quot;;
		$postfilter = &quot;^\\+\/v(8|9)|\\b(and|or)\\b.{1,6}?(=|&gt;|&lt;|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|&lt;\\s*script\\b|&lt;\\s*img\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)&quot;;
		$cookiefilter = &quot;\\b(and|or)\\b.{1,6}?(=|&gt;|&lt;|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|&lt;\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)&quot;;

		// $ArrPGC=array_merge($_GET,$_POST,$_COOKIE);

		//遍历过滤
		foreach ( $_GET as $key =&gt; $value ) {
			$this-&gt;stopAttack ( $key, $value, $getfilter ,$group , $projectName);
		}
		//遍历过滤
		foreach ( $_POST as $key =&gt; $value ) {
			$this-&gt;stopAttack ( $key, $value, $postfilter ,$group , $projectName);
		}
		//遍历过滤
		foreach ( $_COOKIE as $key =&gt; $value ) {
			$this-&gt;stopAttack ( $key, $value, $cookiefilter ,$group , $projectName);
		}
		//遍历过滤
		foreach ( $referer as $key =&gt; $value ) {
			$this-&gt;stopAttack ( $key, $value, $getfilter ,$group , $projectName);
		}
	}
	
	/**
	 * 匹配敏感字符串，并处理
	 * @param 参数key $strFiltKey
	 * @param 参数value $strFiltValue
	 * @param 正则条件 $arrFiltReq
	 * @param 项目名 $joinName
	 * @param 1 linux/2 http/3 Db/ $group
	 * @param 项目名/文件名/null $projectName
	 */
	public function stopAttack($strFiltKey, $strFiltValue, $arrFiltReq,$group = 1,$projectName = NULL) {
		
			$strFiltValue = $this-&gt;arr_foreach ( $strFiltValue );
			//匹配参数值是否合法
			if (preg_match ( &quot;/&quot; . $arrFiltReq . &quot;/is&quot;, $strFiltValue ) == 1) {
				//记录ip
				$ip = &quot;操作IP: &quot;.$_SERVER&#x5B;&quot;REMOTE_ADDR&quot;];
				//记录操作时间
				$time = &quot; 操作时间: &quot;.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;);
				//记录详细页面带参数
				$thePage = &quot; 操作页面: &quot;.$this-&gt;request_uri();
				//记录提交方式
				$type = &quot; 提交方式: &quot;.$_SERVER&#x5B;&quot;REQUEST_METHOD&quot;];
				//记录提交参数
				$key = &quot; 提交参数: &quot;.$strFiltKey;
				//记录参数
				$value = &quot; 提交数据: &quot;.htmlspecialchars($strFiltValue);
				//写入日志
				$strWord = $ip.$time.$thePage.$type.$key.$value;
				//保存为linux类型
				if($group == 1){
					$this-&gt;log_result_common($strWord,$projectName);
				}
				//保存为可web浏览
				if($group == 2){
					$strWord .= &quot;&lt;br&gt;&quot;;
					$this-&gt;slog($strWord,$projectName);
				}
				//保存至数据库
				if($group == 3){
					$this-&gt;sDb($strWord);	
				}
				//过滤参数
				$_REQUEST&#x5B;$strFiltKey] = '';
				//这里不作退出处理
				//exit;
			}
			
			//匹配参数是否合法
			if (preg_match ( &quot;/&quot; . $arrFiltReq . &quot;/is&quot;, $strFiltKey ) == 1) {
				//记录ip
				$ip = &quot;操作IP: &quot;.$_SERVER&#x5B;&quot;REMOTE_ADDR&quot;];
				//记录操作时间
				$time = &quot; 操作时间: &quot;.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;);
				//记录详细页面带参数
				$thePage = &quot; 操作页面: &quot;.$this-&gt;request_uri();
				//记录提交方式
				$type = &quot; 提交方式: &quot;.$_SERVER&#x5B;&quot;REQUEST_METHOD&quot;];
				//记录提交参数
				$key = &quot; 提交参数: &quot;.$strFiltKey;
				//记录参数
				$value = &quot; 提交数据: &quot;.htmlspecialchars($strFiltValue);
				//写入日志
				$strWord = $ip.$time.$thePage.$type.$key.$value;
				//保存为linux类型
				if($group == 1){
					$this-&gt;log_result_common($strWord,$projectName);
				}
				//保存为可web浏览
				if($group == 2){
					$strWord .= &quot;&lt;br&gt;&quot;;
					$this-&gt;slog($strWord,$projectName);
				}
				//保存至数据库
				if($group == 3){
					$this-&gt;sDb($strWord);	
				}
				//过滤参数
				$_REQUEST&#x5B;$strFiltKey] = '';
				//这里不作退出处理
				//exit;
			}
		}
	
	/**
	 * 获取当前url带具体参数
	 * @return string
	 */
	public function request_uri() {
		if (isset ( $_SERVER &#x5B;'REQUEST_URI'] )) {
			$uri = $_SERVER &#x5B;'REQUEST_URI'];
		} else {
			if (isset ( $_SERVER &#x5B;'argv'] )) {
				$uri = $_SERVER &#x5B;'PHP_SELF'] . '?' . $_SERVER &#x5B;'argv'] &#x5B;0];
			} else {
				$uri = $_SERVER &#x5B;'PHP_SELF'] . '?' . $_SERVER &#x5B;'QUERY_STRING'];
			}
		}
		return $uri;
	}
	

	/**
	 * 日志记录(linux模式)
	 * @param 保存内容 $strWord
	 * @param 保存文件名$strPathName
	 */
	public function log_result_common($strWord, $strPathName = NULL) {
		if($strPathName == NULL){
			$strPath = &quot;/var/tmp/&quot;;
			$strDay = date('Y-m-d');
			$strPathName = $strPath.&quot;common_log_&quot;.$strDay.'.log';
		}
	
		$fp = fopen($strPathName,&quot;a&quot;);
		flock($fp, LOCK_EX) ;
		fwrite($fp,$strWord.&quot; date &quot;.date('Y-m-d H:i:s',time()).&quot;\t\n&quot;);
		flock($fp, LOCK_UN);
		fclose($fp);
	}	
	
	/**
	 * 写入日志(支持http查看)
	 * @param 日志内容 $strWord
	 * @param web页面文件名 $fileName
	 */
	public function slog($strWord,$fileName = NULL) {
		if($fileName == NULL){
			$toppath = $_SERVER &#x5B;&quot;DOCUMENT_ROOT&quot;] . &quot;/log.htm&quot;;
		}else{
			$toppath = $_SERVER &#x5B;&quot;DOCUMENT_ROOT&quot;] .'/'. $fileName;
		}
		$Ts = fopen ( $toppath, &quot;a+&quot; );
		fputs ( $Ts, $strWord . &quot;\r\n&quot; );
		fclose ( $Ts );
	}
	
	/**
	 * 写入日志(数据库)
	 * @param 日志内容 $strWord
	 */
	public function sDb($strWord){
		//....
	}
	
	/**
	 * 递归数组
	 * @param array $arr
	 * @return unknown|string
	 */
	public function arr_foreach($arr) {
		static $str = '';
		if (! is_array ( $arr )) {
			return $arr;
		}
		foreach ( $arr as $key =&gt; $val ) {
			if (is_array ( $val )) {
				$this-&gt;arr_foreach ( $val );
			} else {
				$str &#x5B;] = $val;
			}
		}
		return implode ( $str );
	}
}
?&gt;
</pre>
<p>使用：</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
//实例类库
$safeMode = new safeMode();
//这里的参数指的的时 类型，保存的文件名，具体请看类注视。
$safeMode-&gt;xss(2,'test.html');
?&gt;
</pre>
<p>至此基本上，参数带有危险的字符串的时候，将其过滤，并且保存日志到网站根目录的test.html内，可在浏览器预览查看。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mudbest.com/php%e8%bf%87%e6%bb%a4xss%e8%b7%a8%e5%9f%9f%e6%94%bb%e5%87%bb%e4%bb%a5%e5%8f%8asql%e7%ad%89%e5%8d%b1%e9%99%a9%e5%ad%97%e7%ac%a6%e4%b8%b2%e8%bf%87%e6%bb%a4%e5%ae%89%e5%85%a8%e6%a8%a1%e5%9d%97/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
	</channel>
</rss>
