PHP fopen() invalid argument - php

I'm running this code once the user submits a form. The idea is to save a new file called "message_timestamp" where timestamp is the current date and time. It need to be saved in the misc folder, which is located in the same directory as this php file.
My code:
if (isset($_POST['submitIssue'])) {
$type = $_POST['typeOfIssue'];
$prefName = $_POST['preferredName'];
$email = $_POST['userEmail'];
$details = $_POST['detailedReport'];
date_default_timezone_set('Atlantic/Bermuda');
$date = new DateTime('now');
$date = $date->format('Y-m-d_H:i:s');
$date = trim($date);
$fileName = "misc/message_" . $date;
$out = "Issue Alert!\nType of issue: " . $type . "\n\nSubmitted by " . $prefName . "\nEmail ID: " . $email . "\nSubmitted at: " . $date . "\n\nDetails: " . $details;
$myFile = fopen($fileName,"w") or die("Cannot open file!");
fwrite($myFile, $out);
fclose($myFile);
}
I've tried removing whitespaces and looking for escape characters. But as long as $date is appended to the filename, I get the error:
fopen(misc/message_2018-02-0210:47:41): failed to open stream: Invalid
argument in C:\MAMP\htdocs\A2\report.php on line 76
I can get it to work if I don't put the timestamp on it. Any suggestions?

Related

How do I create a new log file if my current log file is larger than 50mb in php?

I have a project where I have to make a new log file if the current log file is larger than 50mb. I know that we have to test for the size of the file.
I am starting out with this $log variable:
$log =
"Branch: ".$branchDir . PHP_EOL.
"Phase: ". $phaseDir . PHP_EOL.
"Total number of results files deleted: ". count($folderCounter). PHP_EOL.
"File names: " . $filePathToDelete . PHP_EOL.
"Starting CustomerID directory name: " . $CustIDvalue . PHP_EOL;
// $log = 'this is a test' . $branch . PHP_EOL;
$dt = time();
$mysql_datetime = strftime("%Y-%m-%d %H:%M:%S", $dt);
$mysql_datetimes = preg_replace('/\s+/', '', $mysql_datetime);
$logFileName = "ResultsFileDeletion" . $mysql_datetimes . ".txt";
if (unlink($filePathToDelete)) {
//this echo string will be moved to a log file
echo "first unlink: {$filePathToDelete} was deleted <br>";
$myFile =
file_put_contents("c:\\sites\\EtonBio/sequencing/logs/{$logFileName}",
$log, FILE_APPEND);
echo 'my file: ' . $myFile . '<br>';
}
I found this code snippet:
$size = filesize($_FILES['foto']['tmp_name']);
I believe my if statement would look something like this:
if($size < 52428800) {
*creates another log file
}
I want to format the $size variable correctly and I am also not sure how to make a new log file.
$size = filesize($_FILES['foto']['tmp_name']); only works if you are uploading the file.
If you want to check a file already in you server ou can simply do
$size = filesize("path/to/file");
Also, there is a ' in your $log declaration that shouldn't be there

Writing to a PHP file

I'm trying to write a basic error form to a file, but when I submit the file my PHP always crashes. I've tried some basic error fixes such as whether or not the if statement is occurring, if all the variables I'm using are not null, etc...
In my code all the string variables are valid an I am 100% certain they are not causing the error.
I've reduced it down through error testing to be the lines
$destination = fopen($filename,"w");
and
$fclose($destination);
My code:
if(isset($_POST['submit']) && $_POST['name'] != "" && $_POST['email'] != ""){
$filename = "message_" . date('Y-m-d H:i:s') . ".txt";
$issueType = "Type of issue: " . $_POST["issues"] . "\r\n";
$submitter = "Submitted by: " . $_POST["name"];
$email = "Email ID: " . $_POST["email"];
$time = "Submitted at: " . date('Y-m-d H:i:s') . "\r\n";
$message = "Details: " . $_POST["details"];
$destination = fopen($filename,"w");
fwrite($destination,"Issue Alert!");
fwrite($destination,$issueType);
fwrite($destination,$submitter);
fwrite($destination,$email);
fwrite($destination,$time);
fwrite($destination,$message);
$fclose($destination);
}
Any other code I'm implementing is irrelevant as I've cut off those as being points of error.
When I try this with basic, hard-coded strings I don't get any errors. All help is appreciated, Thanks!
Try to change your $filename, as you wrote
$filename = "message_" . date('Y-m-d H:i:s') . ".txt";
because you can't use colon ( ':' from 'H:i:s') in file name.
maybe you can try this:
$filename = "message_" . date('U') . ".txt";
you still have date-time information in your file name
But remember, if you have big traffic on your site, maybe you will get same file name in one second, and the previous existing file will overwrited

String adding new lines and I don't understand why

I have got this code to open each file in a folder, decrease a value by 5 and then overwrite the existing content.
<?php
foreach (glob("users/*.php") as $filename) {
$array = file($filename);
$wallet = $array[0];
$time = $array[1];
$status = $array[2];
$steamid = $array[3];
$process = fopen($filename, "w") or die("Unable to open file!");
$time = $time - 5;
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
fwrite($process, $newdata);
fclose($process);
}
?>
Before I execute the script, the files that are opened look like this:
680
310
0
74892748232
After the script was executed, the file looks like this:
680
305
0
74892748232
If the script is executed again, it adds more lines and just breaks the files even more.
The string for the file is created here:
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
Why does it add an empty line after $wallet and $status, but not after $time? How can I avoid this and instead write down:
$wallet
$time
$status
$steamid
Thanks a lot in advance.:)
Try with this solution
You can also use file_put_contents():
file_put_contents($filename, implode("\n", $array) . "\n", FILE_APPEND);
from this SO question
https://stackoverflow.com/a/3066811/1301180

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.

file_get_contents Warning: Failed to open stream

I have a question here, tho, I've been digging here at SO, it seems I can't find the real deal;
I am trying the ff:
<?php
$filename = $trantype . $delimiter . $dateToday . $fileExtension ;
//echo $filename . '<br/>';
$fileToOpen = $filepath . $filename;
echo "File To Open: " . $fileToOpen . '<br/>';
$string = file_get_contents($fileToOpen);
//$string = file_get_contents("../transactions/o/O_20120809.xx");
$json_array = json_decode($string, true);
echo "Echo: " . $json_array[0]['itemheader_sysid'] . '<br/>';
echo "The File Contents: " . $string;
?>
The $string = file_get_contents('../transaction/o/O_20120809.xx') works smoothly on the other hand the $string = file_get_contents($fileToOpen); doesn't seem to work and is giving me the ff: error;
Warning: file_get_contents(../transactions/o/0_20120809.xx) [function.file-get-contents]: failed to open stream: No such file or directory in C:\xampp\htdocs\xx\helper\upo.php on line 19
why so?
Anyone please?

Categories