Laurent Coulon
Laurent Coulon

Reputation: 109

Pass a filename as variable PHP

When I request this URL:

http://example.com/csv_build.php?filename=test.txt&time=1485902100000&data=25

I expect the PHP code to create a file named : datafile.txt that will contain the following data:

test.txt,1485902100000,25<CR><LF>

For some reason, datafile.txt is not created.

Did I made a mistake ?

 <?
 # GRAB THE VARIABLES FROM THE URL
 $File = 'datafile.txt';
 $FileName = $_GET['filename'];
 $HeureTronconMesure = $_GET['time'];
 $DonneeCapteur = $_GET['data'];
 # --------------------------------

 $FICHIER = fopen($File, "a");

 #ftruncate($FICHIER,0);

 fputs($FICHIER, $FileName);
 fputs($FICHIER , ",");
 fputs($FICHIER, $HeureTronconMesure);
 fputs($FICHIER , ",");
 fputs($FICHIER, $DonneeCapteur);
 fputs ($FICHIER , "\r\n");

 fclose($FICHIER);  
 ?>

Upvotes: 1

Views: 1976

Answers (1)

miken32
miken32

Reputation: 42719

You're not doing any error checking. Why do you assume everything will work okay? If you spot some errors, first thing I would check is file permissions.

<?php
 # GRAB THE VARIABLES FROM THE URL
 $File = str_replace("/", "_", $_GET["filename"]);
 $FileName = $_GET['filename'];
 $HeureTronconMesure = $_GET['time'];
 $DonneeCapteur = $_GET['data'];
 # --------------------------------

 if (!$FICHIER = fopen($File, "a")) {
     //there was an error opening the file, do something here
 }

 fputs($FICHIER, $FileName);
 fputs($FICHIER , ",");
 fputs($FICHIER, $HeureTronconMesure);
 fputs($FICHIER , ",");
 fputs($FICHIER, $DonneeCapteur);
 fputs ($FICHIER , "\r\n");

 fclose($FICHIER);  
 ?>

Though really, I'd simplify this code immensely by using some shortcuts and concatenating strings.

<?php
// replace any slashes in the filename with underscores
$file = str_replace(["/", "\\"], "_", $_GET["filename"]);

// build a string out of your data
$data = "$_GET[filename],$_GET[time],$_GET[data]\r\n";

// write the data to the file, checking if it returns false
if (!file_put_contents($file, $data)) {
    //there was an error writing the file, do something here
}

Note, never open your code with <?, it's been deprecated a very long time now. Use <?php.

Upvotes: 3

Related Questions