Closed Thread Icon

Topic awaiting preservation: Writing to an html file with php. Pages that link to <a href="https://ozoneasylum.com/backlink?for=13058" title="Pages that link to Topic awaiting preservation: Writing to an html file with php." rel="nofollow" >Topic awaiting preservation: Writing to an html file with php.\

 
Author Thread
Rinswind 2th
Maniac (V) Inmate

From: Den Haag: The Royal Residence
Insane since: Jul 2000

posted posted 02-15-2004 14:46

Ok i do have a bookmark file online so i could always find my bookmarks. On whatever computer i am whereever in the world. Now i am looking for a way to update the page online. So i actualy am working on a form which a link to the html file and put the link in the right category on the page. So the next time i come to the page (from a different machine) the link is there. But i don't know much about php or perl so i would not know where to start.
Basicly i want to make a serverside script which does the following.
1) show a form
2) get data from form
3) ad data to file
4) save file.

If possible i try to avoid using an MySQL database because i only can have one and i want that for other experiments. So it should work with a flat file.


__________________________________________
finally: www.rinswind.nl

WarMage
Maniac (V) Mad Scientist

From: Rochester, New York, USA
Insane since: May 2000

posted posted 02-15-2004 15:41

Your a bit confusing in your explaination of your problem. What you want to do seems like a trivial exercise using any scripting language. Check out the PHP documentation site, and look for file input and output. It shouldn't be too hard.

-Dan-

Rinswind 2th
Maniac (V) Inmate

From: Den Haag: The Royal Residence
Insane since: Jul 2000

posted posted 02-15-2004 16:50

Well it's the first time i took a closer look at php, and i did find a ton of info and stuff but i was not shure what to look for. Now i could narrow it down.....thanks.

__________________________________________
finally: www.rinswind.nl

smonkey
Paranoid (IV) Inmate

From: Northumberland, England
Insane since: Apr 2003

posted posted 02-15-2004 17:23

wise man say remember that in one mysql database you can have many tables....

<A HREF="http://www.cryokinesis.co.uk" TARGET=_blank>visit

Rinswind 2th
Maniac (V) Inmate

From: Den Haag: The Royal Residence
Insane since: Jul 2000

posted posted 02-15-2004 23:54

After some reading i pieced something together and i use three files to do so.
First there is the Form which should send it's input to the php-file which on it's turn should add it to the end of the bookmark-file. Probably i made a stupid mistake since i got this error when i was testing.

quote:
Parse error: parse error in /home/rinswind/public_html/write2file.php on line 8


I go to bed now an will look at it again tomorrow in the meantime if someone could shine a little light on the error it would be appreciated.


__________________________________________
finally: www.rinswind.nl

[This message has been edited by Rinswind 2th (edited 02-15-2004).]

Skaarjj
Maniac (V) Mad Scientist

From: :morF
Insane since: May 2000

posted posted 02-16-2004 01:28

You'll need to zip up that PHP file if you want us to be able to check your code for you. We can't view the source of a server side script from the client side unless it's in some format that the webserver won't parse before sending it out, like a zip or rar archive. Or you could just post lines 5-8 here, and we'll see what we can see.

Usually though, a parse error of that type is becuase you've missed a ; on a previous line. Remember; every line of that file, except for comments, declarations of loops or choice statements or a line that only contains { or } needs to have a semi-colon at the end.

Rinswind 2th
Maniac (V) Inmate

From: Den Haag: The Royal Residence
Insane since: Jul 2000

posted posted 02-16-2004 07:32

ok the code from the php file:

code:
<html>
<head>
<title>write to file</title>
</head>
<body>

<? php
$string1 = $_POST['name'];
$string2 = $_POST['url'];
$string3 = $_POST['description'];
$outputstring = $string1.$string2.$string3;
$file = fopen("bookmarks.html", "r+");
fwrite($file, $outputstring);
fclose($file);?>
</body>
</html>



__________________________________________
finally: www.rinswind.nl

DmS
Paranoid (IV) Inmate

From: Sthlm, Sweden
Insane since: Oct 2000

posted posted 02-16-2004 10:06

is there a space between <? and php? here "<? php" If so, lose the space for starters.
/Dan

