PHP全栈学习笔记7

2019-04-25 06:58:26来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

PHP全栈学习笔记7

图形图像处理技术,gd库的强大支持,PHP的图像可以是PHP的强项,PHP图形化类库,jpgraph是一款非常好用的强大的图形处理工具。

在PHP中加载GD库

gd官方网址下载:

http://www.boutell.com/gd

激活gd库,修改php.in文件

将该文件中的“;extension=php_gd2.dll”选项前的分号“;”删除

验证GD库是否安装成功
输入“127.0.0.1/phpinfo.php”并按Enter键,检索到的安装信息,即说明GD库安装成功。

Jpgraph的安装与配置

官方网站http://www.aditus.nu/jpgraph/下载

解压到文件夹,编辑php.ini文件,修改include_path参数,如include_path = ".;F:\AppServ\www\jpgraph",重新启动Apache。

配置Jpgraph类库的文件jpg-config.inc.php,
支持中文的配置

DEFINE('CHINESE_TTF_FONT','bkai00mp.ttf');

默认图片格式的配置

DEFINE("DEFAULT_GFORMAT","auto");

创建画布,可以通过imagecreate()函数实现

<?php
$im = imagecreate(200,100);
$white = imagecolorallocate($im, 255,65,150);
imagegif($im);
?>

gd库支持中文,但只能是utf-8,使用imageString()会显示乱码,只能接收utf-8编码格式,默认使用英文字体。

header()函数定义输出图像类型
imagecreatefromjpeg()函数载入图片
imagecolorallocate()函数设置输出字体颜色
iconv()函数对输出的中文字符串的编码格式进行转换
imageTTFText()函数向照片中添加文字

<?php
header("content-type:image/jpeg");
$im = imagecreateformjpeg("images/photo.jpg");
$textcolor = imagecolorallocate($im, 35,35,23);

//定义字体
$fnt="c:/windows/fonts/simhei.ttf";
//定义输出字体串
$motto = iconv("gb2312","utf-8","长白山");
// 写文字
imageTTFText($im, 220,0,200,233, $textcolor, $fnt, $motto); // 写TTF文字到图中
// 简历里jpeg图形
imageipeg($im);
imagedestory($im);
?>

使用图像处理技术生成的验证码

<?php
session_start();
header("content-type:image/png");     //设置创建图像的格式
$image_width=70;                      //设置图像宽度
$image_height=18;                     //设置图像高度
srand(microtime()*100000);            //设置随机数的种子
for($i=0;$i<4;$i++){                  //循环输出一个4位的随机数
   $new_number.=dechex(rand(0,15));
}
$_SESSION[check_checks]=$new_number;    //将获取的随机数验证码写入到SESSION变量中     

