Page 1 of 1

How do I fwrite a php variable into text input

Posted: Thu Jun 11, 2015 3:30 pm
by drayarms
I want to write a php variable obtained from a previous page via form submission, into a file which I save on the server. I have decided to write the variable as a form hidden input value, so that I can later easily retrieve it with javascript, when the page is loaded. So here's the code

Code: Select all

<?php

//So I first retrieve the variable which was submitted via a form from the previous page

$submitted_var = $_POST["value_of_submitted_stuff"];

//Then I create/open the file where I'll write the variable

$my_file = fopen("testfile.php", "w");


//Next I write the data to the file and save it

$page_content = "<form> <input  type = 'text' name = 'submitted_var' value = ".$submitted_var." />   </form>";
		
fwrite($my_file, $page_content);
		
		
fclose($my_file);


//Finally I redirect browser to the saved file

header("Location:testfile.php");
exit;

?>

Well on the client side, the data gets truncated at the first instance where a space in encounter for example if the data entered was "I'm going home", the form input will only display "I'm" and I have no clue what happens to the rest of the data or how to get it. If the data is "", the form displays a forward slash "/". I'm so confused. I must be missing something here. I tried escaping the data as such

Code: Select all

$submitted_var = htmlspecialchars($submitted_var);
No luck though. Not that when I just write the data into the body of the page and not into a form field, it displays correctly.

Re: How do I fwrite a php variable into text input

Posted: Thu Jun 11, 2015 3:44 pm
by Celauran
You'd need quotes around value=

Really, though; what are you trying to accomplish? This looks exceedingly convoluted. Could you not manage the same with cookies or sessions? Maybe a database if you need persistence?

Re: How do I fwrite a php variable into text input

Posted: Thu Jun 11, 2015 4:39 pm
by twinedev
you have a big, Big, BIG security issue with this code. You are allowing the user to execute any PHP code they want (assuming they know/figure out how the site works).

Besides that issue, in addition to what Celauran mentioned about needing to wrap the value with quotes, you should also use htmlspecialchars( $submitted_var ) for what you are putting into the quotes.

Also like mentioned, there is a probably a better way to handle this. I'm also awaiting to hear what you are trying to get done with the code.