skip to Main Content

When a user clicks submit I am trying to create a file.

Centos 7

php 7.2

I have tried to modify the code a couple different ways also tried file_put_contents does not seem to work.

Code:
index.php

<form action="sendmail.php" method="post">
<input type="text" placeholder="fname" name="fname">
<button type="submit">submit</button>
</form>

sendmail.php:

<?php
$fname = $_POST["fname"];
echo "bef: " . $fname;
$myfile = fopen("/signupemails/" . $fname . ".txt", "w") or die("Unable to open file!");
echo "aft: " . $fname;
$txt = $fname;
fwrite($myfile, $txt);
fclose($myfile);
?>

Directory to create file

[root@webserver webdir]# ll -d /signupemails/
drwxrwxrwx. 2 apache apache 51 Aug 25 20:41 /signupemails/

If i change sendmail.php and hardcode the $fname and run php sendmail.php it will create the file fine

Creating it from the browser I get “Unable to open file!”

3

Answers


  1. Try changing this line:

    $myfile = fopen("/signupemails/" . $fname . ".txt", "w") or die("Unable to open file!");
    

    PHP doesn’t have the same logical “or” semantics as JavaScript. That expression returns a boolean, so $myfile will equal true instead of the file handle.

    Write it this way:

    $myfile = fopen("/signupemails/" . $fname . ".txt", "w");
    if (!$myfile) die("Unable to open file!");
    
    Login or Signup to reply.
  2. I suggest do with js
    For example

    
    function download(filename, text) {
      var element = document.createElement('a');
      element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
      element.setAttribute('download', filename);
    
      element.style.display = 'none';
      document.body.appendChild(element);
    
      element.click();
    
      document.body.removeChild(element);
    }
    
    // Start file download.
    download("hello.txt","This is the content of my file :)");
    
    Login or Signup to reply.
  3. Your code should work as is, i just tested it and it seemed to work fine.

    Is selinux disabled?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search