首页 > 编程技术 > php

PHP导出excel类完整实例程序

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

本文章来给各位同学详细介绍关于PHP导出excel类完整实例程序代码,这里我们使用了phpExcel插件哦,大家使用前先去下载一个phpExcel插件。

php exeel.class.php文件

 代码如下 复制代码

<?php

/**
 * Simple excel generating from PHP5
 *
 * @package Utilities
 * @license http://www.opensource.org/licenses/mit-license.php
 * @author Oliver Schwarz <oliver.schwarz@gmail.com>
 * @version 1.0
 */

/**
 * Generating excel documents on-the-fly from PHP5
 *
 * Uses the excel XML-specification to generate a native
 * XML document, readable/processable by excel.
 *
 * @package Utilities
 * @subpackage Excel
 * @author Oliver Schwarz <oliver.schwarz@vaicon.de>
 * @version 1.1
 *
 * @todo Issue #4: Internet Explorer 7 does not work well with the given header
 * @todo Add option to give out first line as header (bold text)
 * @todo Add option to give out last line as footer (bold text)
 * @todo Add option to write to file
 */
class Excel_XML
{

 /**
  * Header (of document)
  * @var string
  */
        private $header = "<?xml version="1.0" encoding="%s"?>n<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">";

        /**
         * Footer (of document)
         * @var string
         */
        private $footer = "</Workbook>";

        /**
         * Lines to output in the excel document
         * @var array
         */
        private $lines = array();

        /**
         * Used encoding
         * @var string
         */
        private $sEncoding;
       
        /**
         * Convert variable types
         * @var boolean
         */
        private $bConvertTypes;
       
        /**
         * Worksheet title
         * @var string
         */
        private $sWorksheetTitle;

        /**
         * Constructor
         *
         * The constructor allows the setting of some additional
         * parameters so that the library may be configured to
         * one's needs.
         *
         * On converting types:
         * When set to true, the library tries to identify the type of
         * the variable value and set the field specification for Excel
         * accordingly. Be careful with article numbers or postcodes
         * starting with a '0' (zero)!
         *
         * @param string $sEncoding Encoding to be used (defaults to UTF-8)
         * @param boolean $bConvertTypes Convert variables to field specification
         * @param string $sWorksheetTitle Title for the worksheet
         */
        public function __construct($sEncoding = 'UTF-8', $bConvertTypes = false, $sWorksheetTitle = 'Table1')
        {
                $this->bConvertTypes = $bConvertTypes;
         $this->setEncoding($sEncoding);
         $this->setWorksheetTitle($sWorksheetTitle);
        }
       
        /**
         * Set encoding
         * @param string Encoding type to set
         */
        public function setEncoding($sEncoding)
        {
         $this->sEncoding = $sEncoding;
        }

        /**
         * Set worksheet title
         *
         * Strips out not allowed characters and trims the
         * title to a maximum length of 31.
         *
         * @param string $title Title for worksheet
         */
        public function setWorksheetTitle ($title)
        {
                $title = preg_replace ("/[\|:|/|?|*|[|]]/", "", $title);
                $title = substr ($title, 0, 31);
                $this->sWorksheetTitle = $title;
        }

        /**
         * Add row
         *
         * Adds a single row to the document. If set to true, self::bConvertTypes
         * checks the type of variable and returns the specific field settings
         * for the cell.
         *
         * @param array $array One-dimensional array with row content
         */
        private function addRow ($array)
        {
         $cells = "";
                foreach ($array as $k => $v):
                        $type = 'String';
                        if ($this->bConvertTypes === true && is_numeric($v)):
                                $type = 'Number';
                        endif;
                        $v = htmlentities($v, ENT_COMPAT, $this->sEncoding);
                        $cells .= "<Cell><Data ss:Type="$type">" . $v . "</Data></Cell>n";
                endforeach;
                $this->lines[] = "<Row>n" . $cells . "</Row>n";
        }

        /**
         * Add an array to the document
         * @param array 2-dimensional array
         */
        public function addArray ($array)
        {
                foreach ($array as $k => $v)
                        $this->addRow ($v);
        }