{cell 260}
-{ a vibration is a movement that doesn't know which way to go }-

Tyberius Prime
Paranoid (IV) Mad Scientist with Finglongers

From: Germany
Insane since: Sep 2001

posted posted 02-16-2004 10:41

yeah, loosing the space will fix the parsing error. (just tried, my editor has a built in php syntax checker...).

On a side note, you should probably check if the form was actually posted, before writing empty stuff to the file.
You'd use if (isset($_POST['name'])) for that.

So long,

Tyberius Prime

poi
Paranoid (IV) Inmate

From: France
Insane since: Jun 2002

posted posted 02-16-2004 10:53

Rinswind 2th: What DmS and Tyberius Prime said is true.
One thing you must know is that the HTML file you generate will be invalid and have no A tags.
I also think you should open the file in 'a' ( Append ) mode rather than 'r+'

You should probably create a RAW text file. To view your bookmarks you, use a PHP page that will include and format correctly the RAW text file. It should give something like:

write2rawfile.php

code:
<?
$string1 = $_POST[ 'name' ];
$string2 = $_POST[ 'url' ];
$string3 = $_POST[ 'description' ];
$outputstring = $string1 ."\n". $string2."\n". $string3 ."\n";
$file = fopen( "bookmarks.txt", "a" );
fwrite( $file, $outputstring );
fclose( $file );
header( "Location: view_bookmarks.php" );

?>



view_bookmarks.php

code:
<html>
<body>
<h1>My bookmarks:</h1>
<dl>
<?

$file = fopen( "bookmarks.txt", "a" );
while( !feof( $file ) )
{
$name = fgets( $file );
$url = fgets( $file );
$desc = fgets( $file );

echo "\n\t<dt><a href='$url'>". htmlentities( $name ) ."</dt>\n\t<dd>". htmlentities( $desc ) ."</dd>";
}
fclose( $file );

?>
</dl>
</body>
</html>



Hope that helps



[This message has been edited by poi (edited 02-16-2004).]

Rinswind 2th
Maniac (V) Inmate

From: Den Haag: The Royal Residence
Insane since: Jul 2000

posted posted 02-16-2004 11:44

Thanks guys you are so helpfull
I got my self a copy of the php manual, (sometimes it's handy to work at a print shop ) this is very interesting stuff.

TP: wher should that if statement go? in the form file or ini the write2 file?

__________________________________________
finally: www.rinswind.nl

[This message has been edited by Rinswind 2th (edited 02-16-2004).]

Tyberius Prime
Paranoid (IV) Mad Scientist with Finglongers

From: Germany
Insane since: Sep 2001

posted posted 02-16-2004 15:45

in the write file, of course. You only want to write if you received a form.

Rinswind 2th
Maniac (V) Inmate

From: Den Haag: The Royal Residence
Insane since: Jul 2000

posted posted 02-16-2004 20:53

Off course...
I found the parse error (the space). However when i add :

header( "Location: view_bookmarks.php" ); to my own write2file.php or when i try poi's write2rawfile.php
i get another error:
Warning: Cannot modify header information - headers already sent by (output started at /home/rinswind/public_html/write2file.php:7) in /home/rinswind/public_html/write2file.php on line 15

When i leave the rule out the info got written to the bookmark.txt file. And when i open the bookmarks.txt file my texts are there.


BTW Poi what does :
while( !feof( $file ) ) do?



__________________________________________
finally: www.rinswind.nl

DmS
Paranoid (IV) Inmate

From: Sthlm, Sweden
Insane since: Oct 2000

posted posted 02-16-2004 21:29

"Cannot modify header..." is an error that comes if you output anything ti the screen before you try to modify the headers, as in this line "header( "Location: view_bookmarks.php" );" Make sure you don't print anything to the screen before that line.

2.
while( !feof( $file ) )

This is a while loop that will run "while the end of $file has not been reached.

! is a negator (not sure of the naming), what it does in this case is to say that the statement is valid if the function does NOT return true...
Crystal clear, right
Since feof returns true as the end of the file has been reached and false if it hasn't been reached this will work. This "while (feof($file) == false)" should also work, they are equal as far as I know.

feof() manual: http://se.php.net/manual/en/function.feof.php
$file is the handle of the actual file

/Dan

{cell 260}
-{ a vibration is a movement that doesn't know which way to go }-

Tyberius Prime
Paranoid (IV) Mad Scientist with Finglongers

From: Germany
Insane since: Sep 2001

posted posted 02-16-2004 22:33

argh!
Doing a while (!feof($filehandle)) without checking the file handle first - you just created an endless loop, since feof doesn't return true if $filehandle isn't a valid filehandle...

so you'd do
[code]
$filehandle = fopen...
if ($filehandle)
{
while ( ! feof($filehandle) )
{
...
}
}

poi
Paranoid (IV) Inmate

From: France
Insane since: Jun 2002

posted posted 02-16-2004 22:53

Sorry guys for including the error tests. I've written that piece of code directly in the Asylum. Anyway if I had done all the job it wouldn't be that funny

Rinswind 2th: Personnaly I prefer to use the PDF or CHM or online versions of the PHP manual rather than a printed version 'coz it saves some space on my desk and the search features in the digital versions are far faster than me. I remember when I printed the ~700 pages references of JavaScript. It took ages and was literaly unsuable.

Rinswind 2th
Maniac (V) Inmate

From: Den Haag: The Royal Residence
Insane since: Jul 2000

posted posted 02-17-2004 00:05

Hehehe with you guys as teachers i keep smiling and learning.

Poi i think the error was very good to learn, now i will not forget what it was. I agree about the searching is better with the online tools, but i cannot carry a .pdf around. And i like paper to scribble in the margins.
These days i carry around one or two binders with me in my backpack. When i have a spare moment (on the train, waiting for the bus) i get my binder and start reading. Then when i come home i start trying things and start searching and asking. This is how i learn and how i will become *cough* the best programmer in the world onde day *cough*)

__________________________________________
finally: www.rinswind.nl

[This message has been edited by Rinswind 2th (edited 02-17-2004).]

norm
Paranoid (IV) Inmate

From: [s]underwater[/s] under-snow in Juneau
Insane since: Sep 2002

posted posted 02-18-2004 01:59

Rinswind 2th:

'The Best Programmer In the World' is the programmer who's code just did exactly what they wanted it to do...

I like this definition because it allows each of us to occasionally lay claim to the title, even if it's only for a moment or two.


/* Sure, go ahead and code in your fancy IDE. Just remember: it's all fun and games until someone puts an $i out */

Tyberius Prime
Paranoid (IV) Mad Scientist with Finglongers

From: Germany
Insane since: Sep 2001

posted posted 02-18-2004 10:45

<sarcasm>good luck. you'll be moved to managment immediatly after reaching that goal</sarcasm>

smonkey
Paranoid (IV) Inmate

From: Northumberland, England
Insane since: Apr 2003

posted posted 02-18-2004 16:09

it may be sad, but it's like norm said.

when you hard code a large section of code and then test it and it works with no bugs no error messages no glitches nothing - that is amongst the best feelings in the world - it is the feeling of doing something right, as right as right can be - that is when you are the best programmer. There is not one programmer alive that claim 100% success rate with code, even simple stuff - human error or 'computer blip' always creeps in except for in the rarest of occasions.

<A HREF="http://www.cryokinesis.co.uk" TARGET=_blank>visit

Rinswind 2th
Maniac (V) Inmate

From: Den Haag: The Royal Residence
Insane since: Jul 2000

posted posted 02-19-2004 00:11

Well i guess it's no managment function for me right now.
The first script is working fine after a bit of tuning:

write2file.php

code:
<html>
<head>
<title>write to file</title>
<link href="basic-style.css" rel="stylesheet" type="text/css">
</head>
<body>

<?php
if (isset($_POST['name'])) //if Post-data is found
{$string1= $_POST['name']; //string1 gets value from form-id name
$string2= $_POST['url']; //string2 gets value from form-id url
$string3= $_POST['description']; //strings3 gets value from form-id description
$outputstring = $string1."\n".$string2."\n".$string3."\n"; //outputstring is formed
$file = fopen("bookmarks.txt", "a"); //open bookmarks.txt and add
//header("location: viewbookmarks.php");} //channel output to viewbookmarks.php
fwrite($file, $outputstring); //write file // behind header to test parsing error
fclose($file); //close file
echo"your bookmark has been added";}
//else //commented out to ceck for parsing error
// { echo "You did not fill in the form correct press the back button to try again"}; //warn people about not filled in form.
?>
</body>
</html>



But the script which should show the bookmarks is still giving me some parsing errors but i think they should wait until tomorrow.

viewbookmarks.php

code:
<html>
<head>
<title>My bookmarks</title>
<link href="basic-style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h2>My bookmarks</h2>
<dl>
<?php
$file=fopen("bookmarks.txt","a"); //open and add to file
if ($file){ //if file is loaded
while (!feof($file)){ //while end of file is not true
$name = fgets($file); //read name-variable from file
$url = fgets($file); //read url-varable from file
$description = fgets($file); // read description variable
echo "\n\t"<dt><a href ='$url'>".htmlentities($name)."<dt>\n\t<dd>".htmlentities($descritption)."</dd>";}
fclose($file);
?>
</dl>
</body>
</html>



To try it yourself
www.rinswind.nl/bookmark-form.htm
www.rinswind.nl/bookmarks.txt

<edit>Could i be that the file viewbookmarks.php is not closed? so i keep getting errors like this:
Warning: Cannot modify header information - headers already sent by (output started at /home/rinswind/public_html/write2file.php:8) in /home/rinswind/public_html/write2file.php on line 16
But as far as i see the header or any other out put is not send two times....</edit>
__________________________________________
finally: www.rinswind.nl

[This message has been edited by Rinswind 2th (edited 02-19-2004).]

poi
Paranoid (IV) Inmate

From: France
Insane since: Jun 2002

posted posted 02-19-2004 03:05

1. The "header already sent" error is absolutely normal since you've sent the <html><body> ... tag soup before the header( "Location: ...... "); instruction. You must send nothing to the client before a header( ); instruction. If you want to output the errors or a confirmation message, do it once you are sure you don't need a redirection, or redirect to a script and send some infos in the URL ( i.e. header( "Location: viewbookmarks.php?bookmarkAddedCorrectly=true" ); or header( "Location: insertbookmarks.php?error=wrong_name" ); )

[edit]

To clarify a little the header thing. You must realize that once something is sent to the client ( be it via PHP or simple HTML ), the HTTP headers are sent and thus can not be modified. So if you want/have to alter the HTTP headers in a PHP script, make sure that there's no remaining HTML before you script and that you output nothing before you touch the HTTP headers.

[/edit]

2. woops, my fault, in viewbookmarks.php the bookmarks.txt is open in Append mode, and thus you'll have a hard time if you try to get something from it, thus replace:

$file=fopen("bookmarks.txt","a");

by

$file=fopen("bookmarks.txt","r");

Oh, and when dealing with forms it's highly advised to test every datas sent by the client. Imagine you forgot the URL or the DESCRIPTION.



[This message has been edited by poi (edited 02-19-2004).]

Taobaybee
Maniac (V) Inmate

From: The Pool Of Life
Insane since: Feb 2003

posted posted 02-19-2004 08:28

I find all this most interesting, even though I know nothing. I thinking of learning.
btw I got this.
"Parse error: parse error in /home/rinswind/public_html/write2file.php on line 14"
::tao::

poi
Paranoid (IV) Inmate

From: France
Insane since: Jun 2002

posted posted 02-19-2004 09:20

In viewbookmarks.php , you forgot to close the brace enclosing the block of statements following the if ($file){ , you must put the } right after the fclose( $file );

Rinswind 2th
Maniac (V) Inmate

From: Den Haag: The Royal Residence
Insane since: Jul 2000

posted posted 02-20-2004 00:36

Finally this works as a charm.
The comment was clogging it a bit up. So i could not see what's happening. Maybe i should get PHP-syntax checking in my editor....

TAO: until last week i thought php was som sort of magic to grow pumpkins with, but after this 'little' experiment i learned a lot and ended up with a working script. So you could do it to

Thanks to everybody who helped with this.
Final version Now try to leave a favourite site i should know about...

Future improvements i think about.
1) opening the bookmark-form in a small window as sort of popup.
2) some way to put the links in categories.
3) preventing the bookmark-form to be seen by anyone but me.

But that would be another story i guess.
__________________________________________
finally: www.rinswind.nl

[This message has been edited by Rinswind 2th (edited 02-20-2004).]

[This message has been edited by Rinswind 2th (edited 02-20-2004).]

Tyberius Prime
Paranoid (IV) Mad Scientist with Finglongers

From: Germany
Insane since: Sep 2001

posted posted 02-20-2004 10:54

you know... my editor is open-source, but currently only available on request.
It is nifty for php coding, though not good for much else ;-).

poi
Paranoid (IV) Inmate

From: France
Insane since: Jun 2002

posted posted 02-20-2004 11:15

I thought it was a little too early to talk about that method, but one thing I like in PHP ( when creating some sorts of CACHEs or what not ) is to generate some PHP code.

Instead of creating bookmarks.txt, why not creating bookmarks.inc.php. Indeed, once you've made sure the datas you handle are safe, you can append some PHP statements to a file you'll include later. Thus, the write2file.php script become ( notice that I only give the writing part and omit the error safe guards ) :

code:
<?

/*
* make sure the datas are safe here
*/

$fileName = "bookmarks.inc.php";

// initialize the outputString
if( !file_exists( $fileName ) )
$outputString = '<'.'? $bookmarksArray=array(); ?' .">\n";
else
$outputString = '';

// add the new entry in the outputString
// ... array_push an associative array with the new datas
$outputString .= '<'.'? array_push( $bookmarksArray, array( ';
$outputString .= '"name"=>"'. $_POST[ 'name' ] .'", ';
$outputString .= '"url"=>"'. $_POST[ 'url' ] .'", ';
$outputString .= '"description"=>"'. $_POST[ 'description' ] .'" ';
$outputString .= ') ); ?'.">\n";

// append the outputString to the file
$file = fopen( $fileName, "a" );
fwrite( $file, $outputString );
fclose( $file );