$num_image=imagecreate($image_width,$image_height);  //创建一个画布
imagecolorallocate($num_image,255,255,255);          //设置画布的颜色
for($i=0;$i<strlen($_SESSION[check_checks]);$i++){  //循环读取SESSION变量中的验证码
   $font=mt_rand(3,5);                              //设置随机的字体
   $x=mt_rand(1,8)+$image_width*$i/4;               //设置随机字符所在位置的X坐标
   $y=mt_rand(1,$image_height/4);                   //设置随机字符所在位置的Y坐标
   $color=imagecolorallocate($num_image,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));       //设置字符的颜色
   imagestring($num_image,$font,$x,$y,$_SESSION[check_checks][$i],$color);                   //水平输出字符
}
imagepng($num_image);               //生成PNG格式的图像
imagedestroy($num_image);           //释放图像资源
?>
<?php
session_start();
if($_POST["Submit"]!=""){
$checks=$_POST["checks"];
if($checks==""){
echo "<script> alert('验证码不能为空');window.location.href='index.php';</script>";
}
if($checks==$_SESSION[check_checks]){
    echo "<script> alert('用户登录成功!');window.location.href='index.php';</script>";
}else{
    echo "<script> alert('您输入的验证码不正确!');window.location.href='index.php';</script>";
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>验证码应用</title>
<style type="text/css">
<!--
.STYLE1 {
    font-size: 12px;
    color: #FFFFFF;
    font-weight: bold;
}
.style2 {font-weight: bold; font-size: 12px;}
-->
</style>
</head>
<body>
<form name="form" method="post" action="">
  <table width="1003" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="168" height="169" background="images/index_01.gif">&nbsp;</td>
      <td width="685" background="images/index_02.gif">&nbsp;</td>
      <td width="150" background="images/index_03.gif">&nbsp;</td>
    </tr>
    <tr>
      <td width="168" height="311" background="images/index_04.gif">&nbsp;</td>
      <td background="images/index_05.gif"><table width="675" height="169"  border="0" cellpadding="0" cellspacing="0">
        <tr>
          <td height="43" align="center" valign="baseline">&nbsp;</td>
          <td align="center" valign="middle">&nbsp;</td>
          <td align="center" valign="baseline">&nbsp;</td>
        </tr>
        <tr>
          <td width="382" height="24" align="center" valign="baseline">&nbsp;</td>
          <td width="207" height="24" valign="middle"><span class="style2">用户名</span><span class="STYLE1">
            <input  name="txt_user" id="txt_user" style="height:20px " size="10">
              </span></td>
          <td width="86" height="24" align="center" valign="baseline">&nbsp;</td>
        </tr>
        <tr>
          <td height="24" align="center" valign="baseline">&nbsp;</td>
          <td height="24" valign="middle"><span class="style2">密码</span><span class="STYLE1">
          <input  name="txt_pwd" type="password" id="txt_pwd" style="FONT-SIZE: 9pt; height:20px" size="10">
          </span></td>
          <td height="24" align="center" valign="baseline">&nbsp;</td>
        </tr>
        <tr>
          <td height="24" align="center" valign="baseline">&nbsp;</td>
          <td height="24" valign="middle"><span class="style2">验证码</span><span class="STYLE1">
          <input name="checks" size="6" style="height:20px ">
          <img src="checks.php" width="70" height="18" border="0" align="bottom"></span>&nbsp;&nbsp;</td>
          <td height="24" align="center" valign="baseline">&nbsp;</td>
        </tr>
        <tr>
          <td height="40" align="center" valign="baseline">&nbsp;</td>
          <td align="center" valign="baseline">&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" name="Submit" value="登录"></td>
          <td align="center" valign="baseline">&nbsp;</td>
        </tr>
      </table></td>
      <td background="images/index_06.gif">&nbsp;</td>
    </tr>
    <tr>
      <td height="100">&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
</form>
</body>
</html>

使用柱形图

<?php
include ("jpgraph/jpgraph.php");
include ("jpgraph/jpgraph_bar.php");

$datay=array(160,180,203,289,405,488,489,408,299,166,187,105);

//创建画布
$graph = new Graph(600,300,"auto"); 
$graph->SetScale("textlin");
$graph->yaxis->scale->SetGrace(20);

//创建画布阴影
$graph->SetShadow();

//设置显示区左、右、上、下距边线的距离,单位为像素
$graph->img->SetMargin(40,30,30,40);

//创建一个矩形的对象
$bplot = new BarPlot($datay);

//设置柱形图的颜色
$bplot->SetFillColor('orange'); 
//设置显示数字    
$bplot->value->Show();
//在柱形图中显示格式化的图书销量
$bplot->value->SetFormat('%d');
//将柱形图添加到图像中
$graph->Add($bplot);

//设置画布背景色为淡蓝色
$graph->SetMarginColor("lightblue");

//创建标题
$graph->title->Set("《PHP》");

//设置X坐标轴文字
$a=array("1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月");
$graph->xaxis->SetTickLabels($a); 

//设置字体
$graph->title->SetFont(FF_SIMSUN);
$graph->xaxis->SetFont(FF_SIMSUN); 

//输出矩形图表
$graph->Stroke();
?>

使用折线图统计

<?php
        include ("jpgraph/jpgraph.php");
        include ("jpgraph/jpgraph_line.php");                                                       //引用折线图LinePlot类文件
        $datay = array(8320,9360,14956,17028,13060,15376,25428,16216,28548,18632,22724,28460);      //填充的数据   
        $graph = new Graph(600,300,"auto");                             //创建画布
        $graph->img->SetMargin(50,40,30,40);                            //设置统计图所在画布的位置,左边距50、右边距40、上边距30、下边距40,单位为像素
        $graph->img->SetAntiAliasing();                                 //设置折线的平滑状态
        $graph->SetScale("textlin");                                    //设置刻度样式
        $graph->SetShadow();                                            //创建画布阴影
        $graph->title->Set("2000年PHP图书月销售额折线图");    //设置标题
        $graph->title->SetFont(FF_SIMSUN,FS_BOLD);                      //设置标题字体
        $graph->SetMarginColor("lightblue");                            //设置画布的背景颜色为淡蓝色
        $graph->yaxis->title->SetFont(FF_SIMSUN,FS_BOLD);               //设置Y轴标题的字体
        $graph->xaxis->SetPos("min");
        $graph->yaxis->HideZeroLabel();
        $graph->ygrid->SetFill(true,'#EFEFEF@0.5','#BBCCFF@0.5');
        $a=array("1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月");           //X轴
        $graph->xaxis->SetTickLabels($a);                               //设置X轴
        $graph->xaxis->SetFont(FF_SIMSUN);                              //设置X坐标轴的字体
        $graph->yscale->SetGrace(20); 
   
        $p1 = new LinePlot($datay);                                     //创建折线图对象
        $p1->mark->SetType(MARK_FILLEDCIRCLE);                          //设置数据坐标点为圆形标记
        $p1->mark->SetFillColor("red");                                 //设置填充的颜色
        $p1->mark->SetWidth(4);                                         //设置圆形标记的直径为4像素
        $p1->SetColor("blue");                                          //设置折形颜色为蓝色
        $p1->SetCenter();                                               //在X轴的各坐标点中心位置绘制折线
        $graph->Add($p1);                                               //在统计图上绘制折线
        $graph->Stroke();                                               //输出图像
?>

应用3D饼形图

<?php
include_once ("jpgraph/jpgraph.php");
include_once ("jpgraph/jpgraph_pie.php");
include_once ("jpgraph/jpgraph_pie3d.php");         //引用3D饼图PiePlot3D对象所在的类文件

$data = array(266036,295621,335851,254256,254254,685425);           //定义数组
$graph = new PieGraph(540,260,'auto');              //创建画布
$graph->SetShadow();                                //设置画布阴影

$graph->title->Set("应用3D饼形图统计2000年商品的年销售额比率");          //创建标题
$graph->title->SetFont(FF_SIMSUN,FS_BOLD);          //设置标题字体
$graph->legend->SetFont(FF_SIMSUN,FS_NORMAL);           //设置图例字体

$p1 = new PiePlot3D($data);                         //创建3D饼形图对象
$p1->SetLegends(array("IT数码","家电通讯","家居日用","服装鞋帽","健康美容","食品烟酒"));
$targ=array("pie3d_csimex1.php?v=1","pie3d_csimex1.php?v=2","pie3d_csimex1.php?v=3",
            "pie3d_csimex1.php?v=4","pie3d_csimex1.php?v=5","pie3d_csimex1.php?v=6");
$alts=array("val=%d","val=%d","val=%d","val=%d","val=%d","val=%d");
$p1->SetCSIMTargets($targ,$alts);

$p1->SetCenter(0.4,0.5);                    //设置饼形图所在画布的位置
$graph->Add($p1);                           //将3D饼图形添加到图像中
$graph->StrokeCSIM();                       //输出图像到浏览器

?>

应用柱形图依次统计2000年月销量

<?php
include ("jpgraph/jpgraph.php");
include ("jpgraph/jpgraph_bar.php");

$datay1=array(58,85,65,39,120,91,152,49,97,130,67);
$datay2=array(18,35,101,69,138,131,112,149,88,60,77);

$graph = new Graph(620,300,'auto'); 
$graph->SetScale("textlin");
$graph->SetShadow();
$graph->SetMarginColor("yellow");                           //设置画布背景色为淡蓝色
$graph->img->SetMargin(40,30,40,40);
$graph->xaxis->SetTickLabels($gDateLocale->GetShortMonth());

$graph->xaxis->title->Set('');
$graph->xaxis->title->SetFont(FF_SIMSUN,FS_BOLD);

$graph->title->Set('应用柱形图依次统计2000年月销量');
$graph->title->SetFont(FF_SIMSUN,FS_BOLD);

$bplot1 = new BarPlot($datay1);
$bplot2 = new BarPlot($datay2);

$bplot1->SetFillColor("orange");
$bplot2->SetFillColor("lightblue");

$bplot1->SetShadow();
$bplot2->SetShadow();

$bplot1->SetShadow();
$bplot2->SetShadow();

$gbarplot = new GroupBarPlot(array($bplot1,$bplot2));
$gbarplot->SetWidth(0.6);
$graph->Add($gbarplot);

$graph->Stroke();
?>

轿车的月销量统计

<?php
include ("jpgraph/jpgraph.php");
include ("jpgraph/jpgraph_line.php");
include ("jpgraph/jpgraph_scatter.php");

$datay1 = array(83,57,93,112,142,112,89,125,69,105,118,75);             //定义数组

//创建画布
$graph = new Graph(620,260);
$graph->SetMarginColor('red');
$graph->SetScale("textlin");
$graph->SetFrame(false);
$graph->SetMargin(30,5,25,20);

//创建标签标题、颜色、文字大小等属性
$graph->tabtitle->Set(' 2000年轿车的月销量统计  ' );
$graph->tabtitle->SetFont(FF_SIMSUN,FS_NORMAL,10);
$graph->tabtitle->SetColor('darkred','yellow');
// 设置X轴网格
$graph->xgrid->Show();

//应用月份做为X轴的坐标
$graph->xaxis->SetTickLabels($gDateLocale->GetShortMonth());

//创建折线对象
$p1 = new LinePlot($datay1);
$p1->SetColor("navy");

$p1->mark->SetType(MARK_IMG,'car.gif',0.8);             //载入汽车模型标记,并限制其输出大小

//输出汽车模型标记的位置
$p1->value->SetFormat('%d');
$p1->value->Show();
$p1->value->SetColor('darkred');
$p1->value->SetFont(FF_ARIAL,FS_BOLD,10);
$p1->value->SetMargin(14);                  //设置汽车销量距汽车模型标记的距离

$p1->SetCenter();           //设置汽车销量及模型在X轴各坐标点居中显示
$graph->Add($p1);           //添加折线图到图像中
$graph->Stroke();           //输出图像到浏览器

?>

统计2006年、2007年、2008年、2009年农产品的产量比率

<?php
include ("jpgraph/jpgraph.php");
include ("jpgraph/jpgraph_pie.php");

//定义数组
$data1 = array(40,21,17,14,23);
$data2 = array(60,54,107,24,83);
$data3 = array(52,151,99,110,223);
$data4 = array(70,181,117,114,33);

//创建画布
$graph = new PieGraph(600,350,"auto");
$graph->SetShadow();

//设置标题名称
$graph->title->Set("统计2006年、2007年、2008年、2009年农产品的产量比率");
$graph->title->SetFont(FF_SIMSUN,FS_BOLD);
$graph->legend->SetFont(FF_SIMSUN,FS_NORMAL);

//创建饼形图对象
$size=0.13;
$p1 = new PiePlot($data1);
$p1->SetLegends(array("大豆","玉米","水稻","小麦","高梁"));
$p1->SetSize($size);
$p1->SetCenter(0.25,0.32);
$p1->value->SetFont(FF_FONT0);
$p1->title->Set("2006年");
$p1->title->SetFont(FF_SIMSUN,FS_BOLD);

$p2 = new PiePlot($data2);
$p2->SetSize($size);
$p2->SetCenter(0.65,0.32);
$p2->value->SetFont(FF_FONT0);
$p2->title->Set("2007年");
$p2->title->SetFont(FF_SIMSUN,FS_BOLD);

$p3 = new PiePlot($data3);
$p3->SetSize($size);
$p3->SetCenter(0.25,0.75);
$p3->value->SetFont(FF_FONT0);
$p3->title->Set("2008年");
$p3->title->SetFont(FF_SIMSUN,FS_BOLD);

$p4 = new PiePlot($data4);
$p4->SetSize($size);
$p4->SetCenter(0.65,0.75);
$p4->value->SetFont(FF_FONT0);
$p4->title->Set("2009年");
$p4->title->SetFont(FF_SIMSUN,FS_BOLD);

$graph->Add($p1);
$graph->Add($p2);
$graph->Add($p3);
$graph->Add($p4);

$graph->Stroke();

?>

文件系统

文件是用来存储数据的方式之一。
打开文件,关闭文件,读写文件,操作文件。

打开文件

resource fopen ( string filename, string mode [, bool use_include_path]);

关闭文件

bool fclose ( resource handle ) ;

<?php
    $f_open =fopen("../file.txt.","rb");       //打开文件
    …    //对文件进行操作
    fclose($f_open)  //操作完成后关闭文件                
?>

读取数据
可以读取一个字符,一行字串,整个文件
读取文件:readfile()、file()和file_get_contents()

readfile()函数
读入一个文件并将其写入到输出缓冲

int readfile(string filename)

file()函数读取整个文件的内容
file()函数将文件内容按行存放到数组中

array file(string filename)

file_get_contents()函数
将文件内容(filename)读入一个字符串

string file_get_contents(string filename[,int offset[,int maxlen]])

案例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>读取整个文件</title>
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
}
body {
    margin-left: 10px;
    margin-top: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
}
-->
</style></head>
<body>
<table border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td width="250" height="25" align="right" valign="middle" scope="col">使用readfile()函数读取文件内容:</td>
    <td height="25" align="center" valign="middle" scope="col">
    <?php readfile('tm.txt'); ?>    </td>
  </tr>
  <tr>
    <td height="25" align="right" valign="middle">使用file()函数读取文件内容:</td>
    <td height="25" align="center" valign="middle">
    <?php
        $f_arr = file('tm.txt');
        foreach($f_arr as $cont){
            echo $cont."<br>";
        }
    ?></td>
  </tr>
  <tr>
    <td width="250" height="25" align="right" valign="middle" scope="col">使用file_get_contents()函数读取文件内容:</td>
    <td height="25" align="center" valign="middle" scope="col">
    <?php
    
        $f_chr = file_get_contents('tm.txt');
        echo $f_chr;
    
    ?></td>
  </tr>
</table>
</body>
</html>

读取一行数据:fgets()和fgetss()

fgets()函数用于一次读取一行数据

string fgets( int handle [, int length] )

fgetss()函数是fgets()函数的变体,用于读取一行数据

string fgetss ( resource handle [, int length [, string 
allowable_tags]] )

fgets和fgetss的区别

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>fgets和fgetss的区别</title>
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
}
body {
    margin-left: 10px;
    margin-top: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
}
-->
</style></head>
<body>
<table border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td height="30" align="right" valign="middle" scope="col">使用fgets函数:</td>
    <td height="30" align="center" valign="middle" scope="col">
<?php
    $fopen = fopen('fun.php','rb');
    while(!feof($fopen)){
        echo fgets($fopen);
    }
    fclose($fopen);
?>  </td>
  </tr>
  <tr>
    <td height="30" align="right" valign="middle">使用fgetss函数:</td>
    <td height="30" align="center" valign="middle">
    <?php
    $fopen = fopen('fun.php','rb');
    while(!feof($fopen)){
        echo fgetss($fopen);
    }
    fclose($fopen);
?>  </td>
  </tr>
</table>
</body>
</html>

读取一个字符:fgetc() 读取任意长度的字串:fread()

string fgetc ( resource handle )

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>使用fgetc函数读取字符</title>
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
}
body {
    margin-left: 10px;
    margin-top: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
}
-->
</style></head>
<body>
<pre>
<?php
    $fopen = fopen('03.txt','rb');
    while(false !== ($chr = fgetc($fopen))){
        echo $chr;
    }
    fclose($fopen);
?>
</pre>
</body>
</html>

string fread ( int handle, int length )

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>使用fread函数读取文件</title>
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
}
body {
    margin-left: 10px;
    margin-top: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
}
-->
</style></head>
<body>
<?php
    $filename = "04.txt";
    $fp = fopen($filename,"rb");
    echo fread($fp,32);
    echo "<p>";
    echo fread($fp,filesize($filename));
?>
</body>
</html>

写入文件

使用fwrite()和file_put_contents()函数向文件中写入数据

fwrite()函数

int fwrite ( resource handle, string string [, int length] )

file_put_contents()函数

int file_put_contents ( string filename, string data [, int 
flags])

使用fwrite和file_put_contents函数写入数据

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>使用fwrite和file_put_contents函数写入数据</title>
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
}
body {
    margin-left: 10px;
    margin-top: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
}
-->
</style></head>
<body>
<?php
    $filepath = "05.txt";
    $str = "此情可待成追忆 只是当时已惘然<br>";
    echo "用fwrite写入文件:";
    $fopen = fopen($filepath,'wb') or die('文件不存在');
    fwrite($fopen,$str);
    fclose($fopen);
    readfile($filepath);
    echo "<p>用file_put_contents写入文件:";
    file_put_contents($filepath,$str);
    readfile($filepath);
?>
</body>
</html>

操作文件

bool copy();
bool rename();
bool unlink();
int fileatime();
int filemtime();
int filesize();
array pathinfo();
string realpath();

目 录 处 理

打开/关闭目录
浏览目录
操作目录

opendir()函数

resource opendir ( string path)

closedir()函数

void closedir ( resource handle )

案例:

<?php  
$path = "D:\\55555\\www\\55\\55\\12" ;
if (is_dir($path)){                     //检测是否是一个目录
    if ($dire = opendir($path))             //判断打开目录是否成功
        echo $dire;                 //输出目录指针
}else{
    echo '路径错误';
    exit();
}
…                                   //其他操作
closedir($dire);                            //关闭目录
?>

浏览目录,scandir()函数

array scandir ( string directory [, int sorting_order ])
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>浏览目录</title>
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
}
body {
    margin-left: 10px;
    margin-top: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
}
-->
</style></head>
<body>
<?php  
    $path = 'E:\AppServ\www\mr\sl\13';
    if(is_dir($path)){
        $dir = scandir($path);
        foreach($dir as $value){
            echo $value."<br>";
        }
    }else{
        echo "目录路径错误!";
    }
?>
</body>
</html>

操作目录

bool mkdir
bool rmdir
string getcwd
bool chdir
float disk_free_space
string readdir
void rewinddir

高级应用
远程文件访问
文件指针
锁定文件

php.ini中配置,找到allow_url_fopen,设为ON

fopen('http://127.0.0.1/index.php','rb'); 

文件指针

1.rewind()函数

bool rewind ( resource handle )

2.fseek()函数

int fseek ( resource handle, int offset [, int whence] )

handle参数为要打开的文件
offset为指针位置或相对whence参数的偏移量,可以是负值
whence的值包括3种:
SEEK_SET,位置等于offset字节
SEEK_CUR,位置等于当前位置加上offset字节
SEEK_END,位置等于文件尾加上offset字节
如果忽略whence参数,系统默认为SEEK_SET

3.feof()函数

