PHP - Adding predefined text as well as session variable using fwrite - php

In the following code, i want to be able to include 'Name:', 'Age:' and 'Email:' before the PHP script writes the variables $name, $age and $email.
It seems so simple, but i just can't get it to work!
<?php
session_start();
$name = $_SESSION['name'];
$age = $_SESSION['age'];
$email = $_SESSION['email'];
$handle = fopen('users.txt', 'a');
fwrite($handle, $name."\n");
$handle = fopen('users.txt', 'a');
fwrite($handle, $age."\n");
$handle = fopen('users.txt', 'a');
fwrite($handle, $email."\n");
fclose($handle);
?>
I have tried this:
<?php
session_start();
$name = $_SESSION['name'];
$age = $_SESSION['age'];
$email = $_SESSION['email'];
$handle = fopen('users.txt', 'a');
fwrite($handle, 'Name:', $name."\n");
$handle = fopen('users.txt', 'a');
fwrite($handle, 'Age:', $age."\n");
$handle = fopen('users.txt', 'a');
fwrite($handle, 'Email', $email."\n");
fclose($handle);
?>
However, all that prints in the user.txt document is 'Age:'.
Any help would be appreciated, thanks!
UPDATE: Removed the multiple fopen and replaced ',' with '.' Everything working perfectly, thanks for everyones help!

<?php
session_start();
$data = array(
'Name:' . (isset($_SESSION['name']) ? $_SESSION['name'] : '') ,
'Age:' . (isset($_SESSION['age']) ? $_SESSION['age'] : '') ,
'Email:' . (isset($_SESSION['email']) ? $_SESSION['email'] ; '') ,
);
if ($fp = fopen('users.txt','a')) {
fwrite($fp,implode(PHP_EOL,$data).PHP_EOL);
fclose($fp);
} else {
die('Error');
}

Use can use this
$fp = fopen('users.txt', 'a');
fwrite($fp, 'Name : '.$name . PHP_EOL);
fwrite($fp, 'Age : '.$age . PHP_EOL);
fwrite($fp, 'Email : '.$email . PHP_EOL);
fclose($fp);

Related

Problem: register_shutdown_function doesn't start

My part code :
function onDie(){
$filename= 'statistic.txt';
$handle = fopen($filename, 'a+') or die('cannot access file statistic.txt');
fwrite($handle, 'shutdown: ' . mt_rand(1, 100) . PHP_EOL);
fclose($handle);
}
register_shutdown_function('onDie');
//onDie();
echo '1';
die('FAtal error ');
Function onDie didn't run becouse file statistic.txt is empty
What's problem here ? Help please

How to add more text to a file by php

Hello guys the following code will add only one line of text to my 'file.txt' whenever i m
going to add more text so its replacing the old one, i want to have the old one with new also
Beside this one i want to separate the words in my 'txt.file' by a comma and space.
Here is my code:
<?php
$Fname = $_POST['fname'];
$email = $_POST['email'];
$Phone = $_POST['number'];
$date = $_POST['date'];
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $Fname);
fwrite($handle, $email);
fwrite($handle, $Phone);
fwrite($handle, $date);
?>
Because you are using write mode (w). To add lines to the end, you have to append (a):
$handle = fopen($my_file, 'a');
To separate words by comma and space, join it into one string in PHP and than save it:
$finalString = $Fname . ', ' . $email . ', ' . $Phone . ', ' . $date;
fwrite($handle, $finalString );
//or you can use file_put_content to add to end of each line
$my_file = 'file.txt';
file_put_content($my_file, $Fname, PHP_EOL, PHP_APPEND);
file_put_content($my_file, $emai, PHP_EOL, PHP_APPEND);
file_put_content($my_file, $phone, PHP_EOL, PHP_APPEND);

PHP fwrite() how to insert a new line after some specific line

