File handling via php

Tuesday `10 March 2022

What I want to do

The current goal is to be able to input something on the web page, save it to a file, and get it back.

  • An example of what I’d like to do is log my exercise over the course of the day, save it, and the be able to get it back during the day, and also, later on, as history.
  • It could also be nice to be able to update the quotations.text file directly from the web page, rather than editing it and uploading a new version.

…I looked into cookies, and it does not appear that they provide the functionality that I want; or, if they do, it seems like working with a regular txt file would provide more flexibility. In the long run, probably a database would be best, but I will save that for later.

So, more particularly, I want to

Open a file
Read one or more lines
One of the following
Display the contents of the file on the page & then alter it

Add a line to the file
delete a line from the file
Write the resulting data to the file, replacing the altered material

File Handling

I will begin by looking at the Robin Nixon book, p 147

<? php
$fh = fopen(“x_logfile.txt”, ‘w’) or die(“Failed to create text file.”);

$text = “This is one line of text…”;

//$text = <<<_END //programmatically add text to a file? Didn’t work.
// line 1
// line 2
// line 3
// _END;

fwrite($fh, $text) or die(“Could not write to file.”);
fclose($fh);
echo “File ‘x_logfile.txt’ written successfully.”;
?>

So far

  • This gives me fopen, fwrite, and fclose. fopen creates a file handle which subsequent file functions use. fopen can also take various arguments which put constraints on what may be done to the opened file (e.g., read only, write only, append only).
    • I tried a, and that works as advertised: it appends text to the end of the file without zeroing the existing file.
  • The “or die()” part in the first line is not obvious to me. Presumably if fopen() is true, then the second part is never evaluated and the program is terminated… that seems a bit sloppy to me.
  • The <<<_END bit of code did not work; when I commented it out and replaced it with just assigning a string to $text all was well — since the latter is more what I will need, I will not worry about <<<
  • There is also a function file_exists(“filename”) that returns a boolean
  • And there is a function fseek($filehandle, positions-to-move-pointer-back, location), where location SEEK_END is the end of the file.
  • And there are lots of other functions that I won’t need, or at least not yet: these include flock() for locking and unlocking files, and file_get_contents() for getting the entire content of a file

Grrr.

  • Forgetting a single semicolon can cause the entire program to fail (i.e. do nothing).
  • And using <? php rather than <?php can do the same
  • And putting \n outside double quotes can do the same
  • echo does not display newlines unless you first have the statement: echo “<pre>”;

VSC seems to offer the potential to validate php code, which might catch such errors, except that it wants me to tell it where the php executable is, and I don’t know that. There are all sorts of php files in the MAMP directory/subdirectories. Sigh.

OK, anyway, the php filehandling works. The next step is to figure out how to get input from the user via the web page. This will be complicated by the fact that to be secure we will want to validate that whatever is entered is not an attack…

Validating/Sanitizing Input

  • If you are uploading a file, then there are ways you can check to make sure that the file is one of a few expected types.
  • If you’ve got a string, you can do some things to ‘sanitize’ the input
    • $name = strtolower(preg_replace("[^A-Za-z0-9.]", "",$name));
    • This command creates a lowercase-only string containing alphanumeric characters or periods.

On to Forms

I think what I need to look at next is forms. Forms seem to be the way of getting user input from a web page. That makes sense, as it would control the nature of the input so security is less of an issue, except when the user is allowed to enter a text field.

<form action="/script-that-processes-form-entries.php">
  <label for="ID-of-the-input-field">First name:</label><br>
  <input type="type-of-the=input" id="ID-of-the-input-field" 
          name="variable-with-content-passed-to-script" 
          value="default-value"><br><br>
  <input type="submit" value="Submit">
</form> 

note that the value of “for” in the label must match the ID of an input

form takes three arguments:

  • action — typically a the location/name of a script that processes the form data
  • target (where the results of the action are displayed) — e.g., _self, or _blank
  • method, get or post. The former passes variables as part of a URL (non-secure, limited to 2048 characters, but good if the user is going to bookmark the result; the latter does something internal that keeps the submitted values invisible and has no length limits.
  • autocomplete (can be on or off, default is off)
  • novalidate (boolean; true if present — default is false)

Where I’m stopping

  • I have a prototype of a form for getting exercise data on the workspace page in MAMP
  • I am breaking the model a bit, because I want to be able to check multiple checkboxes for a single entry — but I don’t think this should be a problem with what I’m doing now.
  • In any event, I can see that the data is getting into the form, by using “get” to pass the parameters embedded into a URL
Kegel exercises (slow & fast): _ _ _ _ _ _

Walking (miles):_

Running (miles):_

Eccentric Heel Lifts: _ _ _ _ _ _

Where I’m stuck

  • I am trying to figure out how to gather or otherwise access the data entered into the form so that I can save it to the log file.
  • I found a bit of javascript the purports to read the form data into variables, but I can’t tell if it is working (that is here: https://discover.hubpages.com/technology/Retrieving-HTML-Form-Data-Using-JavaScritp)
  • The problem might be that I don’t understand the model of when an embedded java script runs, and so it is not running and I’m not seeing the results or it is running but I don’t know where to look for the results
  • Or the javascript just might not be working because the tutorial is wrong or I did something wrong… –

What Next

I should be able to find an example of getting input from a form, saving it, and then retrieving it to repopulat the form. Some pages to check out:

https://www.w3schools.com/php/php_form_complete.asp

https://www.ostraining.com/blog/coding/retrieve-html-form-data-with-php/

Views: 3

Tracking exercises, &c

Wednesday 2 March 2022

  • Found code to put a set of checkboxes into my workspace, so that I can flexibly keep track of exercises, etc.
  • Currently it does not save state between page refreshes: that seems like it ought to be doable with a database or cookie or something.
  • Next, once that is done, it would be nice to be able to have not just a check box, but also a textbook so that, for example, mileage could be put into an entry.
  • After that, it would also be nice to be able to view a history of activity — initially as a table, but then perhaps in some fancier ways.
  • Finally, it would be nice to be able to add (and delete) activities as they change — this would, of course, complicate creating a graphical display….

Views: 6