php 创建文件多种方法总结

 更新时间:2016年11月25日 17:29  点击:2065
php 创建文件的方法有很多种我们最常用的就是fopen,file_put_contents这两种方法来创建文件了,下面我来给大家详细介绍介绍,有需要了解的同学可参考。

创建php文件

 代码如下 复制代码

<?php
$str="<?php echo 123;?>";
file_put_contents('test.php',$str);//使用脚本创建一个php文件
?>

例2

 代码如下 复制代码

<?php
if ($argc != 2) {
die("Usage: php mkphp.php filename");
}
array_shift($argv);
$cat= $argv[0];
file_put_contents($cat.".php", "<?php

?>");

利用fopen创建文件

 代码如下 复制代码

<?

$fp=fopen("1.txt","w+");//fopen()的其它开关请参看相关函数
$str="我加我加我加加加";
fputs($fp,$str);
fclose($fp);
?>

上面没作任何考虑,如果要全面点我们首先,确定你所要新建文件所在的目录权限; 建议设备为777。然后,新建文件的名称建议使用绝对路径。

 代码如下 复制代码

<?php
$filename="test.txt";
$fp=fopen("$filename", "w+"); //打开文件指针,创建文件
if ( !is_writable($filename) ){
      die("文件:" .$filename. "不可写,请检查!");
}
//fwrite($filename, "anything you want to write to $filename.";
fclose($fp);  //关闭指针

'r' 开文件方式为只读,文件指’指到开始处
'r+' 开文件方式为可读写,文件指’指到开始处
'w' 开文件方式为写入,文件指’指到开始处 并将原文‘的长度设为 0。若文件不存在‘‘建立新文件–
'w+' 开文件方式为可读写,文件指’指到开始处 并将原文‘的长度设为 0。若文件不存在‘‘建立新文件–
'a' 开文件方式为写入,文件指’指到文件最后。若文件不存在‘‘建立新文件–
'a+' 开文件方式为可读写,文件指’指到文件最后。若文件不存在‘‘建立新文件–
'b' 若操作系统的文字及二进位文件不同,‘可以用“‘”,UNIX 系统不–要“用 参”。

 代码如下 复制代码

///创建文件
function creat_file($PATH){
   $sFile = "test.html";
   if (file_exists($PATH.$sFile)) {
    creat_file();
   } else {
    $fp= fopen($PATH.$sFile,"w");
    fclose($fp);
   }
   return $sFile;
}

本文章来给大家推荐一个不错的购物车效果,这里主要求包括了几个东西,一个是购物车类用php写的, 还有一个Ajax操作用到了jquery,还有一个jquery插件thickbox了,下面我们来看看。

购物车类:shop_cart.php
购物车的操作:cart_action.php
首页:index.html
Ajax操作用到了jquery,还有一个jquery插件thickbox

不多说了你可以先看看效果示例
shop_cart.php当然是购物车的核心,但是这个类很简单,因为他又引进了cart_action.php用于对外操作。所以这个类显得相当精简。
购物车类shop_cart.php

 代码如下 复制代码

cart_name = $name;
$this->items = $_SESSION[$this->cart_name];
}

/**
* setItemQuantity() - Set the quantity of an item.
*
* @param string $order_code The order code of the item.
* @param int $quantity The quantity.
*/
function setItemQuantity($order_code, $quantity) {
$this->items[$order_code] = $quantity;
}

/**
* getItemPrice() - Get the price of an item.
*
* @param string $order_code The order code of the item.
* @return int The price.
*/
function getItemPrice($order_code) {
// This is where the code taht retrieves prices
// goes. We'll just say everything costs $9.99 for this tutorial.
return 9.99;
}

/**
* getItemName() - Get the name of an item.
*
* @param string $order_code The order code of the item.
*/
function getItemName($order_code) {
// This is where the code that retrieves product names
// goes. We'll just return something generic for this tutorial.
return 'My Product (' . $order_code . ')';
}

/**
* getItems() - Get all items.
*
* @return array The items.
*/
function getItems() {
return $this->items;
}

/**
* hasItems() - Checks to see if there are items in the cart.
*
* @return bool True if there are items.
*/
function hasItems() {
return (bool) $this->items;
}