        /**
         * Generate the excel file
         * @param string $filename Name of excel file to generate (...xls)
         */
        public function generateXML ($filename = 'excel-export')
        {
                // correct/validate filename
                $filename = preg_replace('/[^aA-zZ0-9_-]/', '', $filename);
     
                // deliver header (as recommended in php manual)
                header("Content-Type: application/vnd.ms-excel; charset=" . $this->sEncoding);
                header("Content-Disposition: inline; filename="" . $filename . ".xls"");
                // print out document to the browser
                // need to use stripslashes for the damn ">"
                echo stripslashes (sprintf($this->header, $this->sEncoding));
                echo "n<Worksheet ss:Name="" . $this->sWorksheetTitle . "">n<Table>n";
                foreach ($this->lines as $line)
                        echo $line;

                echo "</Table>n</Worksheet>n";
                echo $this->footer;
        }

}
?>

excel.class.php文件

 代码如下 复制代码

<?php
/*功能:导出excel类
 *时间:2012年8月16日
 *作者:565990136@qq.com
*/
class myexcel{
private $filelds_arr1=array();
private $filelds_arr2=array();
private $filename;
// load library
function __construct($fields_arr1,$fields_arr2,$filename='test'){
 $this->filelds_arr1=$fields_arr1;
 $this->filelds_arr2=$fields_arr2;
 $this->filename=$filename;
 }
function putout(){
require 'php-excel.class.php';

$datavalue=$this->filelds_arr2;
$newdata[0]=$this->filelds_arr1;
$arrcount=count($datavalue);
for($i=1;$i<=$arrcount;$i++){
$newdata[$i]=array_values($datavalue[$i-1]);
}


$filename=$this->filename;
$xls = new Excel_XML('UTF-8', false, 'My Test Sheet');
$xls->addArray($newdata);
$xls->generateXML($filename);
}
}

/*
**用法示例(注意导出的文件名只能用英文)

  $asdasd=new myexcel(array('姓名','电话'),array(array('贾新明','13521530320')),'abc');
  $asdasd->putout();
*/
?>

注意,我们把上面的代码分别保存成两个文件再进行操作。

根据我的理解php生成随机密码就是我们把一些要生成的字符预置一个的字符串包括数字拼音之类的以及一些特殊字符,这样我们再随机取字符组成我们想要的随机密码了。

下面总结了一些实例各位朋友可参考。

例1

最简洁的生成方法

 代码如下 复制代码


function generatePassword($length=8)
{
    $chars = array_merge(range(0,9),
                     range('a','z'),
                     range('A','Z'),
                     array('!','@','$','%','^','&','*'));
    shuffle($chars);
    $password = '';
    for($i=0; $i<8; $i++) {
        $password .= $chars[$i];
    }
    return $password;
}


 

例2

1、在 33 – 126 中生成一个随机整数,如 35,
2、将 35 转换成对应的ASCII码字符,如 35 对应 #
3、重复以上 1、2 步骤 n 次,连接成 n 位的密码

 代码如下 复制代码

function create_password($pw_length = 8)
{
    $randpwd = '';
    for ($i = 0; $i < $pw_length; $i++)
    {
        $randpwd .= chr(mt_rand(33, 126));
    }
    return $randpwd;
}

// 调用该函数,传递长度参数$pw_length = 6
echo create_password(6);

实例

 代码如下 复制代码

<?php
mt_srand((double) microtime() * 1000000);
 
function gen_random_password($password_length = 32, $generated_password = ""){
 $valid_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
 $chars_length = strlen($valid_characters) - 1;
 for($i = $password_length; $i--; ) {
  //$generated_password .= $valid_characters[mt_rand(0, $chars_length)];
 
  $generated_password .= substr($valid_characters, (mt_rand()%(strlen($valid_characters))), 1);
 }
 return $generated_password;
}
 
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>php 密码生成器 v 4.0</title>
<style type="text/css">
body {
 font-family: Arial;
 font-size: 10pt;
}
</style>
</head>
<body>
<span style="font-weight: bold; font-size: 15pt;">密码生成器v4.0 by freemouse</span><br /><br />
<?php
 
