”As am diving into PHP development for web applications, I decide to explore some unique feature of the programming language, I have been able to discover that PHP has so many useful inbuilt functions for web application development and it gets better when object oriented programming pattern is adopted by the developer. In this tutorial we are going to look at how to manipulate CVS file using PHP.
I recently use this feature to create and audit trail module for one of my latest projects . We are going to make use of PHP class I found on PHP Class website to support this feature,. Let’s start by including the php class below into our index.php file
class CSV_Data{
protected $cache = array();
protected $lang;
protected $file;
public $course_code;
public function __construct($file){
$this -> setFile($file);
$this->course_code="IOT";
}
public function setFile($file) {
$this -> file = preg_replace("#[\////]+#",DIRECTORY_SEPARATOR, $file);
$path = $this -> file;
if(!array_key_exists($path, $this -> cache)){
if(file_exists($path)){ $found = true;
} else { $found = false;
} if($found){
$file = fopen($path, 'r');
$flex = true; $array = array();
$names = array();
while (($line = fgetcsv($file,0,',')) !== FALSE) {
if($line){ $name = array_shift($line);
if($flex){ if(!$line){ break; }
$indexes = array();
foreach($line as $index1){
if(!array_key_exists($index1, $array)){
$array[$index1] = array(); $indexes[] = $index1;
} }
$flex = false; }
else { if(!array_key_exists($name, $names)){
foreach($indexes as $i => $index1){
if(array_key_exists($i, $line)){ $array[$index1][$name] = stripslashes($line[$i]); }
else { $array[$index1][$name] = null; } } $names[$name] = true;
} } } } }
else { $array = array(); }
$this -> cache[$path] = $array; } return $this;
} public function get($x, $y){ $path = $this -> file;
if(!empty($this -> cache[$path][$x]) && array_key_exists($y, $this -> cache[$path][$x])){
return $this -> cache[$path][$x][$y]; }
else { return ""; } }
public function edit($x, $y, $new_value){
$key = key($this -> cache[$this -> file]);
if(!array_key_exists($y,$this -> cache[$this -> file][$key])){
$keys_z = array(); foreach($this -> cache[$this -> file][$key] as $keyz=>$val){
if(empty($this -> cache[$this -> file][$x])|| !array_key_exists($keyz,$this -> cache[$this -> file][$x])){
$this -> cache[$this -> file][$x][$keyz] = "";
$this -> cache[$this -> file][$key][$y] = "";
} } }
$this -> cache[$this -> file][$x][$y] = trim($new_value);
return $this; }
public function save() {
$lines = array(array($this->course_code));
$xindex = 1;
$yindex = 0;
foreach($this -> cache[$this -> file] as $x => $value1) {
$no = 0;
$lines[0][$xindex] = $x;
$xindex++;
$yindex++;
foreach($value1 as $y => $value){
$no++; $lines[$no][0] = $y; $lines[$no][$yindex] = $value;
} }
$fp = fopen($this -> file, 'w');
foreach($lines as $i1=>$line){
fwrite($fp, ($i1? PHP_EOL :""));
end($line); $key = key($line);
reset($line);
for($i2=0;$i2<=$key;$i2++){
fwrite($fp,(($i2)?',':'').(array_key_exists($i2,$line)?addcslashes($line[$i2],'\"'):""));
} } fclose($fp); } }
What we want to do is to use PHP to log the IP address of the site visitors but as a means of demostartiong how we can use PHP to edit the CVS file we are also going to use PHP to edit our own information in the file.
To also demostarte how you can secure the access to this file each user will be eligible to edit their own logged data, we will verify their identitiy using their IP address.
No here is our Index .php file.protected $cache = array();
protected $lang;
protected $file;
public $course_code;
public function __construct($file){
$this -> setFile($file);
$this->course_code="IOT";
}
public function setFile($file) {
$this -> file = preg_replace("#[\////]+#",DIRECTORY_SEPARATOR, $file);
$path = $this -> file;
if(!array_key_exists($path, $this -> cache)){
if(file_exists($path)){ $found = true;
} else { $found = false;
} if($found){
$file = fopen($path, 'r');
$flex = true; $array = array();
$names = array();
while (($line = fgetcsv($file,0,',')) !== FALSE) {
if($line){ $name = array_shift($line);
if($flex){ if(!$line){ break; }
$indexes = array();
foreach($line as $index1){
if(!array_key_exists($index1, $array)){
$array[$index1] = array(); $indexes[] = $index1;
} }
$flex = false; }
else { if(!array_key_exists($name, $names)){
foreach($indexes as $i => $index1){
if(array_key_exists($i, $line)){ $array[$index1][$name] = stripslashes($line[$i]); }
else { $array[$index1][$name] = null; } } $names[$name] = true;
} } } } }
else { $array = array(); }
$this -> cache[$path] = $array; } return $this;
} public function get($x, $y){ $path = $this -> file;
if(!empty($this -> cache[$path][$x]) && array_key_exists($y, $this -> cache[$path][$x])){
return $this -> cache[$path][$x][$y]; }
else { return ""; } }
public function edit($x, $y, $new_value){
$key = key($this -> cache[$this -> file]);
if(!array_key_exists($y,$this -> cache[$this -> file][$key])){
$keys_z = array(); foreach($this -> cache[$this -> file][$key] as $keyz=>$val){
if(empty($this -> cache[$this -> file][$x])|| !array_key_exists($keyz,$this -> cache[$this -> file][$x])){
$this -> cache[$this -> file][$x][$keyz] = "";
$this -> cache[$this -> file][$key][$y] = "";
} } }
$this -> cache[$this -> file][$x][$y] = trim($new_value);
return $this; }
public function save() {
$lines = array(array($this->course_code));
$xindex = 1;
$yindex = 0;
foreach($this -> cache[$this -> file] as $x => $value1) {
$no = 0;
$lines[0][$xindex] = $x;
$xindex++;
$yindex++;
foreach($value1 as $y => $value){
$no++; $lines[$no][0] = $y; $lines[$no][$yindex] = $value;
} }
$fp = fopen($this -> file, 'w');
foreach($lines as $i1=>$line){
fwrite($fp, ($i1? PHP_EOL :""));
end($line); $key = key($line);
reset($line);
for($i2=0;$i2<=$key;$i2++){
fwrite($fp,(($i2)?',':'').(array_key_exists($i2,$line)?addcslashes($line[$i2],'\"'):""));
} } fclose($fp); } }
<?php
//include the php class
include_once "CSV_Data.php";
//get user information
//todays date with time
$now = date("Y-m-d h:i:s",time());
//user ip
$ip =$_SERVER['REMOTE_ADDR'].((!empty($_SERVER['HTTP_X_FORWARDED_FOR']))?'('.$_SERVER['HTTP_X_FORWARDED_FOR'].')': '');
//user browser
$browser = $_SERVER['HTTP_USER_AGENT'];
//open the cvs file
$data = new CSV_Data(dirname(__FILE__).'/visitors.csv');
?>
<html>
<head>
<title>CVS Manipulation with PHP| Coding Savvy</title>
<style>
html, body {
font-family: Arial,sans-serif;
background: none repeat scroll 0% 0% #FFF;
border: 0px none;
position: absolute;
height: 100%;
min-width: 100%;
font-size: 13px;
color: #404040;
direction: ltr;
}
.hd {
text-align: center;
background-color: #FFF;
background-image: linear-gradient(#D9EFFA, #D9EFFA 25%, #FFF);
background-repeat: no-repeat;
border-top: 3px solid #05903F;
padding: 20px 0px;
}
.btn {
display: inline-block;
padding: 4px 12px;
margin: 0px 10px 0px 0px;
font-size: 14px;
line-height: 20px;
color: #333;
text-align: center;
text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.75);
vertical-align: middle;
cursor: pointer;
background-color: #F5F5F5;
background-image: linear-gradient(to bottom, #FFF, #E6E6E6);
background-repeat: repeat-x;
border-width: 1px;
border-style: solid;
-moz-border-top-colors: none;
-moz-border-right-colors: none;
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
border-image: none;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) #A2A2A2;
border-radius: 4px;
box-shadow: 0px 1px 0px rgba(255, 255, 255, 0.2) inset, 0px 1px 2px rgba(0, 0, 0, 0.05);
}
</style>
</head>
<body>
<div class="hd">
<h1>
<a href="http://www.codingsavvy.com">CVS FILE MANIPULATION WITH PHP DEMO - Codingsavvy.com</a>
<div>
<script async='async' src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Savvy Leader -->
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-5655726184152350"
data-ad-slot="4213472965"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</div>
<?php
if(isset($_POST['submit'])){
//edit the CVS file
$data -> edit("Browser",trim($ip),trim($_POST['browser']));
//Save all changes
$data -> save();
echo ("<b> Your new Browser Name is:</b><h2 style='color:red;'>".$data -> get("Browser", trim($ip))."</h2> <br/>
Click Here to view Your New Details <a href='".$_SERVER['PHP_SELF']."'>Refresh</a><br/>" );
}else{
?>
<h2 style="text-align:left;">
If You are Seeing Nothing it is Due to your server security.
Your IP: <span style="color:red;"><?php echo($data -> get("User Ip", trim($ip))); ?></span> Has been Logged.</br>
Your Browser: <span style="color:red;"><?php echo($data -> get("Browser", trim($ip))); ?></span> Has been Logged<br/>
Edited Time: <span style="color:red;"><?php echo($data -> get("Time", trim($ip))); ?></span>
</h2>
<?php
}
/* now
*let view the chnages we made and
*the edited file*
*/
?>
</h1>
<b style="color:red;">use this form to manipulate the CVS file by editing your browser:</b>
<form action="<?php echo($_SERVER['PHP_SELF']); ?>" method="post" >
<table>
<tr><th><label>Browser</label><input placeholder="New Browswer" type="text" name="browser" />
</th><th><input class="btn" type="submit" name="submit" value="Edit" /></th><th></th></tr>
</table>
</form>
</body>
</html>
//include the php class
include_once "CSV_Data.php";
//get user information
//todays date with time
$now = date("Y-m-d h:i:s",time());
//user ip
$ip =$_SERVER['REMOTE_ADDR'].((!empty($_SERVER['HTTP_X_FORWARDED_FOR']))?'('.$_SERVER['HTTP_X_FORWARDED_FOR'].')': '');
//user browser
$browser = $_SERVER['HTTP_USER_AGENT'];
//open the cvs file
$data = new CSV_Data(dirname(__FILE__).'/visitors.csv');
?>
<html>
<head>
<title>CVS Manipulation with PHP| Coding Savvy</title>
<style>
html, body {
font-family: Arial,sans-serif;
background: none repeat scroll 0% 0% #FFF;
border: 0px none;
position: absolute;
height: 100%;
min-width: 100%;
font-size: 13px;
color: #404040;
direction: ltr;
}
.hd {
text-align: center;
background-color: #FFF;
background-image: linear-gradient(#D9EFFA, #D9EFFA 25%, #FFF);
background-repeat: no-repeat;
border-top: 3px solid #05903F;
padding: 20px 0px;
}
.btn {
display: inline-block;
padding: 4px 12px;
margin: 0px 10px 0px 0px;
font-size: 14px;
line-height: 20px;
color: #333;
text-align: center;
text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.75);
vertical-align: middle;
cursor: pointer;
background-color: #F5F5F5;
background-image: linear-gradient(to bottom, #FFF, #E6E6E6);
background-repeat: repeat-x;
border-width: 1px;
border-style: solid;
-moz-border-top-colors: none;
-moz-border-right-colors: none;
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
border-image: none;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) #A2A2A2;
border-radius: 4px;
box-shadow: 0px 1px 0px rgba(255, 255, 255, 0.2) inset, 0px 1px 2px rgba(0, 0, 0, 0.05);
}
</style>
</head>
<body>
<div class="hd">
<h1>
<a href="http://www.codingsavvy.com">CVS FILE MANIPULATION WITH PHP DEMO - Codingsavvy.com</a>
<div>
<script async='async' src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Savvy Leader -->
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-5655726184152350"
data-ad-slot="4213472965"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</div>
<?php
if(isset($_POST['submit'])){
//edit the CVS file
$data -> edit("Browser",trim($ip),trim($_POST['browser']));
//Save all changes
$data -> save();
echo ("<b> Your new Browser Name is:</b><h2 style='color:red;'>".$data -> get("Browser", trim($ip))."</h2> <br/>
Click Here to view Your New Details <a href='".$_SERVER['PHP_SELF']."'>Refresh</a><br/>" );
}else{
?>
<h2 style="text-align:left;">
If You are Seeing Nothing it is Due to your server security.
Your IP: <span style="color:red;"><?php echo($data -> get("User Ip", trim($ip))); ?></span> Has been Logged.</br>
Your Browser: <span style="color:red;"><?php echo($data -> get("Browser", trim($ip))); ?></span> Has been Logged<br/>
Edited Time: <span style="color:red;"><?php echo($data -> get("Time", trim($ip))); ?></span>
</h2>
<?php
}
/* now
*let view the chnages we made and
*the edited file*
*/
?>
</h1>
<b style="color:red;">use this form to manipulate the CVS file by editing your browser:</b>
<form action="<?php echo($_SERVER['PHP_SELF']); ?>" method="post" >
<table>
<tr><th><label>Browser</label><input placeholder="New Browswer" type="text" name="browser" />
</th><th><input class="btn" type="submit" name="submit" value="Edit" /></th><th></th></tr>
</table>
</form>
</body>
</html>
To view demo Click here and you can also download the Source Code for this tutorial HERE
Thanks!
Your feedback helps us improve tutorials.
No comments:
Post a Comment