/**
* getItemQuantity() - Get the quantity of an item in the cart.
*
* @param string $order_code The order code.
* @return int The quantity.
*/
function getItemQuantity($order_code) {
return (int) $this->items[$order_code];
}

/**
* clean() - Cleanup the cart contents. If any items have a
*           quantity less than one, remove them.
*/
function clean() {
foreach ( $this->items as $order_code=>$quantity ) {
if ( $quantity < 1 )     unset($this->items[$order_code]);
}
}

/**
* save() - Saves the cart to a session variable.
*/
function save() {
$this->clean();
$_SESSION[$this->cart_name] = $this->items;
}
}

?>

对于cart_action,他实现了shop_cart类与index的中间作用,用于更新,删除,增加商品的操作。
cart_action.php

 代码如下 复制代码

getItemQuantity($_GET['order_code'])+$_GET['quantity'];
$Cart->setItemQuantity($_GET['order_code'], $quantity);
}else{

if ( !empty($_GET['quantity']) ) {
foreach ( $_GET['quantity'] as $order_code=>$quantity){
$Cart->setItemQuantity($order_code, $quantity);
}
}

if ( !empty($_GET['remove']) ) {
foreach ( $_GET['remove'] as $order_code ) {
$Cart->setItemQuantity($order_code, 0);
}
}
}
$Cart->save();

header('Location: cart.php');

?>

还有就是index.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=utf-8">
<title>Shopping Cart</title>
<script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script src="js/jquery.color.js" type="text/javascript"></script>
<script src="js/thickbox.js" type="text/javascript"></script>
<script src="js/cart.js" type="text/javascript"></script>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/thickbox.css" rel="stylesheet" type="text/css" media="screen" />

<script type="text/javascript">
$(function() {
$("form.cart_form").submit(function() {
var title = "Your Shopping Cart";
var orderCode = $("input[name=order_code]", this).val();
var quantity = $("input[name=quantity]", this).val();
var url = "cart_action.php?order_code=" + orderCode + "&amp;amp;amp;amp;amp;amp;amp;quantity=" + quantity + "&amp;amp;amp;amp;amp;amp;amp;TB_iframe=true&amp;amp;amp;amp;amp;amp;amp;height=400&amp;amp;amp;amp;amp;amp;amp;width=780";
tb_show(title, url, false);

return false;
});
});
</script>
</head>
<body>
<div id="container">
<h1>购物车</h1>
<a href="cart.php?KeepThis=true&amp;amp;amp;amp;amp;amp;amp;TB_iframe=true&amp;amp;amp;amp;amp;amp;amp;height=400&amp;amp;amp;amp;amp;amp;amp;width=780" title="Your Shopping Cart" class="thickbox">打开购物车</a>
<hr />
<a href="cart_action.php?order_code=KWL-JFE&amp;amp;amp;amp;amp;amp;amp;quantity=3&amp;amp;amp;amp;amp;amp;amp;TB_iframe=true&amp;amp;amp;amp;amp;amp;amp;height=400&amp;amp;amp;amp;amp;amp;amp;width=780" title="Your Shopping Cart" class="thickbox">添加三个 KWL-JFE 到购物车</a>
<hr />
<form class="cart_form" action="cart_action.php" method="get">
<input type="hidden" name="order_code" value="KWL-JFE" />
<label>KWL-JFE: <input class="center" type="text" name="quantity" value="1" size="3" ?></label>
<input type="submit" name="submit" value="添加到购物车" />
</form>
</div>
</body>
</html>

还有就是cart.php这是我们的购物车

 代码如下 复制代码
