473,787 Members | 2,932 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Writing data to HTML file BEFORE the </body> tag.

Hello:
I have the following code in a PHP file. An HTML form passes user
comment data to the PHP, which then appends the user comments to the
end of the HTML file on which the form is located. This PHP code
works: the HTML file with added comments displays correctly in my
browser. However, appending text to the very end of the HTML file
creates what is, strictly speaking, invalid code.

I am looking for a way to tell PHP to write data to the file JUST
BEFORE the </bodytag. I have read about fseek(), but don't know for
sure if the number of characters (or HTML tags) after my "user
comments" section is going to remain constant.

Being extremely new to PHP, all I know is that I need to move the file
pointer backwards from the end of the HTML file until just before </
body>. I would appreciate any help in doing this.

<HTML>
<HEAD></HEAD>
<BODY>
<?
$name = $_POST['name'];
$website = $_POST['website'];
$message = $_POST['message'];
$timestamp = $_POST['timestamp'];
$fp = fopen(basename( $_SERVER[HTTP_REFERER]), 'a');
if (!$fp)
{
echo "There was an error. Please try again later.";
exit;
}
else
{
$outputstring = "<hr>" .$timestamp. "<br>" .$name. "<br>" .$message.
";
fwrite($fp, $outputstring, strlen($outputs tring));
fclose($fp);
echo "<BR>Commen t posted successfully.<B R>Click <a href='next'>her e</
Ato continue.";
}
?>
</BODY>
</HTML>
Aug 1 '08 #1
6 2547
Shawn wrote:
[...] which then appends the user comments to the end of the HTML file on
which the form is located.
Learn to use a database. I mean it: it'll save you sanity in the long run.

The PHP manual has some examples on SQLite. Even if you're new to PHP, I
strongly suggest you read them.
Cheers,
--
----------------------------------
Iván Sánchez Ortega -ivan-algarroba-sanchezortega-punto-es-

Cambio mujer de 40 por dos de 20.
Aug 1 '08 #2
..oO(Shawn)
>I have the following code in a PHP file. An HTML form passes user
comment data to the PHP, which then appends the user comments to the
end of the HTML file on which the form is located. This PHP code
works: the HTML file with added comments displays correctly in my
browser. However, appending text to the very end of the HTML file
creates what is, strictly speaking, invalid code.

I am looking for a way to tell PHP to write data to the file JUST
BEFORE the </bodytag. I have read about fseek(), but don't know for
sure if the number of characters (or HTML tags) after my "user
comments" section is going to remain constant.
You want to insert data into the middle of a file. This means you have
to recreate the entire file. Usually you would read it into memory,
write all of its data to a new empty file until you reach the insert
position, then write the new data, then the rest of the original file.
After that you replace the old file with the new one.

You could do this with file() and looping through the resulting array
until you reach the "</body>" line. Another way would be to load the
entire file with file_get_conten ts() into a string. Then use string
functions to prepend "</body>" with your new content, finally use
file_put_conten ts() to write it all back to disk.

But there are a lot of other problems:
><HTML>
<HEAD></HEAD>
This code is invalid anyway. There's no document type declaration and
the 'title' element is missing.
><BODY>
<?
Don't use short open tags. They are unreliable and will be turned off by
default in the coming PHP 6. Use the correct <?php instead.
>$name = $_POST['name'];
$website = $_POST['website'];
$message = $_POST['message'];
$timestamp = $_POST['timestamp'];
No error checking that these $_POST values really exist?
>$fp = fopen(basename( $_SERVER[HTTP_REFERER]), 'a');
Holy sh*t... The HTTP referrer is not only totally unreliable, but also
easy to fake. This opens a _huge_ security hole here - an attacker could
easily manipulate _any_ file your web server is allowed to write to and
inject arbitrary code!