// and voilà
header( "Location: view_bookmarks.php" );

?>

and view_bookmarks.php become :

code:
<html>
<body>
<h1>bookmarks</h1>
<dl>
<?

include( "bookmarks.inc.php" );
foreach( $bookmarksArray as $currentEntry )
{
echo "\n\t<dt><a href='". $currentEntry['url'] ."'>". htmlentities( $currentEntry['name'] ) ."</a></dt>";
echo "\n\t<dd>". htmlentities( $currentEntry['description'] ) ."</dd>";
}

?>
</dl>
</body>
</html>

Obviously, you can add some informations in the associative array ( who said 'category' ? ), and sort the $bookmarksArray at will before displaying it.

Btw, the serialize and unserialize functions are damn useful to do generate some data CACHEs too.


[edit] one day I'll be able to write monster-post without editing them ... one day [/edit]

[This message has been edited by poi (edited 02-20-2004).]

Tyberius Prime
Paranoid (IV) Mad Scientist with Finglongers

From: Germany
Insane since: Sep 2001

posted posted 02-20-2004 16:08

actually... writing php code from textual input to a script is an easy way to great an enormous security hole...
And it is not that easy to 'make the data safe'. Data is data, and should not be put into executable files, if you can't gurantee that the data only comes from 'good' sources (which you never can in a web enviroment).

