-1

I am working on a pastebin-like website where I will take two input fields like so:

<form name="form1" method="post" action="paste.php">
 Title: <input type="text" name="title"><br>
 Paste: <input type="text" name="paste"><br>
 <input type="submit" name="Submit" value="Paste Me"> 
 </form>

and I need to write the data to a file like so:

<?php

$title = $_POST['title'];
$paste = $_POST['paste'];

$fh = fopen("[name variable here].txt", "w");

fwrite($fh, $paste);
fclose($fh);

print "The paste has been submitted.";

?>

But in the $fh line, i need to know how i take the input from "title" and create a new txt file with the contents of the "paste" input. How would I do this?

  • Sidenote: You'd better make up for space compensation, unless you want your files to contain spaces; *just saying*. – Funk Forty Niner May 20 '14 at 21:37
  • I would not use user input and use that as the file-name, unless you validate it. – jeroen May 20 '14 at 21:39
  • @hakre Oh, come on admin, I wrote and answer and you closed question, before I got to submitting it. And that is NOT duplicate question. Anyway, here is my answer http://pastie.org/9194196 – Deele May 20 '14 at 22:07
  • @Deele: Sure, only the manual covers that completely, e.g. http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing – hakre May 20 '14 at 22:12

3 Answers3

0

So what you want is:

$fh = fopen("{$_POST['title']}.txt", "w");

or:

$fh = fopen($_POST['title'] . ".txt", "w");

But this is really a bad idea, because someone could fiddle with the title variable and give it so, that you overwrite an important file!

nl-x
  • 11,762
  • 7
  • 33
  • 61
  • If you were wondering, try using going to this url: `http://yourdomain.com/yourscript.php?title=evil.php%00&paste=%3C?php%20eval($_GET%5B'evil'%5D);%20?%3E` and then look at that evil little php file that appears next to where your other .txt files are. (assuming you are using $_GET in stead of $_POST. But this is very possible in $_POST as well) – nl-x May 20 '14 at 22:15
0

In order to use the $_POST['title'] variable as the name of the text file you would do this (you have already assigned the value from the POST array to $title) -

$fh = fopen($title.".txt", "w");

As others have cautioned you, make sure to validate and cleanse the data coming in from users.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
0

I'd suggest using some framework like Symfony2 or Zend2 to create your website. It provides many tools like validation, form control, cache, database/orm etc. But if you want to do that with pure PHP try something like $fileName = preg_replace('/[^A-Za-z0-9_\-]/', '_', $title); And remember: NEVER save original content from the internet without validation.

Bartek
  • 1,349
  • 7
  • 13