bool feof ( resource handle )

4.ftell()函数

int ftell ( resource handle )
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>文件指针函数</title>
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
}
body {
    margin-left: 10px;
    margin-top: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
}
-->
</style></head>
<body>
<?php
$filename = "07.txt";
$total = filesize($filename);
if(is_file($filename)){
    echo "文件总字节数:".$total."<br>";
    $fopen = fopen($filename,'rb');
    echo "初始指针位置是:".ftell($fopen)."<br>";
    fseek($fopen,33);
    echo "使用fseek()函数后指针位置:".ftell($fopen)."<br>";
    echo "输出当前指针后面的内容:".fgets($fopen)."<br>";
    if(feof($fopen))
        echo "当前指针指向文件末尾:".ftell($fopen)."<br>";
    rewind($fopen);
    echo "使用rewind()函数后指针的位置:".ftell($fopen)."<br>";
    echo "输出前33字节的内容:".fgets($fopen,33);
    fclose($fopen);
}else{
    echo "文件不存在";
}
?>
</body>
</html>

锁定文件

bool flock ( int handle, int operation)

LOCK_SH取得共享锁定(读取程序)
LOCK_EX取得独占锁定(写入程序)
LOCK_UN释放锁定
LOCK_NB防止flock()在锁定时堵塞
operation的参数
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>使用flock函数</title>
</head>
<body>
<?php
    $filename = '08.txt';                       //声明要打开的文件的名称
    $fd = fopen($filename,'w');                 //以w形式打开文件
    flock($fd, LOCK_EX);                        //锁定文件(毒针共享
    fwrite($fd, "hightman1");                   //向文件中写入数据
    flock($fd, LOCK_UN);                        //解除锁定
    fclose($fd);                                //关闭文件指针
    readfile($filename);                        //输出文件内容
?>
</body>
</html>

文件上传

文件上传是要通过http协议来实现的,要在php.ini文件中进行对上传文件的设置,要了解$_FILES变量和函数move_uploaded_file()函数实现上传。