<?php
include('shopping_cart.class.php');
session_start();
$Cart = new Shopping_Cart('shopping_cart');
?>
<!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">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<head>
<title>Shopping Cart</title>
<script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script src="js/jquery.color.js" type="text/javascript"></script>
<script src="js/cart.js" type="text/javascript"></script>
<link href="css/cart.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="container">
<h1>Shopping Cart</h1>
<?php if ( $Cart->hasItems() ) : ?>
<form action="cart_action.php" method="get">
<table id="cart">
<tr>
<th>数量</th>
<th>商品名称</th>
<th>商品编号</th>
<th>单价</th>
<th>总价</th>
<th>删除</th>
</tr>
<?php
$total_price = $i = 0;
foreach ( $Cart->getItems() as $order_code=>$quantity ) :
$total_price += $quantity*$Cart->getItemPrice($order_code);
?>
<?php echo $i++%2==0 ? "<tr>" : "<tr class='odd'>"; ?>
<td class="quantity center"><input type="text" name="quantity[<?php echo $order_code; ?>]" size="3" value="<?php echo $quantity; ?>" tabindex="<?php echo $i; ?>" /></td>
<td class="item_name"><?php echo $Cart->getItemName($order_code); ?></td>
<td class="order_code"><?php echo $order_code; ?></td>
<td class="unit_price">$<?php echo $Cart->getItemPrice($order_code); ?></td>
<td class="extended_price">$<?php echo ($Cart->getItemPrice($order_code)*$quantity); ?></td>
<td class="remove center"><input type="checkbox" name="remove[]" value="<?php echo $order_code; ?>" /></td>
</tr>
<?php endforeach; ?>
<tr><td colspan="2"></td><td  colspan="3" id="total_price">您的消费总金额是:¥<?php echo $total_price; ?></td></tr>
</table>
<input type="submit" name="update" value="保存购物车" />
</form>
<?php else: ?>
<p class="center">您还没有购物.</p>
<?php endif; ?>
<p><a href="load.php">加载简单的购物车</a></p>
</div>
</body>
</html>

页面执行时间计算也只是一个大概的过程,我们把程序计算程序的初始化函数放在页面最顶部,然后把计算函数放页面最底部,然后当页面执行完成就可以计算出相关值了,下面看实例

具体代码

 代码如下 复制代码

<?php
class runtime
{
    var $StartTime = 0;
    var $StopTime = 0;
 
    function get_microtime()
    {
        list($usec, $sec) = explode(' ', microtime());
        return ((float)$usec + (float)$sec);
    }
 
    function start()
    {
        $this->StartTime = $this->get_microtime();
    }
 
    function stop()
    {
        $this->StopTime = $this->get_microtime();
    }
 
    function spent()
    {
        return round(($this->StopTime - $this->StartTime) * 1000, 1);
    }
 
}
 
 
//例子
$runtime= new runtime;
$runtime->start();
 
//你的代码开始
 
$a = 0;
for($i=0; $i<1000000; $i++)
{
    $a += $i;
}
 
//你的代码结束
 
$runtime->stop();
echo "页面执行时间: ".$runtime->spent()." 毫秒";
?>


调用方法上面有介绍了我就不说了,我们只是要注意$runtime->start();与$runtime->spent()必须,一前一后哦,否则是无效的,还有不能放在缓存页面中和html页面中。

本文章来给大家介绍php反中文汉字转Unicode编码实现程序方法,有需要了解的朋友可进入参考。

程序

 代码如下 复制代码

/**
 * $str 原始字符串
 * $encoding 原始字符串的编码,默认GBK
 * $prefix 编码后的前缀,默认"&#"
 * $postfix 编码后的后缀,默认";"
 */
function unicode_encode($str, $encoding = 'GBK', $prefix = '&#', $postfix = ';') {
    $str = iconv($encoding, 'UCS-2', $str);
    $arrstr = str_split($str, 2);
    $unistr = '';
    for($i = 0, $len = count($arrstr); $i < $len; $i++) {
        $dec = hexdec(bin2hex($arrstr[$i]));
        $unistr .= $prefix . $dec . $postfix;
    }
    return $unistr;
}
 
/**
 * $str Unicode编码后的字符串
 * $encoding 原始字符串的编码,默认GBK
 * $prefix 编码字符串的前缀,默认"&#"
 * $postfix 编码字符串的后缀,默认";"
 */
function unicode_decode($unistr, $encoding = 'GBK', $prefix = '&#', $postfix = ';') {
    $arruni = explode($prefix, $unistr);
    $unistr = '';
    for($i = 1, $len = count($arruni); $i < $len; $i++) {
        if (strlen($postfix) > 0) {
            $arruni[$i] = substr($arruni[$i], 0, strlen($arruni[$i]) - strlen($postfix));
        }
        $temp = intval($arruni[$i]);
        $unistr .= ($temp < 256) ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256);
    }
    return iconv('UCS-2', $encoding, $unistr);
}

使用范例:

 代码如下 复制代码

//GBK字符串测试
$str = '<b>哈哈</b>';
echo $str.'<br />';
 
