How do I use php so that when a user presses a specific button, they can write to a specific .txt file?

时间秒杀一切 提交于 2019-12-02 10:28:36

Well, you should learn about using forms with PHP, with regards to your comment. If you read that tutorial fully, it should answer all of your questions about forms and php.

As far as getting it to write to a different text file, since you seem worried about "uploading all those pages", you'll be happy to know there's an easy solution!

There's a function called file_put_contents, which will create or write into a file.

Since you're new(ish) to PHP, here's an example:

<?php

$file = 'hello.txt';
$text = 'Hello World!';

file_put_contents($file, $text);

?>

This puts the contents of the $text variable into the file with the name stored in $file.

Reading from a file is similarly easy, with file_get_contents.

Assuming the file hello.txt exists from before and has the same contents, you can use the following code to read from the file and output its contents:

<?php

$file = 'hello.txt';

echo(file_get_contents($file));

?>

That will show the contents of $file.

Now, moving into the specifics of your question, if your form sets a "to" and a "from" GET variable where "to" is your username already, then the following code would write the value in a "message" GET variable into the file based on the pattern you gave:

<?php

$to = addslashes($_GET['to']);
$from = addslashes($_GET['from']);
$msg = addslashes($_GET['message']);
//addslashes is used as a small security measure

$file = $to . $from . '.txt';
file_put_contents($file, $msg);

?>

This fetches our variables from the GET array, sanitizes them to some extent, sets the file name, and writes the message to the file.

If you have any questions about specific parts of this or you'd like me to go into more detail, please feel free to ask!

This is how to write to a file: http://php.net/manual/en/function.fopen.php

You're better off to use a database tho for sure.

To make different links do different things, you can use AJAX as you suggested or you can use GET variables to route functions on the PHP side. The latter is easier but means you will need to reload the page after the user presses the button.

here's a little demo:

<a href="thispage.php?clicked=1">click here</a>

then at the top of the page in php:

 if($_GET['clicked']==1){--write to file1---}
 else if($_GET['clicked']==2){--write to file2---}

Hope it helps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!