Writing to a file in PHP with a variable as a file name

I have a script that will write a given line to a text file ...

I have experience writing txt files through PHP ....

I want to write a file when the form is submitted, and I have a script working to write to the file "users / user_txt / $ username.txt".

But this saves the file name as $ username.txt.

This is the code:

$fp = fopen('users/user_txt/$username.txt', 'a+'); $fwrite = fwrite($fp, "," . $log_write); 

This creates an empty text file and adds it or creates a file if the file does not exist ...

However, it saves the file name as /$username.txt .

I grab the variable "$ username" from the form and this is the correct echo ...

But I need this to create a file name like:

 DJ-PIMP.txt 

If I submit my username as a DJ-PIMP in the form ...

Let's pretend to fill out the form and enter the username as dave123 .

I need a script to write to a file as follows:

 $fp = fopen('users/user_txt/dave123.txt', 'a+'); 

How would I encode this so that when submitting the form (once the form has been submitted, the $ username variable will be "dave123").

+4
source share
1 answer

The above code example uses single quotes that literally take everything. Using:

 $fp = fopen("users/user_txt/$username.txt",'a+'); $fwrite = fwrite($fp, "," . $log_write); 

or

 $fp = fopen('users/user_txt/'.$username.'.txt', 'a+'); $fwrite = fwrite($fp, "," . $log_write); 
+5
source

Source: https://habr.com/ru/post/1396342/


All Articles