How to upload and parse a CSV file in php - php

I want to upload a csv file with php. After the file is uploaded, I want to display the data of the CSV file. I would like an example how to accomplish this task.

This can be done in a much simpler manner now.
$tmpName = $_FILES['csv']['tmp_name'];
$csvAsArray = array_map('str_getcsv', file($tmpName));
This will return you a parsed array of your CSV data. Then you can just loop through it using a foreach statement.

untested but should give you the idea. the view:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" /></form>
upload.php controller:
$csv = array();
// check there are no errors
if($_FILES['csv']['error'] == 0){
$name = $_FILES['csv']['name'];
$ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
$type = $_FILES['csv']['type'];
$tmpName = $_FILES['csv']['tmp_name'];
// check the file is a csv
if($ext === 'csv'){
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
// necessary if a large csv file
set_time_limit(0);
$row = 0;
while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
// number of fields in the csv
$col_count = count($data);
// get the values from the csv
$csv[$row]['col1'] = $data[0];
$csv[$row]['col2'] = $data[1];
// inc the row
$row++;
}
fclose($handle);
}
}
}

Although you could easily find a tutorial how to handle file uploads with php, and there are functions (manual) to handle CSVs, I will post some code because just a few days ago I worked on a project, including a bit of code you could use...
HTML:
<table width="600">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<tr>
<td width="20%">Select file</td>
<td width="80%"><input type="file" name="file" id="file" /></td>
</tr>
<tr>
<td>Submit</td>
<td><input type="submit" name="submit" /></td>
</tr>
</form>
</table>
PHP:
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
//Print file details
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
//if file already exists
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
//Store file in directory "upload" with the name of "uploaded_file.txt"
$storagename = "uploaded_file.txt";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
}
}
} else {
echo "No file selected <br />";
}
}
I know there must be an easier way to do this, but I read the CSV file and store the single cells of every record in an two dimensional array.
if ( isset($storagename) && $file = fopen( "upload/" . $storagename , r ) ) {
echo "File opened.<br />";
$firstline = fgets ($file, 4096 );
//Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
$num = strlen($firstline) - strlen(str_replace(";", "", $firstline));
//save the different fields of the firstline in an array called fields
$fields = array();
$fields = explode( ";", $firstline, ($num+1) );
$line = array();
$i = 0;
//CSV: one line is one record and the cells/fields are seperated by ";"
//so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
while ( $line[$i] = fgets ($file, 4096) ) {
$dsatz[$i] = array();
$dsatz[$i] = explode( ";", $line[$i], ($num+1) );
$i++;
}
echo "<table>";
echo "<tr>";
for ( $k = 0; $k != ($num+1); $k++ ) {
echo "<td>" . $fields[$k] . "</td>";
}
echo "</tr>";
foreach ($dsatz as $key => $number) {
//new table row for every record
echo "<tr>";
foreach ($number as $k => $content) {
//new table cell for every field of the record
echo "<td>" . $content . "</td>";
}
}
echo "</table>";
}
So I hope this will help, it is just a small snippet of code and I have not tested it, because I used it slightly different. The comments should explain everything.

I have created below snippet with the help of #Thomas Clowes answer
$tmpName = $_FILES['csv']['tmp_name'];
$csv_data = array_map('str_getcsv', file($tmpName));
array_walk($csv_data , function(&$x) use ($csv_data) {
$x = array_combine($csv_data[0], $x);
});
/**
*
* array_shift = remove first value of array
* in csv file header was the first value
*
*/
array_shift($csv_data);
// Print Result Data
echo '<pre/>';
print_r($csv_data);
It will get result like below
Array
(
[0] => Array
(
[make] => Audi
[model] => S4
[grade] =>
[chassis] => WAUZZZ8K9DA076529
[year] => 2012
[kms] => 127000
[color] => White
[doors] => 4
[cc] => 3000
[engineno] =>
[trans] => FAT
[fueltype] => P
[condition] => 4
[price] => 15753
)
)

You want the handling file uploads section of the PHP manual, and you would also do well to look at fgetcsv() and explode().

I feel str_getcsv — Parse a CSV string into an array is the best option for you.
You need to upload the file to the server.
Parse the file using str_getcsv.
Run through the array and align as per u need on your website.

function doParseCSVFile($filesArray)
{
if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) {
$strFilePath = $filesArray['frmUpload']['tmp_name'];
$strFileHandle = fopen($strFilePath,"r");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
do {
if ($line_of_text[0]) {
$strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
ExecuteQry($strInsertSql);
}
} while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);
} else {
return FALSE;
}
}

public function uploadCsvFile(){
try{
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$request = $this->post();
$fileName = $request->file;
$file = fopen($fileName, "r"); //open the file
// $fileName = $_FILES["file"]["tmp_name"];
while(($column = fgetcsv($file)) !== FALSE){
$num = count($column);
$this->dbw->query("insert into csv_upload(first_name,last_name,email,phone,address,pin) values('".$column[0]."','".$column[1]."','".$column[2]."','".$column[3]."','".$column[4]."','".$column[5]."')");
}
fclose($file);
}
}catch (Exception $e) {
$this->responseErr($e->getMessage(), 500);
}
}

You can try with this:
function doParseCSVFile($filesArray)
{
if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) {
$strFilePath = $filesArray['frmUpload']['tmp_name'];
$strFileHandle = fopen($strFilePath,"r");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
do {
if ($line_of_text[0]) {
$strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
ExecuteQry($strInsertSql);
}
} while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);
} else {
return FALSE;
}
}

Related

How can I get the contents of a file one line at a time?

I have a project where a user uploads a photo with a name and caption, and I am having trouble with displaying the name and caption.
Right now, it's displaying the entire text file with each image, and I am having trouble fixing this.
My code so far:
<?php
$Dir = "files";
$DirEntries = scandir($Dir);
foreach ($DirEntries as $Entry)
{
if((strcmp($Entry, '.') != 0) && (strcmp($Entry, '..') != 0))
{
echo "<p>Name: " . file_get_contents("imagelist.txt") . "</p>";
echo "<a href=\"files/" . $Entry . "\" target=\"_blank\" >" . $Entry . "</a><br />\n";
}
}
closedir($DirOpen);
?>
Any help would be greatly appreciated.
You can use fgets():
$inputFile = fopen("file.txt", "r");
if ($inputFile) {
while (($line = fgets($inputFile)) !== false) {
echo $line."<br>";
// The process read the file line by line
}
} else {
echo "There was an error in the opening file";
}
fclose($inputFile);

upload and diplay big CSV file

I have a script that uploads and display a CSV file into HTML table.
My problem is that I have an error when I try to open big files.
My file is about 4.5 Mo with 80000 lines. It works fine with small files but I get
Warning: fopen(upload/test.csv): failed to open stream: No such file or directory in /var/www/cvs/PHP charts/sb-admin-v2/test.php on line 45
with big files
Here is my code
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" />
</form>
<?php
//upload
// for set memory limit & execution time
ini_set('memory_limit', '512M');
ini_set('max_execution_time', '180');
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
//if file already exists
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
//Store file in directory "upload" with the name of "uploaded_file.txt"
$storagename = "test.csv";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
}
}
} else {
echo "No file selected <br />";
}
}
//display
$row = 1;
if (($handle = fopen("upload/test.csv", "r")) !== FALSE) {
echo '<table border="1">';
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
?>
Well when I ran into this problem I resorted to a client side solution with https://github.com/knrz/CSV.js. Works very well and takes the load off my server. Only thing is I did not need the entire CSV to be uploaded to my server, once parsed only selective portions were sent using ajax.
If you are only trying to display the data in HTML table this can be a very good solution.

How to read/change directories for file browsing?

I'm having a real disconnect on how to do this--partly due to my inexperience with working with the file system. I'm trying to create a script that will navigate the folders a files below it. The file currently works by listing the contents of the directory it's in (aka "."). I'm stumped on how to make it list contents of the folders below and the best way to do it. How would my script need reworking to fit this goal?
[code]
// sets ordering variables
$a = $_GET['a'];
// are you allowed to delete?
if($_SESSION['delete'] == "ON") {
$do_del = true;
}
else {
$do_del = false;
}
// scandir to opendir coversion from stackoverflow.com/questions/6823489/
$files_dir = ".";
$dir_handle = opendir($files_dir);
while ($dir_temp = readdir($dir_handle)) {
$arr_dir[] = $dir_temp;
}
closedir($dir_handle);
// function created by "acecream" on php.net; modified to include reverse sort
function sortArray($array, $key, $reverse = false)
{
if(isset($array)) {
foreach ($array as $i => $k)
{ $sort_values[$i] = $array[$i][$key]; }
if ($reverse == true)
{ arsort ($sort_values); }
else
{ asort ($sort_values); }
reset ($sort_values);
while (list ($arr_key, $arr_val) = each ($sort_values))
{ $sorted_arr[] = $array[$arr_key]; }
return $sorted_arr;
}
}
foreach($arr_dir as $file)
{
if(!preg_match("/(_vti)|(_borders)|(_private)|(hidden)|(~_)|(\.php)/", $file) && ($file != ".") && ($file !=".."))
{
$full = "$files_dir/$file";
$name = strval($file);
$size = sprintf("%u", filesize($full));
$kind = pathinfo($file, PATHINFO_EXTENSION); // strval(end(explode(".", $file)));
$mtime = filemtime($full); // modify date
$ctime = filectime($full); // creation date
$arr_files[] = array($name, $size, $kind, $mtime, $ctime);
}
}
$arr_count = count($arr_files);
switch ($a) {
case 1 : $arr_files = sortArray($arr_files, 0); break;
case 2 : $arr_files = sortArray($arr_files, 0, true); break;
case 3 : $arr_files = sortArray($arr_files, 1); break;
case 4 : $arr_files = sortArray($arr_files, 1, true); break;
case 5 : $arr_files = sortArray($arr_files, 2); break;
case 6 : $arr_files = sortArray($arr_files, 2, true); break;
case 7 : $arr_files = sortArray($arr_files, 3); break;
case 8 : $arr_files = sortArray($arr_files, 3, true); break;
default: $arr_files = sortArray($arr_files, 3, true); break;
}
unset($a);
function myFileSize($value) {
// convert raw byte site to friendlier forms
if($value > 1000) { $sizestr = round(($value/1024), 1) . " KB"; }
else { $sizestr = "$value B"; }
if($value > 1000000) { $sizestr = round(($value/1048576), 1) . " MB"; }
if($value > 1000000000) { $sizestr = round(($value/1073741824), 1) . " GB"; }
return $sizestr;
}
function myDate($value) {
$date = date("j M y G:i", $value);
return $date;
}
if($arr_count > 0)
{
if($do_del == true) {
print "<form method=\"post\" action=\"./?d=delete\">\n";
}
print "<table>\n";
print " <tr>\n";
print " <td>File Name</td>\n";
print " <td>Size</td>\n";
print " <td>Type</td>\n";
print " <td>Modified</td>\n";
print " <td>Created</td>\n";
if($do_del == true) {
print " <td>Delete?</td>\n";
}
print " </tr>\n";
print " <tr style=\"vertical-align: middle; background-color: #fff; border: 1px solid #000;\">\n";
print " <td>\n";
print " <img src=\"./~_arr-asc.gif\" border=\"0\">\n";
print " <img src=\"./~_arr-dsc.gif\" border=\"0\">\n";
print " </td>\n";
print " <td>\n";
print " <img src=\"./~_arr-asc.gif\" border=\"0\">\n";
print " <img src=\"./~_arr-dsc.gif\" border=\"0\">\n";
print " </td>\n";
print " <td>\n";
print " <img src=\"./~_arr-asc.gif\" border=\"0\">\n";
print " <img src=\"./~_arr-dsc.gif\" border=\"0\">\n";
print " </td>\n";
print " <td>\n";
print " <img src=\"./~_arr-asc.gif\" border=\"0\">\n";
print " <img src=\"./~_arr-dsc.gif\" border=\"0\">\n";
print " </td>\n";
print " <td> </td>\n";
if($do_del == true) {
print " <td> </td>\n";
}
print " </tr>\n";
for ($beat = 0; $beat < $arr_count; $beat++)
{
$name = $arr_files[$beat][0];
$size = $arr_files[$beat][1];
$ext = strtolower($arr_files[$beat][2]);
$mdate = $arr_files[$beat][3];
$cdate = $arr_files[$beat][4];
$size = myFileSize($size);
$mdate = myDate($mdate);
$cdate = myDate($cdate);
// pick the image for file type based on file extension
if(is_dir($name)) {
$pic = "~_folder.png";
}
else {
$pic = "~_file.png";
}
$url = "$name"; // create hard link
print " <tr>\n";
print " <td style=\"width: 300px;\"><img src=\"./$pic\"> $url</td>\n";
print " <td style=\"width: 75px;\">$size</td>\n";
print " <td style=\"width: 50px;\">$ext</td>\n";
print " <td style=\"width: 150px;\">$mdate</td>\n";
print " <td style=\"width: 150px;\">$cdate</td>\n";
if($do_del == true) {
print " <td><input type=\"checkbox\" name=\"list[$files_dir/$name]\" value=\"ON\"></td>\n";
}
print " </tr>\n";
}
print "</table>\n";
if($do_del == true) {
print " <p><input name=\"Submit1\" type=\"submit\" value=\"submit\">\n";
print " <input name=\"Reset1\" type=\"reset\" value=\"reset\"></p>\n";
print "</form>\n";
}
}
else
{
print "There are no files available for download.";
}
[/code]
Make your script a function that takes in the path.
Then in the while statement inside if(is_dir($file)) call your function and pass it $file.
For example,
function myFileSize($value) {...}
function myDate($value) {...}
function list_contents($path)
{
$dir_name = $path;
.
.
.
$dir = opendir($path);
.
.
.
while ($file = readdir($dir)) {
// do some stuff
if (is_dir($file)) {
list_contents($file);
}
}
}
Depending on what you want to do you will need to modify the output of the list_contents() function to work with the recursion. You could generate some tree structure using an array and then print the tree out later like:
// return an array representing tree structure
function list_contents($path, &$tree)
{
// ...
while ($file = readdir($dir)) {
$tree[$path][] = $file;
if (is_dir($file)) {
list_contents($file, $tree[$path]);
}
}
return $tree;
}
function print_tree($tree)
{
// code to display array using tree structure
}
$path = '.';
$dir_name = $path;
$tree_array = array();
$tree = list_contents($path, $tree_array)
print_tree($tree);
Or you could add a variable to count the number of levels in the method is
function list_contents($path, $level = 0)
{
//...
// indent output text by $level number of tabs
while($file = readdir($dir) {
if (is_dir($file)) {
list_contents($file, $level++)
}
}
}
list_contents($path);
Output would look something like
> Root
> Folder1 in root
> Folder2 in root
> Folder1 in Folder2
> Folder2 in Folder2
> Folder3 in root
> Folder1 in Folder3
> Folder1 in Folder1/Folder3
> File1 in Folder1
> File1 in root
> File2 in root
As a suggestion, I would take any functions related to getting file information or manipulating files and put them in their own file file_functions.php and then include that at the top of your script.

In PHP is it possible to inspect content of a Zip file without extracting its content first?

I have seen the ZipArchive class in PHP which lets you read zip files. But I'm wondering if there is a way to iterate though its content without extracting the file first
As found as a comment on http://www.php.net/ziparchive:
The following code can be used to get a list of all the file names in
a zip file.
<?php
$za = new ZipArchive();
$za->open('theZip.zip');
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
print_r( basename( $stat['name'] ) . PHP_EOL );
}
?>
http://www.php.net/manual/en/function.zip-entry-read.php
<?php
$zip = zip_open("test.zip");
if (is_resource($zip))
{
while ($zip_entry = zip_read($zip))
{
echo "<p>";
echo "Name: " . zip_entry_name($zip_entry) . "<br />";
if (zip_entry_open($zip, $zip_entry))
{
echo "File Contents:<br/>";
$contents = zip_entry_read($zip_entry);
echo "$contents<br />";
zip_entry_close($zip_entry);
}
echo "</p>";
}
zip_close($zip);
}
?>
I solved the problem like this.
$zip = new \ZipArchive();
$zip->open(storage_path('app/'.$request->vrfile));
$name = '';
//looped through the zip files and got each index name of the files
//since I only wanted the first name which is the folder name I break the loop
//after updating the variable $name with the index name and that's it
for( $i = 0; $i < $zip->numFiles; $i++ ){
$filename = $zip->getNameIndex($i);
var_dump($filename);
$name = $filename;
if ($i == 1){
break;
}
}
var_dump($name);
Repeated Question. Search before posting.
PHP library that can list contents of zip / rar files
<?php
$rar_file = rar_open('example.rar') or die("Can't open Rar archive");
$entries = rar_list($rar_file);
foreach ($entries as $entry) {
echo 'Filename: ' . $entry->getName() . "\n";
echo 'Packed size: ' . $entry->getPackedSize() . "\n";
echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";
$entry->extract('/dir/extract/to/');
}
rar_close($rar_file);
?>

PHP Losing values in an 2-diminational associative array after they have been modified

I'm baffled about a problem I have with PHP and a 2-dim associative array. I'm in a class for PHP and the instructor is rather clueless.
I declare the array to make it global with some information. I use an html form to display the data from the array. I modify two null values in the array with an html form "calc" button. Everything works great. The array is updated. I then use a form "order" button to create a text file using the array values. This is when it gets weird. The modified values in the array are gone. I can create and save the text file within the $_Post calc If statement just fine. Same text using the $_Post submit button - gives me the old null values.
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>Online Orders</title>
</head>
<body>
<?php
function DisplayTable(){
echo "<h2 style ='text-align:center'>Online Order</h2>\n";
echo "<p>Enter the desired items you wish to order:</p>\n";
echo "<form action='OnlineOrders.php' method ='POST'>";
echo "<table style='background-color:lightgray' border='1' width='80%'>";
echo "<tr><td width = '10%' style = 'text-align:center'><span style = 'font-weight:bold'>Item</span></td>
<td width = '40%' style = 'text-align:center'><span style = 'font-weight:bold'>
Description</span></td>";
echo "<td width = '10%' style = 'text-align:center'><span style = 'font-weight:bold'>Price</span></td>";
echo "<td width = '10%' style = 'text-align:center'><span style = 'font-weight:bold'>Quantity</span></td>";
echo "<td width = '10%' style = 'text-align:center'><span style = 'font-weight:bold'>Total</span></td></tr>";
//foreach($products as $item){
global $products;
for ($i = 0; $i < count($products); ++$i){
$name = key($products);
echo "<tr><td style = 'text-align:left'>" . $name . "</td>";
echo "<td style = 'text-align:left'>" . $products[$name]['Description']. "</td>";
echo "<td style = 'text-align:center'>" . $products[$name]['Price']. "</td>";
if($products[$name]['Quantity'] > 0)
$value = $products[$name]['Quantity'];
else
$value = "";
echo "<td style = 'text-align:left'><input type='text' name = 'quantity[" . $name ."]' value = $value></td>";
if($products[$name]['Total'] > 0)
echo "<td style = 'text-align:left'>" . $products[$name]['Total']. "</td>";
else
echo "<td></td>";
echo "</tr>";
next($products);
}
echo "</table>";
echo "<p></p>";
echo "<input type ='submit' name='submit' value='Order' />";
echo "<input type ='submit' name='calc' value='Calculate' />";
echo "</form>";
}
//creates data array
$pencils = array("Price" => "1.50", "Description" =>"12pk of #2 pencils", "Quantity" => NULL, "Total" => NULL);
$pens = array("Price" => "3.50", "Description" =>"12pk of Bic blue ink pens", "Quantity" => NULL, "Total" => NULL);
$paper = array("Price" => "5.50", "Description" =>"6pk of letter-sized, 100 count paper pads",
"Quantity" => NULL, "Total" => NULL);
$stapler = array("Price" => "6.40", "Description" =>"Streamline stapler - black", "Quantity" => NULL,
"Total" => NULL);
$staples = array("Price" => "2.00", "Description" =>"Streamline staples, 5000 count", "Quantity" => NULL,
"Total" => NULL);
$products = array("Pencils" => $pencils, "Pens" => $pens, "Paper" => $paper, "Stapler" => $stapler,
"Staples" => $staples);
//doesn't work right doesn't have updated values
//Uses the array to create a text file and saves it to the hard drive in a folder entitled "/OnlineOrders"
if(isset($_POST['submit'])){
global $products;
$Dir = "OnlineOrders";
if (is_dir($Dir)){
echo "Products in order";
//print_r($products); //prints out the array as it was declared not modified!
$SaveString = "Online Order\r\n\r\n";
$SaveString .= date('m/d/Y') . "\r\n\r\n";
$SaveString .= "Item\t\tPrice\t Quantity\tTotal\r\n";
for ($i = 0; $i < count($products); ++$i){
$name = key($products);
// if ($products[$name]['Quantity']>0){
$SaveString .= $name ."\t\t" . $products[$name]['Price'] ."\t\t". $products[$name]['Quantity'] .
"\t" . $products[$name]['Total'] ."\r\n\r\n";
// }
// else
// echo "Nothing to write to file";
next($products);
}
$TimeStamp = date('Y_m_d_G_i');
$SaveFileName = "$Dir/order.$TimeStamp.txt";
$fp = fopen($SaveFileName, "wb");
if ($fp === FALSE){
echo "There was an error creating \"" . htmlentities($SaveFileName) . "\".<br />\n";
}
else {
if (flock($fp, LOCK_EX)) {
if (fwrite($fp, $SaveString)>0)
echo "Successfully wrote to file \"" . htmlentities($SaveFileName) . "\".<br />\n";
else
echo "There was an error writing to file \"" . htmlentities($SaveFileName) . "\".<br />\n";
flock($fp, LOCK_UN);
}
else{
echo "There was an error locking file \"" . htmlentities($SaveFileName) .
" for writing\".<br />\n";
}
fclose($fp);
}
}
echo "<p><a href='OnlineOrders.php'>Order Again?</p>\n";
}
//enter values into the quantity input items and addes qty and total to array and redisplays the html table with updated values
else if(isset($_POST['calc'])){
global $products;
$quantity = $_POST['quantity'];
if(is_array($quantity)){
foreach ($quantity as $item => $value){
if($value <> NULL){
$amount = stripslashes($value);
if(is_numeric($amount) && ($amount > 0)){
$products[$item]['Quantity'] = $amount;
$products[$item]['Total'] = ($products[$item]['Price'] * $amount);
}
else
echo "<p>You must enter a number greater than 0 for $item's quantity</p>\n";
}
}
DisplayTable();
//print_r($products); //TEST - PRINTS OUT THE ARRAY WITH UPDATED VALUES CORRECTLY
//TESTING STARTS HERE - SAME CODE FROM submit button and it works
$Dir = "OnlineOrders";
if (is_dir($Dir)){
$SaveString = "Online Order\r\n\r\n";
$SaveString .= date('m/d/Y') . "\r\n\r\n";
$SaveString .= "Item\t\tPrice\t Quantity\tTotal\r\n";
reset($products);
for ($j = 0; $j < count($products); ++$j){
$name = key($products);
if ($products[$name]['Quantity']>0){
$SaveString .= $name ."\t\t" . $products[$name]['Price'] ."\t\t". $products[$name]['Quantity'] .
"\t" . $products[$name]['Total'] ."\r\n";
}
next($products);
}
$TimeStamp = date('Y_m_d_G_i');
$SaveFileName = "$Dir/order.$TimeStamp.txt";
$fp = fopen($SaveFileName, "wb");
if ($fp === FALSE){
echo "There was an error creating \"" . htmlentities($SaveFileName) . "\".<br />\n";
}
else {
if (flock($fp, LOCK_EX)) {
if (fwrite($fp, $SaveString)>0)
echo "Successfully wrote to file \"" . htmlentities($SaveFileName) . "\".<br />\n";
else
echo "There was an error writing to file \"" . htmlentities($SaveFileName) . "\".<br />\n";
flock($fp, LOCK_UN);
}
else{
echo "There was an error locking file \"" . htmlentities($SaveFileName) .
" for writing\".<br />\n";
}
fclose($fp);
}
}
//Testing Ends Here
}
}
else
DisplayTable();
?>
</body>
</html>
My programming "GOD" classmate who isn't even in my class educated me on how PHP and server-side processing works. Basically, the Array does not live once you finish the processing. When the page reloads, the default array is re-created with the default NULL values. I created several functions and run the calculations for both the Calc button and Order buttons and amen it works correctly.

Categories