首页 > 编程技术 > php

php读取文件的方法

发布时间:2016-11-25 16:12

PHP读写文件,就如同ASP中使用FSO进行文件的读写操作。当然在ASP中FSO仅对于运行当前程序的服务器磁盘上文件进行读写(很明显就是需要获得物理路径),然而PHP可以通过FTP或HTTP打开文件进行读写。

一,PHP如何读取文件

     PHP读取文件可以读取当前服务器或远程服务器中的文件。其步骤是:打开文件、读文件和关闭文件。

1,PHP如何打开文件

     使用PHP函数fopen()打开一个文件,fopen()一般使用2个参数表示打开文件的路径和文件模式。比如:

$fp=fopen("../111cn.txt",'w');

 

其中 "../cnbruce.txt" 就表示打开的cnbruce.txt文件的路径(相对当前执行程序文件的路径),'w'表示以只写的方式打开该文本文件。

附录:fopen()函数的文件模式总结

r    只读——读模式,打开文件,从文件头开始读
r+    可读可写方式打开文件,从文件头开始读写
w    只写——写方式打开文件,同时把该文件内容清空,把文件指针指向文件开始处。如果该文件已经存在,将删除文件已有内容;如果该文件不存在,则建立该文件
w+    可读可写方式打开文件,同时把该文件内容清空,把文件指针指向文件开始处。如果该文件不存在,则建立该文件
a    追加    以只写方式打开文件,把文件指针指向文件末尾处。如果该文件不存在,则建立该文件
a+    追加    以可读可写方式打开文件,把文件指针指向文件末尾处。如果该文件不存在,则建立该文件
b    二进制    用于于其他模式进行连接。建议使用该选项,以获得更大程度的可移植性

注意,如果fopen()函数调用失败,函数将返回false。否则返回指针数据。所以一般在打开了文件后\读写文件前需要检测下文件是否存在。


<?php
@ $fp=fopen("http://www.111cn.net/a3",'w');
if (!$fp)
{
    echo'文件不存在';
    exit;
}
?>

 

其中@符号表示PHP将抑制所有由当前函数调用产生的错误。

2,PHP如何读文件

在PHP打开了文件之后就需要对文件进行读取,一般是使用fgets()函数

该函数可以从文件中每次读取一行内容,其不断读入数据,值到遇到本行的换行符,或者全文的结束符号EOF。

介于fgets()函数只能读取一行数据,所以若需要读取文件的所有数据,须使用循环语句来完成。比如:


while (!feof($fp))
{
    $bruce=fgets($fp);
    echo $bruce;
}

 

其中feof()函数是用来检测文件是否结束的。该函数唯一参数就是文件指针(即$fp对应打开的文件)。

当然,在PHP中还可以使用readfile()函数一次读取整个文件。该函数包括了打开文件、读取文件并输出到浏览器中和关闭文件。比如:


<?php
$bruce=readfile("http://www.111cn.net");
echo $bruce;
?>

 

3,PHP如何关闭文件

使用函数fclose()就可以将文件关闭。

二,PHP如何写数据到文件

与PHP读取文件一样,PHP写入文件也需要:打开文件、写入数据和关闭文件。打开和关闭文件的方法上面已经说明,那PHP中写入数据到文件是怎样的呢。

使用fwrite()函数,比如fwrite(文件路径,写入内容)



<?php
$bruce=fopen("http://www.111cn.net/","r");
if(!$bruce)
{
    echo'文件不存在';
    exit;
}
while (!feof($bruce))
{
    $rose=fgets($bruce);
        $james=fopen("index.htm","a");
        fwrite($james,$rose);
        fclose($james);
}
fclose($bruce);
?>
<a href="index.htm">将111cn.net的内容生成了本地文件</a>

 


了解了PHP的读写文件,就可以把最简单的数据存入文本保存了。也就可以做个故事接龙了。

=============================
其他有用的文件函数:

file_exists():查看文件是否存在,返回布尔值
filesize():查看文件大小,可直接echo输出
unlink():删除文件,注意PHP中没有delete函数。

pdo分页

<?php
$page = $_GET['page'];
$dsn = "mysql:host=localhost;dbname=bbv1";
$db  = new PDO($dsn,'root','');        //pdo链接
$num = 10;                             //每页显示的文章数目
$pagea=($page-1)*$num;
foreach ($db->query("SELECT * from article Limit $pagea,$num") as $row)
  {
        echo "<hr>";
        print_r("<a href=delete.php?id=".$row[0].">删除</a>");
        print_r($row[1]);
        print_r($row[2]);
  print_r($row[3]);
   }
$rs = $db->query("select COUNT(*) from article");    //取得数据总数
$count = $rs->fetchColumn();
$pagenum = ceil($count/$num);
?>
<hr>
<a href="insert.php">添加文章</a>
<br>
文章总数:<?php echo"$count" ?>
<br>
文章总页:<?php echo"$pagenum"?>
<hr>
<?php
For($i=1;$i<=$pagenum;$i++){
      
       $show=($i!=$page)?"<a href='index.php?page=".$i."'>$i</a>":"<b>$i</b>";
       Echo $show." ";
}
$db=null;
?>


刚用PHP写了一个网站在线人数的程序,请大家进来指点下!
我是用PHP+MYSQL来写的,原理:网站在线人数的程序代码+后台有MYSQL数据库支持,可以直接统计出网站当前的在线人数。
首先我创建MYSQL数据库表。
CREATE TABLE tablename (
field type(max_length) DEFAULT 'default_value' (NOT) NULL
}可以使用的SQL语句。
CREATE TABLE useronline (
timestamp int(15) DEFAULT '0' NOT NULL,
ip varchar(40) NOT NULL,
file varchar(100) NOT NULL,
PRIMARY KEY (timestamp),
KEY ip (ip),
KEY file (file)
);下面我们是PHP脚本,首先我定义MYSQL的信息。
$server = "localhost"; //你的服务器
$db_user = "root"; //你的mysql的用户名
$db_pass = "password"; //你的mysql的密码
$database = "users"; //表的名字设置统计的时间(多少秒内在线人数)
$timeoutseconds = 300;取当前时间。
$timestamp = time();上面的完整代码:
<?php
$server = "localhost"; //your server
$db_user = "root"; //your mysql database username
$db_pass = "password"; //your mysql database password if any
$database = "users"; //the db name
$timeoutseconds = 300;//timeoutseconds limit
//get the current time
$timestamp = time();
//calculate the lowest timestamp allowed
$timeout = $timestamp-$timeoutseconds;
?>连接mysql
mysql_connect('localhost', 'username', 'password');也允许使用变量形式。
mysql_connect($server, $db_user, $db_pass);如果mysql数据库没有密码的话可以使用下面代码连接
mysql_connect($server, $db_user);查询数据库的代码:
mysql_db_query('database', 'query');我们只要有访客就要增加一条记录。
$insert = mysql_db_query($database, "INSERT INTO useronline VALUES
('$timestamp','".$_SERVER['REMOTE_ADDR']."','".$_SERVER['PHP_SELF']."')");
如果用户用错误信息的话,这样处理。
if(!($insert)) {
print "Useronline Insert Failed > ";
}然后实现当超过设置的时间就删除该用户记录。
$delete = mysql_db_query($database, "DELETE FROM useronline WHERE timestamp<$timeout");同样给出删除记录出错的处理。
if(!($delete)) {
print "Useronline Delete Failed > ";
}下面我们解决数据库中不同IP的问题
$result = mysql_db_query($database, "SELECT DISTINCT ip FROM useronline WHERE file='".$_SERVER['PHP_SELF']."' ");使用
mysql_num_rows(query);来统计用户,代码如下。
$user = mysql_num_rows($result);最后关闭数据库。
mysql_close();显示在线的人数。
if($user == 1) {
print("1 user online\n");
} else {
print("$user users online\n");
}最终把上面代码写成一个PHP文件如下。
<?php
//Put your basic server info here
$server = "localhost"; //normally localhost
$db_user = "root"; //your MySQL database username
$db_pass = "password"; //your MySQL database password
$database = "users";
$timeoutseconds = 300; //it will delete all people which haven't refreshed(so probbably are
// offline or inactive) in $timieoutseconds time (so it actually checks the people that are active in the last
// $timeoutseconds seconds)
//this is where PHP gets the time
$timestamp = time();
//counts the timeout, all people which have been seen last online in earlier than this timestamp, will get removed
$timeout = $timestamp-$timeoutseconds;
//connect to database
mysql_connect($server, $db_user);
//add the timestamp from the user to the online list
$insert = mysql_db_query($database, "INSERT INTO useronline VALUES
('$timestamp','".$_SERVER['REMOTE_ADDR']."','".$_SERVER['PHP_SELF']."')");
if(!($insert)) {
print "Useronline Insert Failed > ";
}
//delete the peoples which haven't been online/active in the last $timeoutseconds seconds.
$delete = mysql_db_query($database, "DELETE FROM useronline WHERE timestamp<$timeout");
if(!($delete)) {
print "Useronline Delete Failed > ";
}
//select the amount of people online, all uniques, which are online on THIS page
$result = mysql_db_query($database, "SELECT DISTINCT ip FROM useronline WHERE file='".$_SERVER['PHP_SELF']."' ");
if(!($result)) {
print "Useronline Select Error > ";
}
//Count the number of rows = the number of people online
$user = mysql_num_rows($result);
//spit out the results
mysql_close();
if($user == 1) {
print("1 user online\n");
} else {
print("$user users online\n");
}
?>

 

 

head>
<title>survey</title>
</head>
<body>
<form method="POST" action="survey.php">
  <p><input type="radio" value="0" name="vote">调查项目一</p>
  <p><input type="radio" name="vote" value="1">调查项目二</p>
  <p><input type="radio" name="vote" value="2">调查项目三</p>
  <p><input type="radio" name="vote" value="3">调查项目四</p>
  <p><input type="radio" name="vote" value="4">调查项目五</p>
  <p><input type="hidden" name="go"  value="1">
  <p><input type="submit" value="提交" name="B1"></p>
  <a href="survey.php?result=1">查看结果</a>
</form>
</body>
</html>
 

注意文件data.txt中的调查项目与上面的调查项目在个数和排列顺序必须保持一致,否则会出错或调查的结果不准确。同时为了将调查结果显示成条形图形式,应该准备若干种不同颜色的条形图片。如:0.gif,1.gif,2.gif,3.gif,4.gif等。
以下是实现调查功能的survey.php代码:

以下为引用的内容:
<?
    data="data.txt";
    votes="survey.txt";
    dataf=file(data);        /*读出调查项目文件中的项目*/
     file_votes=fopen(votes, "r");
  line_votes=fgets(file_votes, 255);  /*读出已经记录的调查结果*/
  fclose(file_votes);
  single_vote=explode("|", line_votes); /* 并将数据按指定的字串切开,再将字串传回到数组变量中  */
   if (result!=1)         /*如果已经接受了调查*/
   {
    file_votes=file(votes, "r");
    if (REMOTE_ADDR == file_votes[1])                           /*检查是不是同一个人*/
      {
       echo "<center><font color=red>您已投过票了,谢谢您的参与!</font></center>";
       exit;
      }
    /*如果IP不重复,则执行以下程序*/
    ficdest=fopen(votes, "w");
    for (i=0; i<=count(dataf)-1; i++)
      {
         if (i == vote)
         {                                 /*判断选择了哪个项目*/ Chinaz.com

          single_vote+=1;
         }
             fputs(ficdest, "single_vote|"); /*将数据写回文件*/
      }
       fputs(ficdest, "\nREMOTE_ADDR");/* //写入投票者IP*/
    fclose(ficdest);
    result=1; /*投票成功*/
  }
  /*写入投票结果后并显示投票结果*/
  if (result==1)
  {
   echo "<table cellpadding=10>";
   for (i=0; i<=count(dataf)-1; i++)
    {
     /*取得投票总数*/
     tot_votes+=single_vote;
    }
   for (i=0; i<=count(dataf)-1; i++)
    {
     imag=strval(i).".gif";/*判断用哪种条形图片来显示统计结果*/
      stat=single_vote/tot_votes*100;  /*计算百分比*/
     scla=stat*5;/*条形图和放大倍数,这里是安百分数的5倍的相素的宽度来显示的*/
     echo "<tr><td><li><font face=Verdana size=2>";
     echo "dataf</font></td><td align=left><font face=Verdana size=2>";
     echo "<img" width=100% src=\"imag\" height=20 width=scla align=middle> ";/*输出条形码图*/
     printf("%.1f", "stat");
     echo "%</font></td><td align=center><font face=Verdana size=2>";
     /*输出本栏目投票数*/
     echo "single_vote</font>";
     echo "</td></tr>";
   }
   echo "</table><p>";
   echo "<font face=Verdana size=2>总投票数:tot_votes </font>";
}
?> 

说明:
在这里为了防止一人多投是采用记录最近的一位投票者的IP的方法来实现的,而最近的一位投票的IP地址是WEB客户机在对服务器发出请求时存储在环境变量REMOTE_ADDR中的。


<?php
class conn{
function __construct(){
  require("config.php");
  $conn = @mysql_connect($host,$root,$pass);
  @mysql_select_db($db);
  if(!$conn){
   echo "无法连接".mysql_errno() . ":" . mysql_error() ;
   exit;
  }
}
function query($sql){
  $result = @mysql_query($sql);
  if (!$result) {
   echo mysql_errno().":".mysql_error();
   exit;
  }
  return $result;
}
function next($result){
  return  @mysql_fetch_array($result);
}
function count_row($result){
  $row = @mysql_num_rows($result);
  return $row;
}
function close($result){
  @mysql_free_result($result);
  @mysql_close();
}
}
class fenye extends conn{
public $sql;
public $page;
public $countpage;
public $pagesize;
public $result;
function __construct($sql,$page,$pagesize){
  $this->sql = $sql;
  $this->page = $page;
  $this->countpage = $countpage;
  $this->pagesize = $pagesize;
  parent::__construct();
  $result = parent::query($sql);
  $num = parent::count_row($result);
  $this->countpage = ceil($num/$pagesize);
  $a = ($page-1)*$pagesize;
  $limit = "limit $a,$pagesize";
  $this->sql = $sql.$limit;
  $this->result = parent::query($this->sql);
}
function getlimit(){
  return $this->sql;
}
    function next(){
     return parent::next($this->result);
    }
function foor(){
  $a = $this->page -1;
  $b = $this->page +1;
  if ($this->page == 1) {
   echo "首页"."    ";
  }else  echo "<a href='?page=1'>首页</a>"."    ";
  if($this->page >1)
     echo "<a href='?page=$a'>上页</a>"."    ";
  else  echo "上页    ";
  for ($i =1;$i <= $this->countpage;$i++){
   echo "<a href='?page=$i'>$i</a>"."       ";
  }
  if($this->page < $this->countpage)
      echo "<a href='?page=$b'>下页</a>"."    ";
  else  echo "下页    ";
  if ($this->page == $this->countpage) {
   echo "末页"."    ";
  }else   echo "<a href='?page=$this->countpage'>末页</a>";
  #######################
 
}
}
####################
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else  $page = 1;
$sql = "select * from guestbook ";
$pagesize =3;
$p = new fenye($sql,$page,$pagesize); 
$sql = $p->getlimit();
$result = $p->query($sql);
while($row = $p->next()){
echo $row['id']."<br>";
}
$p->foor();
$p->close($result);
?>

 

标签:[!--infotagslink--]

您可能感兴趣的文章: