I am pretty new to PHP and am trying to use variables in a string, here is my code:
<?php
$userName = $_GET['Username'];
$message = $_GET['Message'];
if($_POST['Submit']){
$open = fopen("new.txt",'a');
$text = "
________________________________________"+$userName+":"+$message+"
________________________________________";
fwrite($open, $text);
fclose($open);
echo "File updated.<br />";
echo "File:<br />";
$file = file("new.txt");
foreach($file as $text) {
echo $text."<br />";
}
}
?>
Also, would I use 'a' for adding to a file? If not what would I use? Please help me, thanks in advance!
Use .
instead of +
for concatenation.
Or, you can just do:
$text = "
________________________________________$userName:$message
________________________________________";
or (to be slightly clearer to the parser):
$text = "
________________________________________{$userName}:{$message}
________________________________________";
$text = " ___$userName:$message "
will work. Also $text = "whatever{$var}bar{$var2}"
. The documentation for fopen is available here and says of 'a':
Open for writing only; place the file pointer at the end of the file.
'a' in this context generally means 'append'.
$text = "
________________________________________".$userName.":".$message."
________________________________________";
Use .
for concatination
a
would append to a file, so u want to replace the content you would use w
I always like single quotes (when possible) cause they are faster:
$str = '5+5='.(5+5);
Also comma for echo instead of concatenation cause is faster:
echo '5+5=',(5+5);
And in very complex strings (if don't care for speed) and also quotes needed I use variables to make things look more clear:
$dbq="\"";
$sq='\'';
echo $dbq,'This is in double quotes.',$dbq,'<br>';
echo $sq,'This is in single quotes.',$sq;