Have a look at the various predefined values in $_SERVER instead, the
elements 'SCRIPT_NAME' or 'PHP_SELF' could be of interest.
>if (!$fp)
{
echo "There was an error. Please try again later.";
exit;
The exit call here will prevent the script from returning a complete
HTML document to the browser. In case of an error you should just stop
or skip the further file processing, but not kill the entire script.
>}
else
{
$outputstrin g = "<hr>" .$timestamp. "<br>" .$name. "<br>" .$message.
";
You should also have a look at htmlspecialchar s(). Your code allows a
user to insert arbitrary markup, which means that your page can be
abused for cross-site scripting attacks (XSS). Even worse: it also
allows easy code injection - the most severe of all security problems.

My suggestion: Drop the idea of a self-modifying script - this calls for
a lot of _serious_ trouble! Instead write the posted messages to another
file (plain text or CSV for example) or to a database. Then use a little
load function to show these messages on your page.

Micha
Aug 1 '08 #3
Michael Fesser wrote:

[...]
But there are a lot of other problems:
You also forgot about race conditions.

I did some hack some years ago, involving a script appending data to a text
file, and I can assure you that, given enough time and load, things will
invariably f**k up.

That's why atomic operations on a database are so cool: they save you from
lots of potential problems when it comes to concurrent programming
languages.
Cheers,
--
----------------------------------
Iván Sánchez Ortega -ivan-algarroba-sanchezortega-punto-es-

Now listening to: Kb - Destination Lounge: New York City (2007) - [10] El
Musica (main mix) (6:52) (0.000000%)
Aug 1 '08 #4
..oO(Iván Sánchez Ortega)
>Michael Fesser wrote:

[...]
>But there are a lot of other problems:

You also forgot about race conditions.
Indeed.

<excuse mode="blockbust er">
The OP will already be held responsible if attackers take over his
server and abuse it for spreading a virus, which will infect the entire
network, overload every connected system and finally blow up the whole
planet. So I just didn't want to scare him too much. ;-)
</excuse>
>I did some hack some years ago, involving a script appending data to a text
file, and I can assure you that, given enough time and load, things will
invariably f**k up.
You can prevent this with file locking. Might cause other problems,
though. A system which is explicitly designed for parallel accesses
like a DBMS for example is definitely the better choice in such cases.
>That's why atomic operations on a database are so cool: they save you from
lots of potential problems when it comes to concurrent programming
languages.
Yep.

Micha
Aug 1 '08 #5
Thanks, guys, for all of the feedback. In the revised code (see
below), I have done the following:

*Added a <!DOCTYPEassign ment tag.
*Replaced the PHP short open tag w/ the longer one.
*Added if/else statements for basic form validation (additional
validation will be done from the referring form using javascript).
*Used trim() and htmlspecialchar s() to eliminate blank space and
prevent website exploitation via cross-site scripting attacks.
*Removed exit calls that would cause termination of script before
required HTML end tags.

Yes, I am aware that I have used deprecated elements in the <hrtag.

Now let's say that I, as suggested, abandon the idea of using fwrite()
to append the user comments to the end of the referring HTML document.
Let's say that I want to put the comments in a database, instead. How
would that be coded? What steps would I need to take?

It may help to know that my host server allows me several MySQL
databases, although I don't know SQL. It may also help to know that I
will eventually have many pages that need to store comments. Is one
database sufficient for this?

Thanks, again.

-------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://
www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>

<BODY>
<?php
$name = htmlspecialchar s(trim($_POST['name']), ENT_QUOTES);
$website = trim($_POST['website']);
$message = htmlspecialchar s(trim($_POST['message']), ENT_QUOTES);
$timestamp = htmlspecialchar s(trim($_POST['timestamp']), ENT_QUOTES);

// Rem: empty() can only be used on a variable, not on the results of
a function.
if (empty($message )) {
echo "<p>Error: a blank comment cannot be submitted.</p>";
}
else {
if (empty($name)) {
echo "<p>Error: comments cannot be submitted
without a name.</p>";
}

else {
$fp = fopen(basename( $_SERVER[HTTP_REFERER]), 'a');
if (!$fp) {
echo "<p>There was an error. Please try again
later.</p>";
}
else {
$outputstring = "<div style='color: darkgray; text-align:
left'><hr noshade width='50%' align='left'><s mall>" .$timestamp.

"</small><br><B>Na me:</b<a href='" .$website. "'>" .$name. "</
a><br><b>Commen t:</b" .$message. "<br></div>";
fwrite($fp, $outputstring, strlen($outputs tring));
fclose($fp);
echo "<p>Your comment was posted successfully.<b r>Click <a
href='javascrip t:history.back( )'>here</ato continue.</p>";
}
}
}
?>
</BODY>
</HTML>
Aug 1 '08 #6
Shawn wrote:
Thanks, guys, for all of the feedback. In the revised code (see
below), I have done the following:

*Added a <!DOCTYPEassign ment tag.
*Replaced the PHP short open tag w/ the longer one.
*Added if/else statements for basic form validation (additional
validation will be done from the referring form using javascript).
*Used trim() and htmlspecialchar s() to eliminate blank space and
prevent website exploitation via cross-site scripting attacks.
*Removed exit calls that would cause termination of script before
required HTML end tags.

Yes, I am aware that I have used deprecated elements in the <hrtag.

Now let's say that I, as suggested, abandon the idea of using fwrite()
to append the user comments to the end of the referring HTML document.
Let's say that I want to put the comments in a database, instead. How
would that be coded? What steps would I need to take?

It may help to know that my host server allows me several MySQL
databases, although I don't know SQL. It may also help to know that I
will eventually have many pages that need to store comments. Is one
database sufficient for this?

Thanks, again.

-------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://
www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>

<BODY>
<?php
$name = htmlspecialchar s(trim($_POST['name']), ENT_QUOTES);
$website = trim($_POST['website']);
$message = htmlspecialchar s(trim($_POST['message']), ENT_QUOTES);
$timestamp = htmlspecialchar s(trim($_POST['timestamp']), ENT_QUOTES);

// Rem: empty() can only be used on a variable, not on the results of
a function.
if (empty($message )) {
echo "<p>Error: a blank comment cannot be submitted.</p>";
}
else {
if (empty($name)) {
echo "<p>Error: comments cannot be submitted
without a name.</p>";
}

else {
$fp = fopen(basename( $_SERVER[HTTP_REFERER]), 'a');
if (!$fp) {
echo "<p>There was an error. Please try again
later.</p>";
}
else {
$outputstring = "<div style='color: darkgray; text-align:
left'><hr noshade width='50%' align='left'><s mall>" .$timestamp.

"</small><br><B>Na me:</b<a href='" .$website. "'>" .$name. "</
a><br><b>Commen t:</b" .$message. "<br></div>";
fwrite($fp, $outputstring, strlen($outputs tring));
fclose($fp);
echo "<p>Your comment was posted successfully.<b r>Click <a
href='javascrip t:history.back( )'>here</ato continue.</p>";
}
}
}
?>
</BODY>
</HTML>
For MySQL questions, try comp.databases. mysql. You'll need to learn SQL
syntax (which isn't that hard for the easy stuff, but can be very
powerful). And even if you don't use it on this project, SQL is a very
good thing to know.

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
Aug 1 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2144
by: Gordon - Adelphia | last post by:
I have a question regarding xhtml. Why, why, why does the ELEMENT <body> allow “unblocked” text. HTML does not (though, most browsers will render). Xhtml (transitional) however allows text nodes (PCDATA). All of HTML 4, xhtml – transitional, and xhtml-strict allow <div> to contain “unblocked” text. Does anybody know why – I’m looking for the philosophy behind allowing such. I’m in the process of encapsulating xhtml mark-up in content...
7
5559
by: Ignac Vucko | last post by:
Is writing a document *during* page load safe and supported for all 4th and 5th generation browsers? If not, can you show me a specific example/browser where it causes problems? <html> <head> <script>document.writeln("<div id='mydiv'>stuff</div>");</script> </head> <body>blah</body>
15
2252
by: Frances | last post by:
<html> <head> <script> function doIt() { var list = document.forms.product; var selItem = list.options.value; ^^^^^^^ </head>
5
11043
by: Rick Spiewak | last post by:
I need to generate a "buy" button as part of an ASP.NET page - this consists of a small HTML form with hidden fields, conforming to the requirements of a merchant credit card processor. PayPal is similar. I'm succeeding in doing this by using Writer.Write to emit my HTML, at least as far as getting it to work. However, depending on where I put MyBase.Render(Writer), I get my HTML either before the header or after the end of the body of...
7
3632
by: pamelafluente | last post by:
The precious input given by Laurent, Martin, Benjamin about XMLHttpRequest in Javascript, has made me think that perhaps I could improve what I am currently doing by using Ajax. Let's make it simple and schematic, to see if there is a simple Ajax answer to this. A. I have an HTML page which has some pure html/css code representing a GRID of cell. The page may also contain other objects (images, etc). B. On the server I have a windows...
1
1791
by: davidemazza82 | last post by:
Hi all, I got an from IE 7.0.5730.11 when moving the <script src="..." type="text/javascript" /tag from the <headpart to the <bodysection of a HTML file. Is not possibile to include Javascript code via <script src="..." type="text/javascript" /from the <bodysection, instead from the <headone? If yes, anyone has any idea of which the problem could be? If not, how can I programmatically include a javascript external file
8
2260
by: Prisoner at War | last post by:
Another weekend, another project, another problem.... Why should a perfectly fine function work only half-way through when called through onClick in an anchor tag?? The text fade-in script below works when called through onLoad in the <bodytag, but it "hangs" when called through onClick in <a href="#">, as follows: <script language="JavaScript1.2">
23
2242
by: Xah | last post by:
Here's a interesting case of invalid html 4 strict file. In summary, if you have <body></bodywithout any content, the file would be invalid under html 4 strict. Valid if html 4 lose. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/ TR/html4/strict.dtd"> <html> <head> <META HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=utf-8">
3
5754
by: PYG | last post by:
Hi everybody I have a simple question : If i use this code : <body style="font-size:24px;color:blue;"> Text in body <table> <tr><td> Text in table
0
9497
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.