I'm new here.
Anyway, I did my research on fwrite(), but I couldn't find solution, so i'm asking for help.
What I want is f.e. to add a new line of text after some other specific line.
F.e. I have a .txt file in which there is:
//Users
//Other stuff
//Other stuff2
Now what I'd like to do is be able to add a new user below //Users without touching "Other Stuff" and "Other Stuff 2". So it should look something like this:
//Users
Aneszej
Test321
Test123
//Other stuff
//Other stuff2
What I have so far:
$config = 'test.txt';
$file=fopen($config,"r+") or exit("Unable to open file!");
$date = date("F j, Y");
$time = date("H:i:s");
$username = "user";
$password = "pass";
$email = "email";
$newuser = $username . " " . $password . " " . $email . " " . $date . " " . $time;
while (!feof($file)) {
$line=fgets($file);
if (strpos($line, '//Users')!==false) {
$newline = PHP_EOL . $newuser;
}
}
fwrite($file, $newline);
fclose($file);
test.txt file
//Users
//Something Else
//Something Else 2
But this only writes users to the end of the .txt file.
Thanks a lot everyone for your help! It's solved.
I modified your code, I think follows is what you need, and I also put comment, function below will keep adding new user, you can add condition that to check user exist.
$config = 'test.txt';
$file=fopen($config,"r+") or exit("Unable to open file!");
$date = date("F j, Y");
$time = date("H:i:s");
$username = "user";
$password = "pass";
$email = "email";
$newuser = $username . " " . $password . " " . $email . " " . $date . " " . $time."\r\n"; // I added new line after new user
$insertPos=0; // variable for saving //Users position
while (!feof($file)) {
$line=fgets($file);
if (strpos($line, '//Users')!==false) {
$insertPos=ftell($file); // ftell will tell the position where the pointer moved, here is the new line after //Users.
$newline = $newuser;
} else {
$newline.=$line; // append existing data with new data of user
}
}
fseek($file,$insertPos); // move pointer to the file position where we saved above
fwrite($file, $newline);
fclose($file);
You write the new content at the end of the reading, so it has to write at the end of file - the cursor is there after reading all the lines.
Either you store all the content in php-variable and overwrite the file in the end, or you rewind the curser with fseek as mentioned by Robert Rozas comment. That should be done as soon as you read the "Something else" - line.
Try fseek:
<?php
$file = fopen($filename, "c");
fseek($file, -3, SEEK_END);
fwrite($file, "whatever you want to write");
fclose($file);
?>
PHP Doc: http://php.net/manual/en/function.fseek.php
You need to break after you find '//Users'. You keep reading to the end of the file.

PHP variable is empty only in fwrite

I think I'm going crazy.
code:
<?
$meh = $_GET["q"];
echo ( ":" . $meh . ":" . strlen($meh) . PHP_EOL );
$fp = fopen("/tmp/wtf.log","w+");
fwrite($fp, ":" . $meh . ":" . strlen($meh) . PHP_EOL );
fclose($fp);
?>
request:
/search.php?q=meh123
This is in the response ( expected ):
:meh123:6
This is in the file:
me#host:/tmp# cat wtf.log
::0
Try this:
<?
$meh = $_GET["q"];
$writeline = ":{$meh}:{strlen($meh)}";
echo ( $writeline );
$fp = fopen("/tmp/wtf.log","w+");
fwrite($fp, $writeline );
fclose($fp);
?>
Also, as Jay said in the comment above:
try putting if(isset($_GET['q'])) { // code } around your code (something you should be doing anyway)

php fopen - name of file

I currently have:
<?php
if (isset($_POST["submitwrite"])) {
$handle = fopen("writetest.txt","w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
?>
However I need to adjust the filename to be dynamic, instead of 'writetest.txt' I would like it to be: username+pollname+time.txt taking the $_post variables.
I would also like to change the directory these files are stored in to /results.
Help please...
You mean doing something like this?
$filename = '/results/' . $_POST['username'] . '/' . $_POST['pollname'] . '/time.txt';
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
// etc...
Or am I not understanding you?
Edit
To address the issue BalusC pointed out, this is a more complete solution.
It makes sure the $_POST['username'] and $_POST['pollname'] values are valid, so they won't create an invalid or possibly harmful $filename.
<?php
$basedir = '/results';
$basename = 'time.txt';
// Get user and poll names
$username = $_POST['username'];
$pollname = $_POST['pollname'];
// Counteract the old magic_qutoes feature, if needed.
if(get_magic_quotes_gpc()) {
$username = stripslashes($username);
$pollname = stripslashes($pollname);
}
// Validate user and poll names.
$regexp = '/^[\w\d\_\-\. \']+$/iu';
if(!preg_match($regexp, $username) || !preg_match($regexp, $pollname)) {
echo 'Username or pollname is invalid. Aborting!';
}
else {
// Compile the complete file name
$filename = $basedir . '/' . $username . '/' . $pollname . '/' . $basename;
// Write to the file
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
}
?>
fopen creates (at least tries) the file if it does not exist, so
$filename = $username . $pollname . $time . '.txt';
$handle = fopen($filename, 'w+');
will work fine.
By the way, w+ places the pointer at the beginning of the file. If the file already has some data, it will truncate it first. If you want to append data to the file, you may want to use 'a+'

Categories