jeanl
jeanl

Reputation: 389

stream_get_contents() returns an empty string

I have a form that receives a .txt file input. In my php code, I retrieve this file from the form and try to save it in the server:

$fp = fopen($_FILES['textFile']['tmp_name'], 'rb');
saveFile($fp);

//saves file to server with a random file name
function saveFile($file) {

  $fileName = mktime().".txt";

  //creates new file
  $newFile = fopen("".$fileName, 'w');
  $content = stream_get_contents($file);
  echo "CONTENT ".$content;
  if($newFile) {
    fwrite($newFile, $content);
    fclose($newFile);
    fclose($file);
    echo "File saved in server as ".$fileName.".";
  } else {
    echo "Failed to write file to server.";
  }
}

I am able to save the file but it's empty.

Upvotes: 1

Views: 3261

Answers (1)

Paul Latour
Paul Latour

Reputation: 110

You must parse the content in the expression so that the stream contents are returned and resolved before the parsing of the fwrite function. To do this, you must use an extra set of brackets surrounding your $content variable, like, "fwrite($newFile, ($content));" so.

Upvotes: 2

Related Questions