0

I need to overwrite the content of a .txt file when I browse a file in a page.I have written a php script for it.

Form is given below

<input type="file" name="file" size="50" maxlength="25"> <br>
<input type="submit" name="upload" value="Upload">

and PHP script is

$file1=$_FILES['file'];
$out = file_get_contents($file1);

$file2 = "molecule.txt";
$filehandle = fopen($file2, "a");
$file_contents = file($file1);
$count = count(file($file1));
file_put_contents($file2, "");
$newlineno = 0;
foreach ($file_contents as $line_num => $line) {
    if (strpos($line, 'Standard orientation:') !== false) {
        for ($lineno = $line_num + 5; $lineno <= $count; $lineno++) {
            $line = $file_contents[$lineno];
            if (strpos($line, 'Rotational constants (GHZ):') != false) {
                break;
            }

            $line = preg_replace('/\s+/', ' ', $line);
            $split = explode(" ", $line);
            $symbol = $mapping[$split[2]];
            $x = $y = $z = '';

            if ($split[4] >= 0) {
                $x = ' ' . $split[4];
            } else {
                $x = $split[4];
            }
            if ($split[5] >= 0) {
                $y = ' ' . $split[5];
            } else {
                $y = $split[5];
            }
            if ($split[6] >= 0) {
                $z = ' ' . $split[6];
            } else {
                $z = $split[6];
            }

            $x = substr($x, 0, -3);
            $y = substr($y, 0, -3);
            $z = substr($z, 0, -3);
            $newlineno++;
            $newline = "ATOM\t" . $newlineno . "\t" . $x . "\t" . $y . "\t" . $z . "\t" . $symbol . "\n";

            fwrite($filehandle, $newline);
        }
    }
}


fclose($filehandle);

$lines = file($file2); 
$last = sizeof($lines) - 1 ; 
unset($lines[$last]); 

$fp = fopen($file2, 'w'); 
fwrite($fp, implode('', $lines)); 
fclose($fp); 

echo "File UPLOADED SUCESSFULLLy";

?>
<form method="POST" action="molecules.html"><br><br>
<p><input type="submit" name="structure" value="View file">

In molecule.html file contain code for displaying the content of molecule.txt file

But it is not overwriting the content of molecules.txt file.

Do I need anything more to add? Please help me.

Thanks in Advance.

Malay M
  • 1,659
  • 1
  • 14
  • 22
121kk
  • 51
  • 8

2 Answers2

0

instead of

$filehandle = fopen($file2, "a"); // this mode means append content 

use

$filehandle = fopen($file2, "w"); //this mode means write file by over writing the previous content
Sourabh Kumar Sharma
  • 2,864
  • 3
  • 25
  • 33
0
$filehandle = fopen($file2, "w+");

//w+ : Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

Reference: http://php.net/manual/en/function.fopen.php

Note - using fopen in 'w' mode will NOT update the modification time (filemtime) of a file like you may expect. You may want to issue a touch() after writing and closing the file which update its modification time. This may become critical in a caching situation.

I am suggesting two approach

Approach - 1 (File handling, simplest method; considering you're not doing any logical operation or string matching from the content, being read out)

molecules.html - Page containing form to upload file

<form method="POST" action="fileOverwrite.php"  method="post" enctype="multipart/form-data">
    <input type="file" name="file" size="50" />
    <br />
    <input type="submit" name="upload" value="Upload" />
</form>

fileOverwrite.php - File for overwriting logic/script

<?php
$file1      = $_FILES['file']['tmp_name'];
$out        = file_get_contents($file1);
$file2  = "molecule.txt";
$filehandle= fopen($file2, "w+") or die("Unable to open file!");
fwrite($filehandle, $out);
fclose($filehandle);
echo "File UPLOADED SUCESSFULLLY";
?>
<form method="POST" action="molecules.html">
    <br/ ><br />
    <input type="submit" name="structure" value="View file" />
</form>

Approach - 2 (matches your requirement, where you're doing some string search)

molecules.html - Page containing form to upload file

<form method="POST" action="test.php"  method="post" enctype="multipart/form-data">
    <input type="file" name="file" size="50" />
    <br />
    <input type="submit" name="upload" value="Upload" />
</form>

fileOverwrite.php - File for overwriting logic/script

<?php
// Capture the file's temp path and name
$file1  = $_FILES['file']['tmp_name'];

// Reads entire file into a string
$out    = file_get_contents( $file1 );

// Target file
$file2  = "molecule.txt";

// Open file for reading and writing
$filehandle = fopen( $file2, "w+" );

//Reads entire file into an array
$file_contents = file( $file1 );

$count = count( file( $file1 ) );

// Write a string to a file
file_put_contents( $file2, $file_contents );

$newlineno = 0;
foreach ($file_contents as $line_num => $line) {
    if (strpos($line, 'Standard orientation:') !== false) {
        for ($lineno = $line_num + 5; $lineno <= $count; $lineno++) {
            $line = $file_contents[$lineno];
            if (strpos($line, 'Rotational constants (GHZ):') != false) {
                break;
            }

            $line   = preg_replace( '/\s+/', ' ', $line );
            $split  = explode( " ", $line );
            $symbol = $mapping[$split[2]];
            $x = $y = $z = '';

            if ($split[4] >= 0) {
                $x = ' ' . $split[4];
            } else {
                $x = $split[4];
            }

            if ($split[5] >= 0) {
                $y = ' ' . $split[5];
            } else {
                $y = $split[5];
            }

            if ($split[6] >= 0) {
                $z = ' ' . $split[6];
            } else {
                $z = $split[6];
            }

            $x = substr($x, 0, -3);
            $y = substr($y, 0, -3);
            $z = substr($z, 0, -3);

            $newlineno++;
            $newline = "ATOM\t" . $newlineno . "\t" . $x . "\t" . $y . "\t" . $z . "\t" . $symbol . "\n";

            // Binary-safe file write
            fwrite($filehandle, $newline);
        }
    }
}

// Close open file pointer
fclose($filehandle);

$lines = file($file2); 
$last   = sizeof($lines) - 1; 
unset($lines[$last]);

$fp = fopen($file2, 'w+');
fwrite( $fp, implode( '', $lines ) );
fclose($fp);

echo "File UPLOADED SUCESSFULLLY";
?>

<form method="POST" action="molecules.html">
    <br/ ><br />
    <input type="submit" name="structure" value="View file" />
</form>
Swatantra Kumar
  • 1,324
  • 5
  • 24
  • 32
  • thanks for your response I have tried it.....But it doesnot updating content of molecule.txt file – 121kk Jul 13 '15 at 06:53
  • Do you want a) new content to be added at the end of existing content while keeping the old as it is or b) replace old content with new one removing old one – Swatantra Kumar Jul 13 '15 at 07:27
  • I've updated this with entire code which is short as well. You may try this. It fulfils option b. – Swatantra Kumar Jul 13 '15 at 09:23