Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: appending to html at beginning

by haukex (Abbot)
on Feb 03, 2017 at 08:13 UTC ( #1180936=note: print w/replies, xml ) Need Help??

in reply to appending to html at beginning

Hi Limbomusic,

It appears you have found some very old example code - the code you are using to get the form parameters is outdated, and your script isn't doing use warnings; use strict; at the top (see Use strict and warnings).

If you are just learning Perl / CGI scripting, there are several modern web frameworks nowadays, whose use I'd strongly recommend. For example, a good starting point is Mojolicious::Guides::Tutorial. The "old" CGI module, which is the way a script like the one you've shown would handle form parameters, is no longer recommended for new developments.

Anyway, moving on to your question: Your open is using a mode of '>>', which is "append mode", that's why anything you write to the filehandle $fh is being inserted at the end of the file. If you wanted to insert lines at the top of a file, there are several ways to do so. However, simply inserting lines at the top of the file will break the HTML, so instead you'd need to insert the lines at the correct place instead. One way to do this would be to insert a marker comment at the proper place in the file, like <!-- INSERT HERE -->, and then one relatively easy way to insert lines in the middle of a file is Tie::File (see also the documentation of splice).

#!/usr/bin/env perl use warnings; use strict; my $filename = 'test.html'; my @to_insert = ( '<p>Hello,', 'World! It is '.gmtime(time).' UTC</p>' ); use Tie::File; tie my @lines, 'Tie::File', $filename or die "tie $filename: $!"; my $found; for (my $i=0; defined($lines[$i]); $i++) { if ($lines[$i]=~/<!--\s*INSERT\s+HERE\s*-->/i) { $found=1; splice @lines, $i+1, 0, @to_insert; last; } } die "Marker not found" unless $found; untie @lines;

Update: Code now inserts current time to make the order of updates to the file more clear.

Note that there are more "modern" ways to accomplish this instead of editing an HTML file. For example, you could store new "stories" in a file or a database on the server, and then when someone wants to see the list of stories, build the HTML page to display them dynamically. This has the advantages that you could allow for the user to select a range of stories, easily change the display format, etc. Even more advanced and "modern" techniques would be to provide the "stories" in JSON format, and then have JavaScript in the browser dynamically retrieve and display them. However, if you are just getting started, then the above is a good first step before going into these advanced techniques.

Hope this helps,
-- Hauke D

Replies are listed 'Best First'.
Re^2: appending to html at beginning
by Limbomusic (Initiate) on Feb 03, 2017 at 08:58 UTC
    Thanx for lightning fast replies :-) Sadly I am not "mentally equipped" yet - to fully understand how to implement your suggestions, and yes, old code - If I just put
    use warnings;
    use strict;
    I get 500 internal server error - because I guess the code isnt totally "right" ?
    I do have tho - a working guestbook (which I found at Matt Wrights website) - and there the entries gets sorted last first - he has some code:
    # Open Link File to Output open (GUEST,">$guestbookreal") || die "Can't Open $guestbookreal: $!\n +"; for ($i=0;$i<=$SIZE;$i++) { $_=$LINES[$i]; if (/<!--begin-->/) { if ($entry_order eq '1') { print GUEST "<!--begin-->\n"; } if ($line_breaks == 1) { $FORM{'comments'} =~ s/\cM\n/<br>\n/g; } print GUEST "<b>$FORM{'comments'}</b><br>\n";
    which I guess has something to do with it - but dont know how to implement it.
    I,ll keep investigating and gonna fiddle with your suggestions, but for now, I think I,m just gonna find some html which sends the user to the bottom of the page.
    Thank you SO much for your input guys.
    Kind regards

    P.S - "Madlibs" I guess is the english word - in norwegian - we call it an "adjective story".

      I do have tho - a working guestbook (which I found at Matt Wrights website)

      Do be very, very careful with that. There has been plenty of discussion about that collection of scripts over the years and almost all of the recent comments have been uncomplimentary. The scripts are very old and at least some are very insecure. See the summary at the NMS project for some background and how to obtain better versions of those scripts.

      The monks here can help you with your perl questions but if you are going to try to patch some of Matt's old code often the better strategy would be to start again from scratch with the benefit of a modern approach and security as a primary principle.

      Addendum: For the benefit of non-English speakers, there is a word in English which means "appending to the beginning" and it is prepending. Appending is reserved for adding to the end only.

      Hi Limbomusic,

      I get 500 internal server error - because I guess the code isnt totally "right" ?

      Yes, as described in Use strict and warnings, one of the first things that will happen is that you get errors because you need to declare your variables at or before their first use, for example my $navn = $FORM{navn};. The best way to debug this is by running the script from the command line and looking at the errors you get there. If you're just looking for compilation errors like undeclared variables, you can also run perl -c

      Once you've got the script working locally, if you have trouble on the server, see CGI Help Guide and Troubleshooting Perl CGI scripts.

      a working guestbook

      Please be very careful with code you find like this - what you've shown has a security hole! The problem is print GUEST "<b>$FORM{'comments'}</b><br>\n"; - this allows the visitor to insert any arbitrary HTML code into the page, including JavaScript, which has the potential to seriously mess with the user. This is known as a Cross-site scripting (XSS) attack, for a tutorial see for example this.

      Sorry, but based on the code I have to recommend removing that script from your site, or at least temporarily disabling it. Note: As I was writing this, hippo posted a reply pointing you to a better alternative.

      Hope this helps,
      -- Hauke D

      I get 500 internal server error - because I guess the code isnt totally "right" ?

      yes you cannot put use strict; use warnings; bare statements without modifying your code. You need to declare all variables you use using my like in my $var = "foo";

      Blindly develop on webserver is, in my experience, a frustrting operation: everything you get wrong you got a 500 error.

      if you want to learn about Modern Perl Web you can start with and it's module Dancer2 it is pretty easy to use.


      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

        Hi Discipulus,

        Blindly develop on webserver is, in my experience, a frustrting operation: everything you get wrong you got a 500 error.

        use CGI::Carp qw/fatalsToBrowser/; can help with that. Although I would only recommend it in a development, not production, environment, since it can potentially reveal details about the script or server to an attacker.

        -- Hauke D

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1180936]
[Corion]: It's close to my Perl script where you paste in the SQL and get the result as XLSX file, but I guess the Excel sheet is more user-friendly :)
[choroba]: What drivers does it support? ;-)
[erix]: sounds cool -- but now you have to give SQL lessons?

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2018-07-18 13:07 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (392 votes). Check out past polls.