要配置php.ini文件,在文件中找到file_uploads,如果值为on,说明服务器支持文件上传,如果为off,则表示不支持,upload_tmp_dir为上传文件临时位置,系统默认,也可以自己定。

upload_max_filesize为服务器允许上传的文件的最大值,默认2mb。max_execution_timePHP中一个指令所能执行的最大时间,memory_limitPHP中一个指令所分配的内存空间。

$_FILES[filename][name]
上传文件的文件名

$_FILES[filename][size]
文件大小

$_FILES[filename][tmp_name]
为临时文件名

$_FILES[filename][type]
文件的类型

$_FILES[filename][error]
上传文件的结果。如果返回0,说明文件上传成功
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>$_FIELS变量</title>
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
}
body {
    margin-left: 10px;
    margin-top: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
}
-->
</style></head>
<body>
<table width="500" border="0" cellspacing="0" cellpadding="0">
<form action="" method="post" enctype="multipart/form-data">
  <tr>
    <td width="150" height="30" align="right" valign="middle">请选择上传文件:</td>
    <td width="250"><input type="file" name="upfile"/></td>
    <td width="100"><input type="submit" name="submit" value="上传" /></td>
  </tr>
</form>
</table>
<?php
    if(!empty($_FILES)){
        foreach($_FILES['upfile'] as $name => $value)
            echo $name.' = '.$value.'<br>';
    }
?>
</body>
</html>

文件上传函数

move_uploaded_file()函数上传文件

bool move_uploaded_file ( string filename, string destination )

将上传文件存储到指定的位置

单文件上传

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>单文件上传</title>
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
}
body {
    margin-left: 10px;
    margin-top: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
}
--> 
</style></head>
<body>
<?php
    if(!empty($_FILES[up_file][name])){
    $fileinfo = $_FILES[up_file];
        if($fileinfo['size'] < 1000000 && $fileinfo['size'] > 0){
            move_uploaded_file($fileinfo['tmp_name'],$fileinfo['name']);
            echo '上传成功';
        }else{
            echo '文件太大或未知';
        }
    }
?>
<table width="385" height="185" border="0" cellpadding="0" cellspacing="0" background="images/bg.JPG">
  <tr>
    <td width="142" height="80">&nbsp;</td>
    <td width="174">&nbsp;</td>
    <td width="69">&nbsp;</td>
  </tr>
<form action="" method="post" enctype="multipart/form-data" name="form">
  <tr>
    <td height="30">&nbsp;</td>
    <td align="left" valign="middle"><input name="up_file" type="file" size="12" /></td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td height="27" align="right">&nbsp;</td>
    <td align="center" valign="top">&nbsp;&nbsp;<input type="image" name="imageField" src="images/fg.bmp"></td>
    <td>&nbsp;</td>
  </tr>
  </form>
  <tr>
    <td height="48">&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>

</body>
</html>

多文件上传

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>多文件上传</title>
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
}
body {
    margin-left: 10px;
    margin-top: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
}
-->
</style>
</head>
<body>
请选择要上传的文件
<form action="" method="post" enctype="multipart/form-data">
  <table border="1" cellpadding="1" cellspacing="1" bordercolor="#FFFFFF" bgcolor="#CCCCCC" id="up_table" >
    <tbody id="auto">
      <tr id="show" >
        <td bgcolor="#FFFFFF">上传文件 </td>
        <td bgcolor="#FFFFFF"><input name="u_file[]" type="file"></td>
      </tr>
      <tr>
        <td bgcolor="#FFFFFF">上传文件 </td>
        <td bgcolor="#FFFFFF"><input name="u_file[]" type="file"></td>
      </tr>
      <tr>
        <td bgcolor="#FFFFFF">上传文件 </td>
        <td bgcolor="#FFFFFF"><input name="u_file[]" type="file"></td>
      </tr>
      <tr>
        <td bgcolor="#FFFFFF">上传文件 </td>
        <td bgcolor="#FFFFFF"><input name="u_file[]" type="file"></td>
      </tr>
    </tbody>
    <tr>
      <td colspan="4" bgcolor="#FFFFFF"><input type="submit" value="上传" /></td>
    </tr>
  </table>