$unistr = unicode_encode($str);
echo $unistr.'<br />'; // &#60;&#98;&#62;&#21704;&#21704;&#60;&#47;&#98;&#62;
 
$str2 = unicode_decode($unistr);
echo $str2.'<br />'; //<b>哈哈</b>
 
//UTF-8字符串测试
$utf8_str = iconv('GBK', 'UTF-8', $str);
echo $utf8_str.'<br />'; // <b>????</b> 注:UTF在GBK下显示的乱码!可切换浏览器的编码测试
 
$utf8_unistr = unicode_encode($utf8_str, 'UTF-8');
echo $utf8_unistr.'<br />'; // &#60;&#98;&#62;&#21704;&#21704;&#60;&#47;&#98;&#62;
 
$utf8_str2 = unicode_decode($utf8_unistr, 'UTF-8');
echo $utf8_str2.'<br />'; // <b>????</b>
 
//其它后缀、前缀测试
$prefix_unistr = unicode_encode($str, 'GBK', "\u", '');
echo $prefix_unistr.'<br />'; // u60u98u62u21704u21704u60u47u98u62
 
$profix_unistr2 = unicode_decode($prefix_unistr, 'GBK', "\u", '');
echo $profix_unistr2.'<br />'; //<b>哈哈</b>

本文章给大家介绍利用txt与php实现随机广告显示调用方法,原理很简单我们把广告文件放到txt文件中,当有用户访问时我们把txt文件载入,然后随机出来.
 代码如下 复制代码
<?php
  #########随机广告显示##########
  function myads(){
  $dir="ads"; #设置存放记录的目录
  //$dir="ads"; #设置存放记录的目录
  $ads="$dir/ads.txt"; #设置广告代码文件
  $log ="$dir/ads.log"; #设置ip记录文件
  
  $ads_lines=file($ads);
  $lines=count($ads_lines);#文件总行数
  
  ####读出广告总数$ads_count和显示次数到数组$display_array########
  $ads_count=0;
  $display_count=0;
  for ($i=0;$i<$lines;$i++){
   if((!strcmp(substr($ads_lines[$i],0,7),"display"))){
   $ads_count+=1;
   $display_array[$ads_count]=substr($ads_lines[$i],8);
   $display_count+=$display_array[$ads_count];
   }
  }
  ####决定随机显示序号$display_rand#####
  srand((double)microtime()*1000000);
  $display_rand = rand(1,$display_count);
  
  ###决定广告序号$ads_num######
  $pricount=0;
  $ads_num=1;
  for($i=1; $i<=$ads_count; $i++) {
   $pricount += $display_array[$i];
   if ($display_rand<=$pricount) {$ads_num=$i;break;}
  }
  
  #####播放广告########
  $num=0;
  $flag=0;
  
  for($i=0;$i<$lines;$i++){
   if((!strcmp(substr($ads_lines[$i],0,7),"display"))){$num++;}
   if(($num==$ads_num)and($flag==0)){$flag=1;continue;}
   if(($flag==1)and strcmp($ads_lines[$i][0],"#")){echo $ads_lines[$i];continue;}
   if(($flag==1)and(!(strcmp($ads_lines[$i][0],"#")))){break;}
  }
  ####纪录广告显示次数#########
  $fp=fopen($log,"a");
  fputs($fp,date( "Y-m-d H:i:s " ).getenv("REMOTE_ADDR")."==>".$ads_num."n");
  fclose($fp);
  }
  ?>

  
广告代码文件ads.txt

 代码如下 复制代码
  
  ########每个广告代码之间用'#'隔开,display为显示加权数,越大显示次数越多################
  ################################
  display=10
  
  <a href="http://www.111cn.net">
  <img src="h/c_banner.gif" alt="Chance2mail,好礼物送给您!"> </a>
  ################################
  display=10
  
  <a href="http://www.111cn.net" target=_blank>
  <img src="8848.gif" width="468" height="60" border="0"></a>

   
  
调用

<?php myads();?>

即可

[!--infotagslink--]

