当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP读取CURL模拟登录时生成Cookie文件的方法

PHP读取CURL模拟登录时生成Cookie文件的方法

2019年06月02日  | 移动技术网IT编程  | 我要评论

本文实例讲述了php读取curl模拟登录时生成cookie文件的方法。分享给大家供大家参考。具体实现方法如下:

在使用php中的curl模拟登录时会保存一个cookie文件,例如下面的代码

复制代码 代码如下:
$login_url = 'xxx'; 
 
$post_fields['email'] = 'xxxx'; 
$post_fields['password'] = 'xxxx'; 
$post_fields['origurl'] = 'xxx'; 
$post_fields['domain'] = 'xxx.com'; 
//cookie文件存放在网站根目录的temp文件夹下 
$cookie_file = tempnam('./temp','cookie'); 
 
$ch = curl_init($login_url); 
curl_setopt($ch, curlopt_useragent, 'mozilla/5.0 (windows; u; windows nt 5.1; zh-cn; rv:1.9.1.5) gecko/20091102 firefox/3.5.5'); 
curl_setopt($ch, curlopt_header, 0); 
curl_setopt($ch, curlopt_returntransfer, 1); 
curl_setopt($ch, curlopt_maxredirs, 1); 
curl_setopt($ch, curlopt_followlocation, 1); 
curl_setopt($ch, curlopt_autoreferer, 1); 
curl_setopt($ch, curlopt_post, 1); 
curl_setopt($ch, curlopt_postfields, $post_fields); 
curl_setopt($ch, curlopt_cookiejar, $cookie_file); 
curl_exec($ch); 
curl_close($ch); 
 
//带上cookie文件,访问需要访问的页面 
$send_url='xxx.com'; 
$ch = curl_init($send_url); 
curl_setopt($ch, curlopt_header, 0); 
curl_setopt($ch, curlopt_returntransfer, 1); 
curl_setopt($ch, curlopt_cookiefile, $cookie_file); 
$contents = curl_exec($ch); 
curl_close($ch); 
 
//清理cookie文件 
unlink($cookie_file); 
 
//输出网页内容 
print_r($contents);

在temp文件夹下保存一个cookie前缀的临时文件,例如:coo3a98.tmp文件
打开这个文件得到如下代码:

要使用php来格式化该文件,使用以下代码就能实现

复制代码 代码如下:
<?php  
$cookie_folder = dirname(__file__)."/temp"; 
$lines = file($cookie_folder.'/coo3a98.tmp'); 
 
$trows = ''; 
 
foreach($lines as $line) { 
    if($line[0] != '#' && substr_count($line, "\t") == 6) { 
        $tokens = explode("\t", $line); 
        $tokens = array_map('trim', $tokens); 
        $tokens[4] = date('y-m-d h:i:s', $tokens[4]); 
        $trows .= '<tr><td>' . implode('</td><td>', $tokens) . '</td></tr>' . php_eol; 
    } 

echo '<table>'.php_eol.'<tbody>'.php_eol.$trows.'</tbody>'.php_eol.'</table>'; 
?>

运行之后就如下图所示,已经被写入到table当中

大功告成,如果只读取其中字段可自行修改即可。

希望本文所述对大家的php程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网