</form>
<?php
if(!empty($_FILES[u_file][name])){
    $file_name = $_FILES[u_file][name];
    $file_tmp_name = $_FILES[u_file][tmp_name];
    for($i = 0; $i < count($file_name); $i++){
        if($file_name[$i] != ''){
            move_uploaded_file($file_tmp_name[$i],$i.$file_name[$i]);
            echo '文件'.$file_name[$i].'上传成功。更名为'.$i.$file_name[$i].'<br>';
        }
    }
}
?>
</body>
</html>

访问量:

<?php session_start();  
if($_SESSION[temp]==""){ //判断$_SESSION[temp]==""的值是否为空,其中的temp为自定义的变量
    if(($fp=fopen("counter.txt","r"))==false){ 
        echo "打开文件失败!";
    }else{ 
        $counter=fgets($fp,1024);       //读取文件中数据
        fclose($fp);                    //关闭文本文件
        $counter++;                     //计数器增加1
        $fp=fopen("counter.txt","w");   //以写的方式打开文本文件<!---->
        fputs($fp,$counter);            //将新的统计数据增加1
        fclose($fp);    
    }                                   //关闭文   
    $_SESSION[temp]=1;                  //登录以后,$_SESSION[temp]的值不为空,给$_SESSION[temp]赋一个值1
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>通过文本文件统计页面访问量</title>
</head>
<body>
<img src="gd1.php" />
</BODY>
</HTML>

<?php 
//以图形的形式输出数据库中的记录数

if(($fp=fopen("counter.txt","r"))==false){
    echo "打开文件失败!";
}else{
    $counter=fgets($fp,1024);
    fclose($fp);
    //通过GD2函数创建画布
    $im=imagecreate(240,24);
    $gray=imagecolorallocate($im,255,255,255);
    $color =imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));    //定义字体颜色
    //输出中文字符
    $text=iconv("gb2312","utf-8","网站的访问量:");                        //对指定的中文字符串进行转换
    $font = "Fonts/FZHCJW.TTF";  
    imagettftext($im,14,0,20,18,$color,$font,$text);                        //输出中文
    //输出网站的访问次数
    imagestring($im,5,160,5,$counter,$color);
    imagepng($im);
    imagedestroy($im);
}   

?>

限制大小的文件上传

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>限制大小的文件上传</title>
<style type="text/css">
<!--
body {
    margin-left: 00px;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 0px;
}
-->
</style></head>

<body>
<table width="385" height="185" border="0" cellpadding="0" cellspacing="0" background="images/bg.JPG">
  <tr>
    <td width="142" height="80">&nbsp;</td>
    <td width="174">&nbsp;</td>
    <td width="69">&nbsp;</td>
  </tr>
  <form name="form1" method="post" action="index_ok.php" enctype="multipart/form-data">
  <tr>
    <td height="30">&nbsp;</td>
    <td align="left" valign="middle"><input name="files" type="file" id="files" size="13" maxlength="150">   </td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td height="27" align="right">&nbsp;</td>
    <td align="center" valign="top">&nbsp;&nbsp;<input type="image" name="imageField" src="images/fg.bmp"></td>
    <td>&nbsp;</td>
  </tr>
  </form>
  <tr>
    <td height="48">&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>
</body>
</html>

<?php 
    if($_FILES['files']['name']==true){
        $filesize=$_FILES['files']['size'];
        if($filesize>1000000){
            echo "对不起,您上传的文件超过规定的大小!!";
            echo "<meta http-equiv=\"Refresh\" content=\"3;url=index.php\">将在3秒钟后返回前页...";
        }else{
            $path = './upfiles/'. $_FILES['files']['name'];
            if (move_uploaded_file($_FILES['files']['tmp_name'],$path)) { 
                echo "上传成功!!";
                echo "<meta http-equiv=\"Refresh\" content=\"3;url=index.php\">"; 
            }else{
                echo "文件上传失败!!";
                echo "<meta http-equiv=\"Refresh\" content=\"3;url=index.php\">";
            }
        }
    }
?>

结言

好了,欢迎在留言区留言,与大家分享你的经验和心得。

感谢你学习今天的内容,如果你觉得这篇文章对你有帮助的话,也欢迎把它分享给更多的朋友,感谢。

感谢!承蒙关照!您真诚的赞赏是我前进的最大动力!

image

image


原文链接:https://www.cnblogs.com/dashucoding/p/10759929.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:[TCP/IP] TCP的传输连接管理

下一篇:学习PHP的基础知识