0

I am trying to create a php\shell script to create a file. I am using the exec() command to create the link between the shell and the php itself. I am also trying to receive data from the user and for that I have a php form page linked to the script.

<?php
$username = $_POST['txt_username'];
exec("sudo echo $username > file.txt");
?>

From my research I have found that exec() does not accept $_POST or $_GET variables. I have also tried functions like extract(), getenv() and var_dump(), as well as escapeshellcmd() and escapeshellarg(). Could someone help me?

5
  • 4
    exec() does not know where string variables originate from. You ought to escape them for shell context however, escapeshellarg() comes to mind. And exec is not uncommonly constrained by the server setup. Why aren't you using PHP-builtins for writing to files? Commented Mar 31, 2013 at 18:05
  • It's for a school project in which I have to create a php form page to receive data to input into a file information from the user. I can't use php builtins. Commented Mar 31, 2013 at 18:09
  • 1
    @user2229813: I think you misunderstood mario: php has functions for writing to files, such as file_put_contents(). Why exactly can't you use them? Commented Mar 31, 2013 at 18:16
  • 1
    Ouch, this looks evil. Do not do that! Let PHP write this file. You are passing client input directly to the OS' command line, which is more then a nasty security hole. Commented Mar 31, 2013 at 18:51
  • 1
    Imagine if the username as typed in the HTML form is exactly the "foo; /bin/rm -rf /" string -without the double quotes.... Commented Mar 31, 2013 at 19:33

2 Answers 2

1

is this what you are looking ?

<?php

$uname = $_POST['UserName']; 
$file_to_write = "file.txt";
$open_file = fopen($file_to_write,'w') or die ("Cant Open File");
fwrite($file_to_write, $uname);
flcose($file_to_write);

?>
Sign up to request clarification or add additional context in comments.

Comments

1

I would do it like this.

<?php
    file_put_contents( 'file.txt', $_POST['txt_username'] );
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.