相关文章

  • php读取zip文件(删除文件,提取文件,增加文件)实例

    下面小编来给大家演示几个php操作zip文件的实例,我们可以读取zip包中指定文件与删除zip包中指定文件,下面来给大这介绍一下。 从zip压缩文件中提取文件 代...2016-11-25
  • Jupyter Notebook读取csv文件出现的问题及解决

    这篇文章主要介绍了JupyterNotebook读取csv文件出现的问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2023-01-06
  • php 中file_get_contents超时问题的解决方法

    file_get_contents超时我知道最多的原因就是你机器访问远程机器过慢,导致php脚本超时了,但也有其它很多原因,下面我来总结file_get_contents超时问题的解决方法总结。...2016-11-25
  • php抓取网站图片并保存的实现方法

    php如何实现抓取网页图片,相较于手动的粘贴复制,使用小程序要方便快捷多了,喜欢编程的人总会喜欢制作一些简单有用的小软件,最近就参考了网上一个php抓取图片代码,封装了一个php远程抓取图片的类,测试了一下,效果还不错分享...2015-10-30
  • HTTP 408错误是什么 HTTP 408错误解决方法

    相信很多站长都遇到过这样一个问题,访问页面时出现408错误,下面一聚教程网将为大家介绍408错误出现的原因以及408错误的解决办法。 HTTP 408错误出现原因: HTT...2017-01-22
  • Android子控件超出父控件的范围显示出来方法

    下面我们来看一篇关于Android子控件超出父控件的范围显示出来方法,希望这篇文章能够帮助到各位朋友,有碰到此问题的朋友可以进来看看哦。 <RelativeLayout xmlns:an...2016-10-02
  • ps把文字背景变透明的操作方法

    ps软件是现在非常受大家喜欢的一款软件,有着非常不错的使用功能。这次文章就给大家介绍下ps把文字背景变透明的操作方法,喜欢的一起来看看。 1、使用Photoshop软件...2017-07-06
  • Photoshop打开PSD文件空白怎么解决

    有时我们接受或下载到的PSD文件打开是空白的,那么我们要如何来解决这个 问题了,下面一聚教程小伙伴就为各位介绍Photoshop打开PSD文件空白解决办法。 1、如我们打开...2016-09-14
  • C#操作本地文件及保存文件到数据库的基本方法总结

    C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
  • 解决python 使用openpyxl读写大文件的坑

    这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
  • C#实现HTTP下载文件的方法

    这篇文章主要介绍了C#实现HTTP下载文件的方法,包括了HTTP通信的创建、本地文件的写入等,非常具有实用价值,需要的朋友可以参考下...2020-06-25
  • intellij idea快速查看当前类中的所有方法(推荐)

    这篇文章主要介绍了intellij idea快速查看当前类中的所有方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-09-02
  • Mysql select语句设置默认值的方法

    1.在没有设置默认值的情况下: 复制代码 代码如下:SELECT userinfo.id, user_name, role, adm_regionid, region_name , create_timeFROM userinfoLEFT JOIN region ON userinfo.adm_regionid = region.id 结果:...2014-05-31
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • js导出table数据到excel即导出为EXCEL文档的方法

    复制代码 代码如下: <!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 ht...2013-10-13
  • mysql 批量更新与批量更新多条记录的不同值实现方法

    批量更新mysql更新语句很简单,更新一条数据的某个字段,一般这样写:复制代码 代码如下:UPDATE mytable SET myfield = 'value' WHERE other_field = 'other_value';如果更新同一字段为同一个值,mysql也很简单,修改下where即...2013-10-04
  • ps怎么制作倒影 ps设计倒影的方法

    ps软件是一款非常不错的图片处理软件,有着非常不错的使用效果。这次文章要给大家介绍的是ps怎么制作倒影,一起来看看设计倒影的方法。 用ps怎么做倒影最终效果&#819...2017-07-06
  • php无刷新利用iframe实现页面无刷新上传文件(1/2)

    利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25
  • js基础知识(公有方法、私有方法、特权方法)

    本文涉及的主题虽然很基础,在许多人看来属于小伎俩,但在JavaScript基础知识中属于一个综合性的话题。这里会涉及到对象属性的封装、原型、构造函数、闭包以及立即执行表达式等知识。公有方法 公有方法就是能被外部访问...2015-11-08
  • 安卓手机wifi打不开修复教程,安卓手机wifi打不开解决方法

    手机wifi打不开?让小编来告诉你如何解决。还不知道的朋友快来看看。 手机wifi是现在生活中最常用的手机功能,但是遇到手机wifi打不开的情况该怎么办呢?如果手机wifi...2016-12-21