Plus,
it's just complicates such a trivial task as rincewind is going for around here, don't you think, poi?
Serialize/unserialize are much better, clearer, safer, and easier to use than writing having php code create more php code.

poi
Paranoid (IV) Inmate

From: France
Insane since: Jun 2002

posted posted 02-20-2004 17:27

Tyberius Prime: I fully agree with you. I should stop to think to my posts as I write them

I should have insisted on the importance to check the datas before using them. But as you said on some occasion you know the skill and intentions of the people who'll use your script and you can trust they ( all the more if the person is yourself, the author of the script, which is the case here ) won't try to execute a malicious code.

Regarding the security measures to prevent an attack, AFAIK there's really few things left once you've set up an HTTP authentication, checked the referer ( and eventually the IP of the client ), taken care of the magic_quote + length of the datas and encoded the special characters.

And yes, serialize/unserialize are far more appropriate for a mere data cache. I've used them once combined with gzcompress/gzuncompress to create some cache files for a big data structure that took ages to retrieve from the database otherwise.

CPrompt
Maniac (V) Inmate

From: there...no..there.....
Insane since: May 2001

posted posted 02-20-2004 22:45
quote:
3) preventing the bookmark-form to be seen by anyone but me.



For that, I would look into using htaccess

Later,

C:\


~Binary is best~

Steve
Maniac (V) Inmate

From: Boston, MA, USA
Insane since: Apr 2000

posted posted 02-21-2004 05:12

Okay - as a relatively new and unsophisticated php user, I was following this pretty well until just now. I had been thinking along Poi's lines, but not so fancy. Why can't you just have the form append a new, formatted line to a simple text file and include that text file in the viewbookmarks.php page? Why does the receiving file have to have any php in it at all?

I followed the links to the serialize/unserialize page and as usual, php.net made my head ache.

I guess I sort of understand in a fuzzy way how serialize could save significant space in a large database. How does it apply to Rinswind 2th's little links thing? What are the advantages to so complex a function in a relatively small application?

poi
Paranoid (IV) Inmate

From: France
Insane since: Jun 2002

posted posted 02-21-2004 05:51

To make it short, serialize creates a string describing a PHP variable and unserialize does the reverse operation ( re-create a PHP variable from a string ). I mentionned them because they could be used here to replace my associative array by creating that same associative array in write2file.php and appending its serialized string to the bookmarks.inc.php instead of appending a juggling with the quotes, double quotes and splitting the <? and ?> tags..

But as TP said, generating some PHP code for such a simple task is a waste of energy and can be dangerous if you don't take some precautions.

Tyberius Prime
Paranoid (IV) Mad Scientist with Finglongers

From: Germany
Insane since: Sep 2001

posted posted 02-21-2004 11:20

Steve: There's nothing wrong with storing the data in a simple text file, but you would not include it. Because then, if it was to contain php code, it would get executed.
You would read the file, using the fopen() and assorted functions, and intepret it from there.

« BackwardsOnwards »

Show Forum Drop Down Menu