if (isset($_GET['password_length'])){
 if(preg_match("/([0-9]{1,8})/", $_GET['password_length'])){
  print("密码生成成功:<br />
<span style="font-weight: bold">" . gen_random_password($_GET['password_length']) . "</span><br /><br />n");
 } else {
  print("密码长度不正确!<br /><br />n");
 }
}
 
print <<< end
请为密码生成其指定生成密码的长度:<br /><br />
<form action="{$_SERVER['PHP_SELF']}" method="get">
 <input type="text" name="password_length">
 <input type="submit" value="生成">
</form>
end;
 
?>
</body>
</html>

例4


1、预置一个的字符串 $chars ,包括 a – z,A – Z,0 – 9,以及一些特殊字符
2、在 $chars 字符串中随机取一个字符
3、重复第二步 n 次,可得长度为 n 的密码

 代码如下 复制代码

function generate_password( $length = 8 ) {
    // 密码字符集,可任意添加你需要的字符
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';

    $password = '';
    for ( $i = 0; $i < $length; $i++ )
    {
        // 这里提供两种字符获取方式
        // 第一种是使用 substr 截取$chars中的任意一位字符;
        // 第二种是取字符数组 $chars 的任意元素
        // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }

    return $password;
}


上面经过测试性能都不如下面这个

1、预置一个的字符数组 $chars ,包括 a – z,A – Z,0 – 9,以及一些特殊字符
2、通过array_rand()从数组 $chars 中随机选出 $length 个元素
3、根据已获取的键名数组 $keys,从数组 $chars 取出字符拼接字符串。该方法的缺点是相同的字符不会重复取。

 代码如下 复制代码

function make_password( $length = 8 )
{
    // 密码字符集,可任意添加你需要的字符
    $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
    'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
    't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',
    'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',
    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!',
    '@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_',
    '[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',',
    '.', ';', ':', '/', '?', '|');

    // 在 $chars 中随机取 $length 个数组元素键名
    $keys = array_rand($chars, $length);

    $password = '';
    for($i = 0; $i < $length; $i++)
    {
        // 将 $length 个数组元素连接成字符串
        $password .= $chars[$keys[$i]];
    }

    return $password;
}

文章来给各位同学介绍在PHP命令行执行PHP脚本的注意事项总结,如果你不注意这些东西,很可能服务器安全就出问题哦。

如果你使用的wamp集成安装环境的话,那么你php的配置是在D:/wamp/bin/apache/Apache2.2.17/bin
你要先把他复制覆盖掉D:/wamp/bin/php/php5.3.3下的php.ini,否则当你调用扩展函数的时候会报错误如:Fatal error: Call to undefined function

如果你懒得写那么大长串php的路径,你也可以把D:/wamp/bin/php/php5.3.3加到环境变量path里面。
另外关于传参的问题。 比如我要执行test.php?a=123
命令行中我们就可以写 php test.php 123
在test.php中使用$argv[1]来接收123.

建一个简单的文本文件,其中包含有以下PHP代码,并把它保存为hello.php:

 代码如下 复制代码

<?php
echo "Hello from the CLI";
?>

现在,试着在命令行提示符下运行这个程序,方法是调用CLI可执行文件并提供脚本的文件名:

 代码如下 复制代码
#php phphello.php
输出Hello from the CLI

附上一个bat的可执行文件作为参考

 代码如下 复制代码

@echo off

php D:/wamp/www/taobao/items.php 158345687

php D:/wamp/www/taobao/refunds_up.php 158345687

php D:/wamp/www/taobao/trade.php 158345687

echo.&echo 请按任意键关闭BAT窗口...&pause

exit


一些常用的执行命令的代码

下是 PHP 二进制文件(即 php.exe 程序)提供的命令行模式的选项参数,您随时可以通过 PHP -h 命令来查询这些参数。
Usage: php [options] [-f] <file> [args...]
       php [options] -r <code> [args...]
       php [options] [-- args...]
  -s               Display colour syntax highlighted source.
  -w               Display source with stripped comments and whitespace.
  -f <file>        Parse <file>.
  -v               Version number
  -c <path>|<file> Look for php.ini file in this directory
  -a               Run interactively
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -z <file>        Load Zend extension <file>.
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -i               PHP information
  -r <code>        Run PHP <code> without using script tags <?..?>
  -h               This help
 
  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

CLI SAPI 模块有以下三种不同的方法来获取您要运行的 PHP 代码:

  在windows环境下,尽量使用双引号, 在linux环境下则尽量使用单引号来完成。


1.让 PHP 运行指定文件。

 代码如下 复制代码

php my_script.php
 
php -f  "my_script.php"

以上两种方法(使用或不使用 -f 参数)都能够运行给定的 my_script.php 文件。您可以选择任何文件来运行,您指定的 PHP 脚本并非必须要以 .php 为扩展名,它们可以有任意的文件名和扩展名。

2.在命令行直接运行 PHP 代码。

 代码如下 复制代码

php -r "print_r(get_defined_constants());"

在使用这种方法时,请您注意外壳变量的替代及引号的使用。

注: 请仔细阅读以上范例,在运行代码时没有开始和结束的标记符!加上 -r 参数后,这些标记符是不需要的,加上它们会导致语法错误。

3.通过标准输入(stdin)提供需要运行的 PHP 代码。

以上用法给我们提供了非常强大的功能,使得我们可以如下范例所示,动态地生成 PHP 代码并通过命令行运行这些代码:

 代码如下 复制代码

$ some_application | some_filter | php | sort -u >final_output.txt

本文章来给各位同学介绍一个简单的PHP/Shell大文件数据统计并且排序实现程序,各位同学可参考使用哦。

诸多大互联网公司的面试都会有这么个问题,有个4G的文件,如何用只有1G内存的机器去计算文件中出现次数做多的数字(假设1行是1个数组,例如QQ号码)。如果这个文件只有4B或者几十兆,那么最简单的办法就是直接读取这个文件后进行分析统计。但是这个是4G的文件,当然也可能是几十G甚至几百G的文件,这就不是直接读取能解决了的。

同样对于如此大的文件,单纯用PHP做是肯定行不通的,我的思路是不管多大文件,首先要切割为多个应用可以承受的小文件,然后批量或者依次分析统计小文件后再把总的结果汇总后统计出符合要求的最终结果。类似于比较流行的MapReduce模型,其核心思想就是“Map(映射)”和“Reduce(化简)”,加上分布式的文件处理,当然我能理解和使用到的只有Reduce后去处理。

假设有1个10亿行的文件,每行一个6位-10位不等的QQ号码,那么我需要解决的就是计算在这10亿个QQ号码中,重复最多的前10个号码,使用下面的PHP脚本生成这个文件,很可能这个随机数中不会出现重复,但是我们假设这里面会有重复的数字出现。

 代码如下 复制代码

$fp = fopen('qq.txt','w+');
for( $i=0; $i<1000000000; $i++ ){
    $str = mt_rand(10000,9999999999)."n";
    fwrite($fp,$str);
}
fclose($fp);

生成文件的世界比较长,Linux下直接使用php-client运行PHP文件会比较节省时间,当然也可以使用其他方式生成文件。生成的文件大约11G。

然后使用Linux Split切割文件,切割标准为每100万行数据1个文件。

 

 代码如下 复制代码
split -l 1000000 -a 3 qq.txt qqfile

qq.txt被分割为名字是qqfileaaa到qqfilebml的1000个文件,每个文件11mb大小,这时再使用任何处理方法都会比较简单了。我还是使用PHP进行分析统计:

 代码如下 复制代码

$results = array();
foreach( glob('/tmp/qq/*') as $file ){
    $fp = fopen($file,'r');
    $arr = array();
    while( $qq = fgets($fp) ){
        $qq = trim($qq);
        isset($arr[$qq]) ? $arr[$qq]++ : $arr[$qq]=1;
    }
    arsort($arr);
    //以下处理方式存在问题
    do{
        $i=0;
        foreach( $arr as $qq=>$times ){
            if( $i > 10 ){
                isset($results[$qq]) ? $results[$qq]+=$times : $results[$qq]=$times;
                $i++;
            } else {
                break;
            }
        }
    } while(false);
    fclose($fp);
}
if( $results ){
    arsort($results);
    do{
        $i=0;
        foreach( $results as $qq=>$times ){
            if( $i > 10 ){
                echo $qq . "t" . $times . "n";
                $i++;
            } else {
                break;
            }
        }
    } while(false);
}

这样每个样本取前10个,最后放到一起分析统计,不排除有个数在每个样本中都排名第11位但是总数绝对在前10的可能性,所以后面统计计算算法还需要改进。

也许有人说使用Linux中的awk和sort命令可以完成排序,但是我试了下如果是小文件还可以实现,但是11G的文件,不管是内存还是时间都无法承受。下面是我改的1个awk+sort的脚本,或许是写法有问题,求牛人指导。

 代码如下 复制代码

awk -F '\@' '{name[$1]++ } END {for (count in name) print name[count],count}' qq.txt |sort -n > 123.txt


互联网几何级增长,未来不管是大文件处理还是可能存在的大数据都存在很大的需求空间

我们要取远程服务器中网页的图片然后保存到我们本地需要珍到php fopen或curl等等这类的函数,下面我给大家介绍几个常用的实例。


fopen函数实例

ob_start : 打开输出缓冲

readfile : 读入一个文件并写入到输出缓冲
返回从文件中读入的字节数。如果出错返回 FALSE 并且除非是以 @readfile() 形式调用,否则会显示错误信息。

ob_get_contents : Return the contents of the output buffer(返回输出缓冲的内容)
This will return the contents of the output buffer without clearing it or FALSE, if output buffering isn’t active. (如果输出缓冲没有活动(打开),则返回 FALSE)

ob_end_clean() : Clean (erase) the output buffer and turn off output buffering(清除输出缓冲)

 代码如下 复制代码


<?php
//URL是远程的完整图片地址,不能为空, $filename 是另存为的图片名字
//默认把图片放在以此脚本相同的目录里
function GrabImage($url,$filename=""){
        if($url == ""){
            return false;
        }
       
        $ext=strrchr($url,".");
       
        if($ext != ".gif" && $ext != ".jpg" && $ext != ".bmp" && $ext != ".png"){
            echo "格式不支持!";
            return false;
        }
       
        if($filename == ""){
            $filename = time()."$ext";
        }
       
        ob_start();
        readfile($url);
        $img=ob_get_contents();
        ob_end_clean();
        $size=strlen($img);
        $fp2=fopen($filename,"a");
        if(fwrite($fp2,$img) === false){
            echo "不能写入文件".$filename;
            exit();
        }else{
            echo "保存图片成功!";
        }
        fclose($fp2);
        return $filename;
       
    }
//测试
GrabImage("/logo.png","as.png");
?>


php下载远程图片函数 可伪造来路


$gurl 要下载的图片地址
$rfurl 来路。如果目标图像做了防盗链设置,可以绕过。
$filename 下载图片保存的文件名,相对路径,不要用realpath
$gcookie 调整cookie 伪造的cookie
$JumpCount 跳转计数
$maxtime 最大次数
调用方法:DownImageKeep(“http://www.baidu.com/img/baidu_jgylogo2.gif”,”http://baidu.com”,”a.gif”,”",0,10);

 代码如下 复制代码

function DownImageKeep($gurl, $rfurl, $filename, $gcookie=”", $JumpCount=0, $maxtime=30)
{
$urlinfos = GetHostInfo($gurl);
$ghost = trim($urlinfos['host']);
if($ghost==”)
{
return FALSE;
}
$gquery = $urlinfos['query'];
if($gcookie==”" && !empty($rfurl))
{
$gcookie = RefurlCookie($rfurl);
}
$sessionQuery = “GET $gquery HTTP/1.1rn”;
$sessionQuery .= “Host: $ghostrn”;
$sessionQuery .= “Referer: $rfurlrn”;
$sessionQuery .= “Accept: */*rn”;
$sessionQuery .= “User-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)rn”;
if($gcookie!=”" && !preg_match(“/[rn]/”, $gcookie))
{
$sessionQuery .= $gcookie.”rn”;
}
$sessionQuery .= “Connection: Keep-Alivernrn”;
$errno = “”;
$errstr = “”;
$m_fp = fsockopen($ghost, 80, $errno, $errstr,10);
fwrite($m_fp,$sessionQuery);
$lnum = 0;

//获取应答头
$m_httphead = Array();
$httpstas = explode(” “,fgets($m_fp,256));
$m_httphead["http-edition"] = trim($httpstas[0]);
$m_httphead["http-state"] = trim($httpstas[1]);
while(!feof($m_fp))
{
$line = trim(fgets($m_fp,256));
if($line == “” || $lnum>100)
{
break;
}
$hkey = “”;
$hvalue = “”;
$v = 0;
for($i=0; $i {
if($v==1)
{
$hvalue .= $line[$i];
}
if($line[$i]==”:”)
{
$v = 1;
}
if($v==0)
{
$hkey .= $line[$i];
}
}
$hkey = trim($hkey);
if($hkey!=”")
{
$m_httphead[strtolower($hkey)] = trim($hvalue);
}
}

if(preg_match(“/^3/”, $m_httphead["http-state"]))
{
if(isset($m_httphead["location"]) && $JumpCount<3) { $JumpCount++; DownImageKeep($gurl,$rfurl,$filename,$gcookie,$JumpCount); } else { return FALSE; } } if(!preg_match(“/^2/”, $m_httphead["http-state"])) { return FALSE; } if(!isset($m_httphead)) { return FALSE; } $contentLength = $m_httphead['content-length']; //保存图片 $fp = fopen($filename,”w”) or die(“写入文件:{$filename} 失败!”); $i=0; $okdata = “”; $starttime = time(); while(!feof($m_fp)) { $okdata .= fgetc($m_fp); $i++; //超时退出 if(time()-$starttime>$maxtime)
{
break;
}

//到达指定大小结束
if($i >= $contentLength)
{
break;
}
}
if($okdata!=”")
{
fwrite($fp,$okdata);
}
fclose($fp);
if($okdata==”")
{
@unlink($filename);
fclose($m_fp);
return FALSE;
}
fclose($m_fp);
return TRUE;
}
//获得网址的host和query部份
function GetHostInfo($gurl)
{
$gurl = preg_replace(“/^http:///i”, “”, trim($gurl));
$garr['host'] = preg_replace(“//(.*)$/i”, “”, $gurl);
$garr['query'] = “/”.preg_replace(“/^([^/]*)//i”, “”, $gurl);
return $garr;
}
//获得页面返回的Cookie信息
function RefurlCookie($gurl)
{
global $gcookie,$lastRfurl;
$gurl = trim($gurl);
if(!empty($gcookie) && $lastRfurl==$gurl)
{
return $gcookie;
}
else
{
$lastRfurl=$gurl;
}
if(trim($gurl)==”)
{
return ”;
}
$urlinfos = GetHostInfo($gurl);
$ghost = $urlinfos['host'];
$gquery = $urlinfos['query'];
$sessionQuery = “GET $gquery HTTP/1.1rn”;
$sessionQuery .= “Host: $ghostrn”;
$sessionQuery .= “Accept: */*rn”;
$sessionQuery .= “User-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)rn”;
$sessionQuery .= “Connection: Closernrn”;
$errno = “”;
$errstr = “”;
$m_fp = fsockopen($ghost, 80, $errno, $errstr,10) or die($ghost.’
‘);
fwrite($m_fp,$sessionQuery);
$lnum = 0;

//获取详细应答头
$gcookie = “”;
while(!feof($m_fp))
{
$line = trim(fgets($m_fp,256));
if($line == “” || $lnum>100)
{
break;
}
else
{
if(preg_match(“/^cookie/i”, $line))
{
$gcookie = $line;
break;
}
}
}
fclose($m_fp);
return $gcookie;
}

标签:[!--infotagslink--]

您可能感兴趣的文章: