程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php中配置文件操作 如config.php文件的讀取修改等操作

php中配置文件操作 如config.php文件的讀取修改等操作

編輯:關於PHP編程

復制代碼 代碼如下:
<?php
$name="admin";//kkkk
$bb='234';
$db=4561321;
$kkk="admin";
?>

函數定義:
配置文件數據值獲取:function getconfig($file, $ini, $type="string")
配置文件數據項更新:function updateconfig($file, $ini, $value,$type="string")
調用方式:
復制代碼 代碼如下:
getconfig("./2.php", "bb");//
updateconfig("./2.php", "kkk", "admin");

復制代碼 代碼如下:
<?php

//配置文件數據值獲取。
//默認沒有第三個參數時,按照字符串讀取提取''中或""中的內容
//如果有第三個參數時為int時按照數字int處理。
function getconfig($file, $ini, $type="string")
{
if ($type=="int")
{
$str = file_get_contents($file);
$config = preg_match("/" . $ini . "=(.*);/", $str, $res);
Return $res[1];
}
else
{
$str = file_get_contents($file);
$config = preg_match("/" . $ini . "=\"(.*)\";/", $str, $res);
if($res[1]==null)
{
$config = preg_match("/" . $ini . "='(.*)';/", $str, $res);
}
Return $res[1];
}
}

//配置文件數據項更新
//默認沒有第四個參數時,按照字符串讀取提取''中或""中的內容
//如果有第四個參數時為int時按照數字int處理。
function updateconfig($file, $ini, $value,$type="string")
{
$str = file_get_contents($file);
$str2="";
if($type=="int")
{
$str2 = preg_replace("/" . $ini . "=(.*);/", $ini . "=" . $value . ";", $str);
}
else
{
$str2 = preg_replace("/" . $ini . "=(.*);/", $ini . "=\"" . $value . "\";",$str);
}
file_put_contents($file, $str2);
}


//echo getconfig("./2.php", "bb", "string");
getconfig("./2.php", "bb");//
updateconfig("./2.php", "kkk", "admin");
//echo "<br/>".getconfig("./2.php", "name","string");

?>

復制代碼 代碼如下:
//完善改進版


/**
* 配置文件操作(查詢了與修改)
* 默認沒有第三個參數時,按照字符串讀取提取''中或""中的內容
* 如果有第三個參數時為int時按照數字int處理。
*調用demo
$name="admin";//kkkk
$bb='234';

$bb=getconfig("./2.php", "bb", "string");
updateconfig("./2.php", "name", "admin");
*/
function get_config($file, $ini, $type="string"){
if(!file_exists($file)) return false;
$str = file_get_contents($file);
if ($type=="int"){
$config = preg_match("/".preg_quote($ini)."=(.*);/", $str, $res);
return $res[1];
}
else{
$config = preg_match("/".preg_quote($ini)."=\"(.*)\";/", $str, $res);
if($res[1]==null){
$config = preg_match("/".preg_quote($ini)."='(.*)';/", $str, $res);
}
return $res[1];
}
}

function update_config($file, $ini, $value,$type="string"){
if(!file_exists($file)) return false;
$str = file_get_contents($file);
$str2="";
if($type=="int"){
$str2 = preg_replace("/".preg_quote($ini)."=(.*);/", $ini."=".$value.";",$str);
}
else{
$str2 = preg_replace("/".preg_quote($ini)."=(.*);/",$ini."=\"".$value."\";",$str);
}
file_put_contents($file, $str2);
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved