I'm working on a web project in which a user should be able to take a .csv generated by an Asana project export and import it so it prints specific rows.
I am actually able to import the file :
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//error while uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else {
//error message if file already exists
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
//Uploads file in the upload/ folder
$storagename = "uploaded_file.txt";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
echo "<strong>Stored in:</strong> " . "upload/" . $_FILES["file"]["name"] . "<br />";
}
}
} else {
echo "No file selected <br />";
}
}
and then dump the data :
$row = 1;
if (($handle = fopen("upload/" . $storagename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num champs à la ligne $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
So, in order to print some specific rows, I thought of this, which would take the data from the 11, 12, 13 & 14 rows :
$kilometrage = $data[11];
$stationnement = $data[12];
$perdiem = $data[13];
$depenses = $data[14];
But sadly, I am not able to figure this out.
Is someone have a clue/idea/tip? Any help will be greatly appreciated. Thank you!
Actually, I did figured out with this, by looping, setting and echoing the variables. I still don't know if it's the best way of doing it but it actually works :
$row = 1;
if (($handle = fopen("upload/" . $storagename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
$kilometrage = $data[11];
$stationnement = $data[12];
$perdiem = $data[13];
$depenses = $data[14];
for ($c=0; $c < 1; $c++) {
echo "<table style='min-width:1000px;'><tbody><tr>";
echo "<td style='width:25%'>" . $kilometrage . "</td>";
echo "<td style='width:25%'>" . $stationnement . "</td>";
echo "<td style='width:25%'>" . $perdiem . "</td>";
echo "<td style='width:25%'>" . $depenses . "</td>";
echo "</tr></tbody></table>";
}
}
fclose($handle);
}
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);
I'm trying to upload 3 files using html and PHP, in local server it is working but when I host it, this code is not working. What may be the problem?
Here is my HTML and PHP Code:
HTML CODE:
<form name="test" id="test" action="pet_up.php" enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="5097152" />
Upload File 1:<input type='file' id='f1' name='f1'/>
Upload File 2:<input type='file' id='f2' name='f2'/>
Upload File 3:<input type='file' id='f3' name='f3'/>
<input type="submit" value="Update"/>
</form>
PHP CODE:
if(isset($_FILES['f1']['name']))
{
$image1 = $_FILES['f1']['name'];
$tmp1 = $_FILES['f1']['tmp_name'];
$pathAndName1 = "uploads/".$image1;
if(!empty($_FILES) && file_exists($tmp1) && is_uploaded_file($tmp1))
{
move_uploaded_file($tmp1,$pathAndName1);
}
else
{
$pathAndName1="";
}
echo"<script>alert(".$pathAndName1.");</script>";
$qry="update petition set f1='".$pathAndName1."'";
$result=mysql_query($qry);
}
if(isset($_FILES['f2']['name']))
{
$image2 = $_FILES['f2']['name'];
$tmp2 = $_FILES['f2']['tmp_name'];
$pathAndName2 = "uploads/".$image2;
if(!empty($_FILES) && file_exists($tmp2) && is_uploaded_file($tmp2))
{
move_uploaded_file($tmp2,$pathAndName2);
}
else
{
$pathAndName2="";
}
echo"<script>alert(".$pathAndName2.");</script>";
$qry="update petition set f2='".$pathAndName2."'";
$result=mysql_query($qry);
}
if(isset($_FILES['f3']['name']))
{
$image3 = $_FILES['f3']['name'];
$tmp3 = $_FILES['f3']['tmp_name'];
$pathAndName3 = "uploads/".$image3;
if(!empty($_FILES) && file_exists($tmp3) && is_uploaded_file($tmp3))
{
move_uploaded_file($tmp3,$pathAndName3);
}
else
{
$pathAndName3="";
}
echo"<script>alert(".$pathAndName3.");</script>";
$qry="update petition set f3='".$pathAndName3."'";
$result=mysql_query($qry);
}
by default, you can upload a file with 2Mb size, if you want bigger file to upload then change your php.ini file and set your value that you want to upload.
Please use this simplified version of your query.. This will help you debug more easily...
$count = count($_FILES);
for ($i = 1; $i <= $count; $i++)
{
if (isset($_FILES['f' . $i]['name']))
{
$image . $i= $_FILES['f' . $i]['name'];
$tmp . $i= $_FILES['f' . $i]['tmp_name'];
$pathAndName . $i= "uploads/" . $image . $i;
if (!empty($_FILES) && file_exists($tmp . $count) && is_uploaded_file($tmp . $count))
{
move_uploaded_file($tmp . $i, $pathAndName . $i);
echo 'error uploading file'.$i;
}
else
{
$pathAndName . $i= "";
}
}
if ($pathAndName . $i!= '')
{
echo"<script>alert(" . $pathAndName . $i. ");</script>";
}
$qry = mysql_query("update petition set f" . $i. "='" . $pathAndName . $i. "'");
if(!$qry)
{
echo 'error in query'.$i;
}
}
I've got a script which lists all the txt files that I have in a directory. I've put a hyperlink each of the results that comes up and I want to the redirect to a simple editor which I have the code for.
This is the code for listing the files in the directory;
<?php
//Open directory
$dir = dir("content");
//List files in directory
while (($file = $dir->read()) !== false){
//Make sure it's a .txt file
if(strlen($file) < 5 || substr($file, -4) != '.txt')
continue;
echo "Page: <a href='content/" .$file. "'>" . $file . "</a><br />";
}
$dir->close();
?>
And the code to edit the file:
<?
if($_POST['Submit']){
$open = fopen("content/body.txt","w+");
$text = $_POST['update'];
fwrite($open, $text);
fclose($open);
echo "File updated.<br />";
echo "File:<br />";
$file = file("content/body.txt");
foreach($file as $text) {
echo $text."<br />";
}
}else{
$file = file("content/body.txt");
echo "<form action=\"".$PHP_SELF."\" method=\"post\">";
echo "<textarea Name=\"update\" cols=\"50\" rows=\"10\">";
foreach($file as $text) {
echo $text;
}
echo "</textarea>";
echo "<input name=\"Submit\" type=\"submit\" value=\"Update\" />\n
</form>";
}
?>
What's the best way to try and do this?
Thanks in advance.
I think you mean this:
in directory list use this:
echo "Page: <a href='editor_script.php?filename=".$file."'>".$file."</a><br/>";
in your editor script use this:
$open = fopen("content/".$_GET['filename'].".txt","w+");
$file = file("content/".$_GET['filename'].".txt");
I' not sure but maybe you have to remove action from form
echo '<form method="post">';
or use url with $_GET['filename']
echo '<form action="editor_script.php?filename='.$_GET['filename'].'" method="post">';
maybe this works too but I'm not sure
echo '<form action="?filename='.$_GET['filename'].'" method="post">';
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;
}
}