Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new txt file with a PHP function

Tags:

function

file

php

I am trying to write a function that takes two parameters (the filename and a sting to put inside) that creates a new file, containing the string.

<?php

function writeFile($name, $string) {
    $text = $string;
    $fh = fopen($name + ".txt", 'w') or die("Could not create the file.");
    fwrite($fh, $text) or die("Could not write to the file.");
    fclose($fh);
    echo "File " . $name . ".txt created!";
}

writeFile("testovFail", "Lorem ipsum dolor sit amet");

if(file_exists("testovFail.txt")) echo "<br>File exists!";

?>

This is what I have so far, the function echos that the file was created, but when I run the IF conditional to check whether the file was created, it returns that it wasn't.

like image 249
Georgi B. Nikolov Avatar asked Dec 15 '22 10:12

Georgi B. Nikolov


1 Answers

how about using file_put_contents instead?

$current = "John Smith";
file_put_contents("blabla.txt", $current);
like image 192
Desolator Avatar answered Dec 17 '22 22:12

Desolator