Nginx 开启gzip压缩(图片,文件,css)
1、Vim打开Nginx配置文件
vim /usr/local/nginx/conf/nginx.conf
2、找到如下一段,进行修改
gzip on; gzip_min_length 1k; gzip_buffers 4 16k; #gzip_http_version 1.0; gzip_comp_level 2; gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; gzip_vary off; gzip_disable "MSIE [1-6]\.";
3、解释一下
第1行:开启Gzip
第2行:不压缩临界值,大于1K的才压缩,一般不用改
第3行:buffer,就是,嗯,算了不解释了,不用改
第4行:用了反向代理的话,末端通信是HTTP/1.0,有需求的应该也不用看我这科普文了;有这句的话注释了就行了,默认是HTTP/1.1
第5行:压缩级别,1-10,数字越大压缩的越好,时间也越长,看心情随便改吧
第6行:进行压缩的文件类型,缺啥补啥就行了,JavaScript有两种写法,最好都写上吧,总有人抱怨js文件没有压缩,其实多写一种格式就行了
第7行:跟Squid等缓存服务有关,on的话会在Header里增加"Vary: Accept-Encoding",我不需要这玩意,自己对照情况看着办吧
第8行:IE6对Gzip不怎么友好,不给它Gzip了
4、:wq保存退出,重新加载Nginx
/usr/local/nginx/sbin/nginx -s reload
5、用curl测试Gzip是否成功开启
curl -I -H "Accept-Encoding: gzip, deflate" "http://www.111cn.net/" HTTP/1.1 200 OK Server: nginx/1.0.15 Date: Sun, 26 Aug 2012 18:13:09 GMT Content-Type: text/html; charset=UTF-8 Connection: keep-alive X-Powered-By: PHP/5.2.17p1 X-Pingback: http://www.slyar.com/blog/xmlrpc.php Content-Encoding: gzip
页面成功压缩
curl -I -H "Accept-Encoding: gzip, deflate" "http://www.ye111cn.nethemes/default/statics/css/lib.css" HTTP/1.1 200 OK Server: nginx/1.0.15 Date: Sun, 26 Aug 2012 18:21:25 GMT Content-Type: text/css Last-Modified: Sun, 26 Aug 2012 15:17:07 GMT Connection: keep-alive Expires: Mon, 27 Aug 2012 06:21:25 GMT Cache-Control: max-age=43200 Content-Encoding: gzip
css文件成功压缩
curl -I -H "Accept-Encoding: gzip, deflate" http://www.111cn.net /Themes/default/statics/js/jquery.min.js" HTTP/1.1 200 OK Server: nginx/1.0.15 Date: Sun, 26 Aug 2012 18:21:38 GMT Content-Type: application/x-javascript Last-Modified: Thu, 12 Jul 2012 17:42:45 GMT Connection: keep-alive Expires: Mon, 27 Aug 2012 06:21:38 GMT Cache-Control: max-age=43200 Content-Encoding: gzip
js文件成功压缩
curl -I -H "Accept-Encoding: gzip, deflate" "http://www.slyar.com/blog/wp-content/uploads/2012/08/2012-08-23_203542.png" HTTP/1.1 200 OK Server: nginx/1.0.15 Date: Sun, 26 Aug 2012 18:22:45 GMT Content-Type: image/png Last-Modified: Thu, 23 Aug 2012 13:50:53 GMT Connection: keep-alive Expires: Tue, 25 Sep 2012 18:22:45 GMT Cache-Control: max-age=2592000 Content-Encoding: gzip
图片成功压缩
curl -I -H "Accept-Encoding: gzip, deflate" "http://www.slyar.com/blog/wp-content/plugins/wp-multicollinks/wp-multicollinks.css" HTTP/1.1 200 OK Server: nginx/1.0.15 Date: Sun, 26 Aug 2012 18:23:27 GMT Content-Type: text/css Content-Length: 180 Last-Modified: Sat, 02 May 2009 08:46:15 GMT Connection: keep-alive Expires: Mon, 27 Aug 2012 06:23:27 GMT Cache-Control: max-age=43200 Accept-Ranges: bytes
最后来个不到1K的文件,由于我的阈值是1K,所以没压缩
生成RSS非常的简单只需要使用rss格式然后生成输出到浏览器就可以了,重点就是要告诉浏览器你是rss格式的数据即可,具体来看个例子。
rss(简易信息聚合也叫聚合内容)是一种描述和同步网站内容的格式。下面的生成RSS订阅的代码:
rss XML结构
<?xml version="1.0" encoding="utf-8"?> <rss version="2.0"> <channel> <title>网站名称</title> <link>http://www.111cn.net/</link> <description>网站描述!</description> <item> <title>RSS Tutorial</title> <link>网站地址/rss</link> <description>New RSS tutorial on W3School</description> </item> <item> <title>XML Tutorial</title> <link>网站地址/xml</link> <description>New XML tutorial on W3School</description> </item> </channel> </rss>
RSS实例
<?php class Rss { public function createFeed() { //RSS头部 $webUrl = 'http://'.$_SERVER['HTTP_HOST'];//网站地址 $webName = '网站名称'; //网站名称 $webDesc = '网站描述'; //网站描述 $html = '<?xml version="1.0" encoding="utf-8"?> <rss version="2.0"> <channel> <title>'.$webName.'</title> <link>'.$webUrl.'</link> <description>'.$webDesc.'</description> '.$this->createItem().' </channel> </rss> '; echo $html; } private function createItem() { //RSS item //$data可替换为自己的数据 $html = ''; //文章数据 $data = array( 'id' => 1, 'date' => date('r', time()), 'title' => '文章标题', 'link' => 'http://www.111cn.net', //文章地址 'description' => '网站描述' ); for($i = 0; $i < 6; $i++) { $html .= ' <item> <title>'.$data['title'].'</title> <link>'.$data['link'].'</link> <pubDate>'.$data['date'].'</pubDate> <description><![CDATA['.$data['description'].']]></description> </item> '; } return $html; } } header("Content-Type: text/xml; charset=utf-8"); $rss = new Rss(); $rss->createFeed(); exit; ?>
RSS Feed 生成后,如何设置才能给网站添加 RSS 呢?并且让 Firefox、IE7 或其它 Feed 机器人自动发现?很简单,在网页的 Head 节添加一个特定的 Link 标签即可,如下:
<link rel=”alternate” type=”application/rss+xml” title=”网站名称 RSS Feed” href=”http://www.111cn.net” />
设置 title 为 Feed 标题,href 为 Feed 地址,一切就 OK 了!
例子2
<?xml version="1.0" encoding="utf-8"?> <rss version="2.0"> <channel> <title>php程序员教程网</title> <link>http://www.111cn.net/</link> <description>本站是一个php程序员的工作生活笔记!</description> <item> <title>RSS Tutorial</title> <link>网站地址/rss</link> <description>New RSS tutorial on W3School</description> </item> <item> <title>XML Tutorial</title> <link>网站地址/xml</link> <description>New XML tutorial on W3School</description> </item> </channel> </rss>
下面分享一段使用 php 动态生成 RSS 的代码示例:
<?php /** ** php 动态生成 RSS 类 **/ define("TIME_ZONE",""); define("FEEDCREATOR_VERSION","www.111cn.net");//您的网址 class FeedItem extends HtmlDescribable{ var $title,$description,$link; var $author,$authorEmail,$image,$category,$comments,$guid,$source,$creator; var $date; var $additionalElements=Array(); } class FeedImage extends HtmlDescribable{ var $title,$url,$link; var $width,$height,$description; } class HtmlDescribable{ var $descriptionHtmlSyndicated; var $descriptionTruncSize; function getDescription(){ $descriptionField=new FeedHtmlField($this->description); $descriptionField->syndicateHtml=$this->descriptionHtmlSyndicated; $descriptionField->truncSize=$this->descriptionTruncSize; return $descriptionField->output(); } } class FeedHtmlField{ var $rawFieldContent; var $truncSize,$syndicateHtml; function FeedHtmlField($parFieldContent){ if($parFieldContent){ $this->rawFieldContent=$parFieldContent; } } function output(){ if(!$this->rawFieldContent){ $result=""; } elseif($this->syndicateHtml){ $result="<![CDATA[".$this->rawFieldContent."]]>"; }else{ if($this->truncSize and is_int($this->truncSize)){ $result=FeedCreator::iTrunc(htmlspecialchars($this->rawFieldContent),$this->truncSize); }else{ $result=htmlspecialchars($this->rawFieldContent); } } return $result; } } class UniversalFeedCreator extends FeedCreator{ var $_feed; function _setFormat($format){ switch (strtoupper($format)){ case "2.0": // fall through case "RSS2.0": $this->_feed=new RSSCreator20(); break; case "0.91": // fall through case "RSS0.91": $this->_feed=new RSSCreator091(); break; default: $this->_feed=new RSSCreator091(); break; } $vars=get_object_vars($this); foreach ($vars as $key => $value){ // prevent overwriting of properties "contentType","encoding"; do not copy "_feed" itself if(!in_array($key, array("_feed","contentType","encoding"))){ $this->_feed->{$key}=$this->{$key}; } } } function createFeed($format="RSS0.91"){ $this->_setFormat($format); return $this->_feed->createFeed(); } function saveFeed($format="RSS0.91",$filename="",$displayContents=true){ $this->_setFormat($format); $this->_feed->saveFeed($filename,$displayContents); } function useCached($format="RSS0.91",$filename="",$timeout=3600){ $this->_setFormat($format); $this->_feed->useCached($filename,$timeout); } } class FeedCreator extends HtmlDescribable{ var $title,$description,$link; var $syndicationURL,$image,$language,$copyright,$pubDate,$lastBuildDate,$editor,$editorEmail,$webmaster,$category,$docs,$ttl,$rating,$skipHours,$skipDays; var $xslStyleSheet=""; var $items=Array(); var $contentType="application/xml"; var $encoding="utf-8"; var $additionalElements=Array(); function addItem($item){ $this->items[]=$item; } function clearItem2Null(){ $this->items=array(); } function iTrunc($string,$length){ if(strlen($string)<=$length){ return $string; } $pos=strrpos($string,"."); if($pos>=$length-4){ $string=substr($string,0,$length-4); $pos=strrpos($string,"."); } if($pos>=$length*0.4){ return substr($string,0,$pos+1)." ..."; } $pos=strrpos($string," "); if($pos>=$length-4){ $string=substr($string,0,$length-4); $pos=strrpos($string," "); } if($pos>=$length*0.4){ return substr($string,0,$pos)." ..."; } return substr($string,0,$length-4)." ..."; } function _createGeneratorComment(){ return "<!-- generator=\"".FEEDCREATOR_VERSION."\" -->\n"; } function _createAdditionalElements($elements,$indentString=""){ $ae=""; if(is_array($elements)){ foreach($elements AS $key => $value){ $ae.= $indentString."<$key>$value</$key>\n"; } } return $ae; } function _createStylesheetReferences(){ $xml=""; if($this->cssStyleSheet) $xml .= "<?xml-stylesheet href=\"".$this->cssStyleSheet."\" type=\"text/css\"?>\n"; if($this->xslStyleSheet) $xml .= "<?xml-stylesheet href=\"".$this->xslStyleSheet."\" type=\"text/xsl\"?>\n"; return $xml; } function createFeed(){} function _generateFilename(){ $fileInfo=pathinfo($_SERVER["PHP_SELF"]); return substr($fileInfo["basename"],0,-(strlen($fileInfo["extension"])+1)).".xml"; } function _redirect($filename){ Header("Content-Type: ".$this->contentType."; charset=".$this->encoding."; filename=".basename($filename)); Header("Content-Disposition: inline; filename=".basename($filename)); readfile($filename,"r"); die(); } function useCached($filename="",$timeout=3600){ $this->_timeout=$timeout; if($filename==""){ $filename=$this->_generateFilename(); } if(file_exists($filename) && (time()-filemtime($filename) < $timeout)){ $this->_redirect($filename); } } function saveFeed($filename="",$displayContents=true){ if($filename==""){ $filename=$this->_generateFilename(); } $feedFile=fopen($filename,"w+"); if($feedFile){ fputs($feedFile,$this->createFeed()); fclose($feedFile); if($displayContents){ $this->_redirect($filename); } }else{ echo "<br /><b>Error creating feed file, please check write permissions.</b><br />"; } } } class FeedDate{ var $unix; function FeedDate($dateString=""){ if($dateString=="") $dateString=date("r"); if(is_integer($dateString)){ $this->unix=$dateString; return; } if(preg_match("~(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s+)?(\\d{1,2})\\s+([a-zA-Z]{3})\\s+(\\d{4})\\s+(\\d{2}):(\\d{2}):(\\d{2})\\s+(.*)~",$dateString,$matches)){ $months=Array("Jan"=>1,"Feb"=>2,"Mar"=>3,"Apr"=>4,"May"=>5,"Jun"=>6,"Jul"=>7,"Aug"=>8,"Sep"=>9,"Oct"=>10,"Nov"=>11,"Dec"=>12); $this->unix=mktime($matches[4],$matches[5],$matches[6],$months[$matches[2]],$matches[1],$matches[3]); if(substr($matches[7],0,1)=='+' OR substr($matches[7],0,1)=='-'){ $tzOffset=(substr($matches[7],0,3) * 60 + substr($matches[7],-2)) * 60; }else{ if(strlen($matches[7])==1){ $oneHour=3600; $ord=ord($matches[7]); if($ord < ord("M")){ $tzOffset=(ord("A") - $ord - 1) * $oneHour; } elseif($ord >= ord("M") && $matches[7]!="Z"){ $tzOffset=($ord - ord("M")) * $oneHour; } elseif($matches[7]=="Z"){ $tzOffset=0; } } switch ($matches[7]){ case "UT": case "GMT": $tzOffset=0; } } $this->unix += $tzOffset; return; } if(preg_match("~(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(.*)~",$dateString,$matches)){ $this->unix=mktime($matches[4],$matches[5],$matches[6],$matches[2],$matches[3],$matches[1]); if(substr($matches[7],0,1)=='+' OR substr($matches[7],0,1)=='-'){ $tzOffset=(substr($matches[7],0,3) * 60 + substr($matches[7],-2)) * 60; }else{ if($matches[7]=="Z"){ $tzOffset=0; } } $this->unix += $tzOffset; return; } $this->unix=0; } function rfc822(){ $date=gmdate("Y-m-d H:i:s",$this->unix); if(TIME_ZONE!="") $date .= " ".str_replace(":","",TIME_ZONE); return $date; } function iso8601(){ $date=gmdate("Y-m-d H:i:s",$this->unix); $date=substr($date,0,22) . ':' . substr($date,-2); if(TIME_ZONE!="") $date=str_replace("+00:00",TIME_ZONE,$date); return $date; } function unix(){ return $this->unix; } } class RSSCreator10 extends FeedCreator{ function createFeed(){ $feed="<?xml version=\"1.0\" encoding=\"".$this->encoding."\"?>\n"; $feed.= $this->_createGeneratorComment(); if($this->cssStyleSheet==""){ $cssStyleSheet="http://www.w3.org/2000/08/w3c-synd/style.css"; } $feed.= $this->_createStylesheetReferences(); $feed.= "<rdf:RDF\n"; $feed.= " xmlns=\"http://purl.org/rss/1.0/\"\n"; $feed.= " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"; $feed.= " xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\"\n"; $feed.= " xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"; $feed.= " <channel rdf:about=\"".$this->syndicationURL."\">\n"; $feed.= " <title>".htmlspecialchars($this->title)."</title>\n"; $feed.= " <description>".htmlspecialchars($this->description)."</description>\n"; $feed.= " <link>".$this->link."</link>\n"; if($this->image!=null){ $feed.= " <image rdf:resource=\"".$this->image->url."\" />\n"; } $now=new FeedDate(); $feed.= " <dc:date>".htmlspecialchars($now->iso8601())."</dc:date>\n"; $feed.= " <items>\n"; $feed.= " <rdf:Seq>\n"; for ($i=0;$i<count($this->items);$i++){ $feed.= " <rdf:li rdf:resource=\"".htmlspecialchars($this->items[$i]->link)."\"/>\n"; } $feed.= " </rdf:Seq>\n"; $feed.= " </items>\n"; $feed.= " </channel>\n"; if($this->image!=null){ $feed.= " <image rdf:about=\"".$this->image->url."\">\n"; $feed.= " <title>".$this->image->title."</title>\n"; $feed.= " <link>".$this->image->link."</link>\n"; $feed.= " <url>".$this->image->url."</url>\n"; $feed.= " </image>\n"; } $feed.= $this->_createAdditionalElements($this->additionalElements," "); for ($i=0;$i<count($this->items);$i++){ $feed.= " <item rdf:about=\"".htmlspecialchars($this->items[$i]->link)."\">\n"; //$feed.= " <dc:type>Posting</dc:type>\n"; $feed.= " <dc:format>text/html</dc:format>\n"; if($this->items[$i]->date!=null){ $itemDate=new FeedDate($this->items[$i]->date); $feed.= " <dc:date>".htmlspecialchars($itemDate->iso8601())."</dc:date>\n"; } if($this->items[$i]->source!=""){ $feed.= " <dc:source>".htmlspecialchars($this->items[$i]->source)."</dc:source>\n"; } if($this->items[$i]->author!=""){ $feed.= " <dc:creator>".htmlspecialchars($this->items[$i]->author)."</dc:creator>\n"; } $feed.= " <title>".htmlspecialchars(strip_tags(strtr($this->items[$i]->title,"\n\r"," ")))."</title>\n"; $feed.= " <link>".htmlspecialchars($this->items[$i]->link)."</link>\n"; $feed.= " <description>".htmlspecialchars($this->items[$i]->description)."</description>\n"; $feed.= $this->_createAdditionalElements($this->items[$i]->additionalElements," "); $feed.= " </item>\n"; } $feed.= "</rdf:RDF>\n"; return $feed; } } class RSSCreator091 extends FeedCreator{ var $RSSVersion; function RSSCreator091(){ $this->_setRSSVersion("0.91"); $this->contentType="application/rss+xml"; } function _setRSSVersion($version){ $this->RSSVersion=$version; } function createFeed(){ $feed="<?xml version=\"1.0\" encoding=\"".$this->encoding."\"?>\n"; $feed.= $this->_createGeneratorComment(); $feed.= $this->_createStylesheetReferences(); $feed.= "<rss version=\"".$this->RSSVersion."\">\n"; $feed.= " <channel>\n"; $feed.= " <title>".FeedCreator::iTrunc(htmlspecialchars($this->title),100)."</title>\n"; $this->descriptionTruncSize=500; $feed.= " <description>".$this->getDescription()."</description>\n"; $feed.= " <link>".$this->link."</link>\n"; $now=new FeedDate(); $feed.= " <lastBuildDate>".htmlspecialchars($now->rfc822())."</lastBuildDate>\n"; $feed.= " <generator>".FEEDCREATOR_VERSION."</generator>\n"; if($this->image!=null){ $feed.= " <image>\n"; $feed.= " <url>".$this->image->url."</url>\n"; $feed.= " <title>".FeedCreator::iTrunc(htmlspecialchars($this->image->title),100)."</title>\n"; $feed.= " <link>".$this->image->link."</link>\n"; if($this->image->width!=""){ $feed.= " <width>".$this->image->width."</width>\n"; } if($this->image->height!=""){ $feed.= " <height>".$this->image->height."</height>\n"; } if($this->image->description!=""){ $feed.= " <description>".$this->image->getDescription()."</description>\n"; } $feed.= " </image>\n"; } if($this->language!=""){ $feed.= " <language>".$this->language."</language>\n"; } if($this->copyright!=""){ $feed.= " <copyright>".FeedCreator::iTrunc(htmlspecialchars($this->copyright),100)."</copyright>\n"; } if($this->editor!=""){ $feed.= " <managingEditor>".FeedCreator::iTrunc(htmlspecialchars($this->editor),100)."</managingEditor>\n"; } if($this->webmaster!=""){ $feed.= " <webMaster>".FeedCreator::iTrunc(htmlspecialchars($this->webmaster),100)."</webMaster>\n"; } if($this->pubDate!=""){ $pubDate=new FeedDate($this->pubDate); $feed.= " <pubDate>".htmlspecialchars($pubDate->rfc822())."</pubDate>\n"; } if($this->category!=""){ $feed.= " <category>".htmlspecialchars($this->category)."</category>\n"; } if($this->docs!=""){ $feed.= " <docs>".FeedCreator::iTrunc(htmlspecialchars($this->docs),500)."</docs>\n"; } if($this->ttl!=""){ $feed.= " <ttl>".htmlspecialchars($this->ttl)."</ttl>\n"; } if($this->rating!=""){ $feed.= " <rating>".FeedCreator::iTrunc(htmlspecialchars($this->rating),500)."</rating>\n"; } if($this->skipHours!=""){ $feed.= " <skipHours>".htmlspecialchars($this->skipHours)."</skipHours>\n"; } if($this->skipDays!=""){ $feed.= " <skipDays>".htmlspecialchars($this->skipDays)."</skipDays>\n"; } $feed.= $this->_createAdditionalElements($this->additionalElements," "); for ($i=0;$i<count($this->items);$i++){ $feed.= " <item>\n"; $feed.= " <title>".FeedCreator::iTrunc(htmlspecialchars(strip_tags($this->items[$i]->title)),100)."</title>\n"; $feed.= " <link>".htmlspecialchars($this->items[$i]->link)."</link>\n"; $feed.= " <description>".$this->items[$i]->getDescription()."</description>\n"; if($this->items[$i]->author!=""){ $feed.= " <author>".htmlspecialchars($this->items[$i]->author)."</author>\n"; } /* // on hold if($this->items[$i]->source!=""){ $feed.= " <source>".htmlspecialchars($this->items[$i]->source)."</source>\n"; } */ if($this->items[$i]->category!=""){ $feed.= " <category>".htmlspecialchars($this->items[$i]->category)."</category>\n"; } if($this->items[$i]->comments!=""){ $feed.= " <comments>".htmlspecialchars($this->items[$i]->comments)."</comments>\n"; } if($this->items[$i]->date!=""){ $itemDate=new FeedDate($this->items[$i]->date); $feed.= " <pubDate>".htmlspecialchars($itemDate->rfc822())."</pubDate>\n"; } if($this->items[$i]->guid!=""){ $feed.= " <guid>".htmlspecialchars($this->items[$i]->guid)."</guid>\n"; } $feed.= $this->_createAdditionalElements($this->items[$i]->additionalElements," "); $feed.= " </item>\n"; } $feed.= " </channel>\n"; $feed.= "</rss>\n"; return $feed; } } class RSSCreator20 extends RSSCreator091{ function RSSCreator20(){ parent::_setRSSVersion("2.0"); } }
使用示例:
<?php header('Content-Type:text/html; charset=utf-8'); $db=mysql_connect('127.0.0.1','root','123456'); mysql_query("set names utf8"); mysql_select_db('dbname',$db); $brs=mysql_query('select * from article order by add_time desc limit 0,10',$db); $rss=new UniversalFeedCreator(); $rss->title="页面标题"; $rss->link="网址http://"; $rss->description="rss标题"; while($rowbrs=mysql_fetch_array($brs)){ $item=new FeedItem(); $item->title =$rowbrs['subject']; $item->link='http://www.111cn.net/'; $item->description =$rowbrs['description']; $rss->addItem($item); } mysql_close($db); $rss->saveFeed("RSS2.0","rss.xml");微信公众号号在手机中通过api接口可以实现自定义分享内容了,下面我们来看这个接口的实现步骤。
一、准备阶段
公众号一个,微网站一个。
二、绑定域名
先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
备注:登录后可在“开发者中心”查看对应的接口权限。
三、代码
<?php //curl获取请求文本内容 function get_curl_contents($url, $method ='GET', $data = array()) { if ($method == 'POST') { //使用crul模拟 $ch = curl_init(); //禁用https curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //允许请求以文件流的形式返回 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 30); curl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); //执行发送 curl_close($ch); }else { if (ini_get('allow_fopen_url') == '1') { $result = file_get_contents($url); }else { //使用crul模拟 $ch = curl_init(); //允许请求以文件流的形式返回 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //禁用https curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); //执行发送 curl_close($ch); } } return $result; } //获取微信公从号access_token function wx_get_token() { $AppID = '1235464654';//AppID(应用ID) $AppSecret = '705641465sdfasdf456465a4sdf';//AppSecret(应用密钥) $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$AppID.'&secret='.$AppSecret; $res = get_curl_contents($url); $res = json_decode($res, true); //这里应该把access_token缓存起来,至于要怎么缓存就看各位了,有效期是7200s return $res['access_token']; } //获取微信公从号ticket function wx_get_jsapi_ticket() { $url = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", wx_get_token()); $res = get_curl_contents($url); $res = json_decode($res, true); //这里应该把access_token缓存起来,至于要怎么缓存就看各位了,有效期是7200s return $res['ticket']; } $wx = array(); //生成签名的时间戳 $wx['timestamp'] = time(); //生成签名的随机串 $wx['noncestr'] = 'Wm3WZYTPz0wzccnW'; //jsapi_ticket是公众号用于调用微信JS接口的临时票据。正常情况下,jsapi_ticket的有效期为7200秒,通过access_token来获取。 $wx['jsapi_ticket'] = wx_get_jsapi_ticket(); //分享的地址,注意:这里是指当前网页的URL,不包含#及其后面部分,曾经的我就在这里被坑了,所以小伙伴们要小心了 $wx['url'] = 'http://www.baidu.com'; $string = sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s", $wx['jsapi_ticket'], $wx['noncestr'], $wx['timestamp'], $wx['url']); //生成签名 $wx['signature'] = sha1($string); /* 注意事项 签名用的noncestr和timestamp必须与wx.config中的nonceStr和timestamp相同。 签名用的url必须是调用JS接口页面的完整URL。 出于安全考虑,开发者必须在服务器端实现签名的逻辑。 */ ?>
四、视图显示
在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.0.0.js
通过config接口注入权限验证配置
<script> //通过config接口注入权限验证配置 wx.config({ debug : false, appId : 'AppID', timestamp : '<?php echo $wx["timestamp"];?>', nonceStr : '<?php echo $wx["noncestr"];?>', signature : '<?php echo $wx["signature"];?>', jsApiList : ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo'] }); wx.ready(function(){ var s_title = '分享标题', // 分享标题 s_link = '分享链接', // 分享链接 s_desc = '分享描述', //分享描述 s_imgUrl = '分享图片'; // 分享图标 //朋友圈 wx.onMenuShareTimeline({ title: s_title, // 分享标题 link: s_link, // 分享链接 imgUrl: s_imgUrl, // 分享图标 success: function () { }, cancel: function () { } }); //发送给好友 wx.onMenuShareAppMessage({ title: s_title, // 分享标题 desc: s_desc, // 分享描述 link: s_link, // 分享链接 imgUrl: s_imgUrl, // 分享图标 type: '', // 分享类型,music、video或link,不填默认为link dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空 success: function () {}, cancel: function () {} }); //QQ好友 wx.onMenuShareQQ({ title: s_title, // 分享标题 desc: s_desc, // 分享描述 link: s_link, // 分享链接 imgUrl: s_imgUrl, // 分享图标 success: function () { }, cancel: function () { } }); //腾讯微博 wx.onMenuShareWeibo({ title: s_title, // 分享标题 desc: s_desc, // 分享描述 link: s_link, // 分享链接 imgUrl: s_imgUrl, // 分享图标 success: function () { }, cancel: function () { } }); }); </script>
五、大功告成
基本上的流程就是这样了,比较麻烦的一点就是生成签名那一块,注意一点就行了
本文章来为各位介绍一篇关于php-fpm设置socket方式连接FastCGI的例子,希望文章可能帮助到各位深入的理解socket方式连接FastCGI的知识。socket方式不会走到tcp层,tcp方式则会走到ip层。因此,理论上说socket连接方式效率会更好一点。
TCP和unix domain socket方式对比
TCP是使用TCP端口连接127.0.0.1:9000
Socket是使用unix domain socket连接套接字/dev/shm/php-fpm.sock
修改php-fpm.conf配置
#listen = 127.0.0.1:9000 listen=/dev/shm/php-fpm.sock #/dev/shm/为内存文件系统,注意 确保可读写 listen.owner=apache #注意自己的用户和组 listen.group=apache
修改nginx.conf配置
#fastcgi_pass 127.0.0.1:9000; #将相应的如上内容修改如下 fastcgi_pass unix:/dev/shm/php-fpm.sock;
重启nginx和php-fpm
service nginx restart /usr/local/nginx/sbin/nginx -s reload
下文小编为各位来介绍一篇关于PHP ASCII码与字符串的相互转换的例子,希望这个例子能够对各位有帮助。
<?php class ascii { /** * 将ascii码转为字符串 * @param type $str 要解码的字符串 * @param type $prefix 前缀,默认:&# * @return type */ function decode($str, $prefix="&#") { $str = str_replace($prefix, "", $str); $a = explode(";", $str); foreach ($a as $dec) { if ($dec < 128) { $utf .= chr($dec); } else if ($dec < 2048) { $utf .= chr(192 + (($dec - ($dec % 64)) / 64)); $utf .= chr(128 + ($dec % 64)); } else { $utf .= chr(224 + (($dec - ($dec % 4096)) / 4096)); $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64)); $utf .= chr(128 + ($dec % 64)); } } return $utf; } /** * 将字符串转换为ascii码 * @param type $c 要编码的字符串 * @param type $prefix 前缀,默认:&# * @return string */ function encode($c, $prefix="&#") { $len = strlen($c); $a = 0; while ($a < $len) { $ud = 0; if (ord($c{$a}) >= 0 && ord($c{$a}) <= 127) { $ud = ord($c{$a}); $a += 1; } else if (ord($c{$a}) >= 192 && ord($c{$a}) <= 223) { $ud = (ord($c{$a}) - 192) * 64 + (ord($c{$a + 1}) - 128); $a += 2; } else if (ord($c{$a}) >= 224 && ord($c{$a}) <= 239) { $ud = (ord($c{$a}) - 224) * 4096 + (ord($c{$a + 1}) - 128) * 64 + (ord($c{$a + 2}) - 128); $a += 3; } else if (ord($c{$a}) >= 240 && ord($c{$a}) <= 247) { $ud = (ord($c{$a}) - 240) * 262144 + (ord($c{$a + 1}) - 128) * 4096 + (ord($c{$a + 2}) - 128) * 64 + (ord($c{$a + 3}) - 128); $a += 4; } else if (ord($c{$a}) >= 248 && ord($c{$a}) <= 251) { $ud = (ord($c{$a}) - 248) * 16777216 + (ord($c{$a + 1}) - 128) * 262144 + (ord($c{$a + 2}) - 128) * 4096 + (ord($c{$a + 3}) - 128) * 64 + (ord($c{$a + 4}) - 128); $a += 5; } else if (ord($c{$a}) >= 252 && ord($c{$a}) <= 253) { $ud = (ord($c{$a}) - 252) * 1073741824 + (ord($c{$a + 1}) - 128) * 16777216 + (ord($c{$a + 2}) - 128) * 262144 + (ord($c{$a + 3}) - 128) * 4096 + (ord($c{$a + 4}) - 128) * 64 + (ord($c{$a + 5}) - 128); $a += 6; } else if (ord($c{$a}) >= 254 && ord($c{$a}) <= 255) { //error $ud = false; } $scill .= $prefix.$ud.";"; } return $scill; } } /* PHP 转 ASCII require_once "ascii_class.php"; */ $aa = new ascii; echo "<xmp>"; echo $str = $aa->encode("PHP二次开发:www.111cn.net"); echo "</xmp>"; echo $aa->decode($str); ?>
相关文章
使用PHP+JavaScript将HTML页面转换为图片的实例分享
这篇文章主要介绍了使用PHP+JavaScript将HTML元素转换为图片的实例分享,文后结果的截图只能体现出替换的字体,也不能说将静态页面转为图片可以加快加载,只是这种做法比较interesting XD需要的朋友可以参考下...2016-04-19- 这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
- 今天小编在这里就来给各位Photoshop的这一款软件的使用者们来说说把古装美女图片转为细腻的工笔画效果的制作教程,各位想知道方法的使用者们,那么下面就快来跟着小编一...2016-09-14
- 这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
- php如何实现抓取网页图片,相较于手动的粘贴复制,使用小程序要方便快捷多了,喜欢编程的人总会喜欢制作一些简单有用的小软件,最近就参考了网上一个php抓取图片代码,封装了一个php远程抓取图片的类,测试了一下,效果还不错分享...2015-10-30
- 这篇文章主要介绍了Go语言压缩和解压缩tar.gz文件的方法,实例分析了使用Go语言压缩文件与解压文件的技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-05-03
jquery左右滚动焦点图banner图片鼠标经过显示上下页按钮
jquery左右滚动焦点图banner图片鼠标经过显示上下页按钮...2013-10-13- 下面小编就为大家带来一篇利用JS实现点击按钮后图片自动切换的简单方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-10-25
- Photoshop的这一款软件小编相信很多的人都已经是使用过了吧,那么今天小编在这里就给大家带来了用Photoshop软件制作枪战电影海报的教程,想知道制作步骤的玩家们,那么下面...2016-09-14
- 这篇文章主要为大家详细介绍了js实现上传图片及时预览的相关资料,具有一定的参考价值,感兴趣的朋友可以参考一下...2016-05-09
- 图片剪裁是常用的方法,那么如何通过4坐标剪裁图片,本文就详细的来介绍一下,感兴趣的小伙伴们可以参考一下...2021-06-04
- 共享一段使用PHP下载CSS文件中的图片的代码 复制代码 代码如下: <?php //note 设置PHP超时时间 set_time_limit(0); //note 取得样式文件内容 $styleFileContent = file_get_contents('images/style.css'); //not...2013-10-04
- PHP代码如下:复制代码 代码如下:if (isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) { $upload_file = $_FILES['Filedata']; $fil...2013-10-04
- 这篇文章主要给大家介绍了关于微信小程序如何获取图片宽度与高度的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-10
C#中图片旋转和翻转(RotateFlipType)用法分析
这篇文章主要介绍了C#中图片旋转和翻转(RotateFlipType)用法,实例分析了C#图片旋转及翻转Image.RotateFlip方法属性的常用设置技巧,需要的朋友可以参考下...2020-06-25- ps软件是现在很多人比较喜欢的,有着非常不错的使用效果,这次文章就给大家介绍下ps怎么制作图片阴影效果,还不知道制作方法的赶紧来看看。 ps图片阴影效果怎么做方法/...2017-07-06
- 这篇文章主要介绍了OpenCV如何去除图片中的阴影的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-29
- 本文主要介绍用C#实现图片转换成字节流,字节流转换成图片,并根据图片路径返回图片的字节流,有需要的朋友可以参考下...2020-06-25
- 这篇文章主要介绍了JavaScript 如何禁止用户保存图片,帮助大家完成需求,更好的理解和使用JavaScript,感兴趣的朋友可以了解下...2020-11-19
- 我们在php中上传文件就必须使用#_FILE变量了,这个自动全局变量 $_FILES 从 PHP 4.1.0 版本开始被支持。在这之前,从 4.0.0 版本开始,PHP 支持 $HTTP_POST_FILES 数组。这...2016-11-25