PHP fwrite writing empty file - php

I'm trying to make this save a file and it creates the file, but it's always empty. This is the code for it:
<?php
$code = htmlentities($_POST['code']);
$i = 0;
$path = 'files/';
$file_name = '';
while(true) {
if (file_exists($path . strval($i) . '.txt')) {
$i++;
} else {
$name = strval($i);
$file_name = $path . $name . '.txt';
break;
}
}
fopen($file_name, 'w');
fwrite($file_name, $code);
fclose($file_name);
header("location: index.php?file=$i");
?>
I echoed out $code to make sure it wasn't empty, and it wasn't. I also tried replacing
fwrite($file_name, $code);
with this:
fwrite($file_name, 'Test');
and it was still empty. I have written to files a couple of times before in PHP, but I'm still really new to PHP and I have no idea whats wrong. Could someone tell me what I'm doing wrong or how to fix this? Thanks

Reading/Writing to/from a file or stream requires a resource handle:
$resource = fopen($file_name, 'w');
fwrite($resource, $code);
fclose($resource);
The resource handle $resource is essentially a pointer to the open file/stream resource. You interact with the created resource handle, not the string representation of the file name.
This concept also exists with cURL as well. This is a common practice in PHP, especially since PHP didn't have support for OOP when these methods came to be.

Take a look of the samples on php.net

Related

PHP file stream data coming back in Binary

So I have a function that I CANNOT get to work. What's happening is it's coming back with data that's in binary and not the actual file. However, in the binary that I get back, the name of the particular file is included in the string. The data looks like this:
PK‹Mpt-BR/finalinport.html³)°S(ÉÈ,V¢‘ŒT…‚ü¢’ÒôÒÔâT…´Ì¼Ä ™” “I,QðT(ÏÌÉQ(-ÈÉOLQH„¨‡*Ê/B×]’X”žZ¢`£_`ÇPK.Ùô LePK‹M.Ùô Lept-BR/finalinport.htmlPKD
pt-BR is the directory and the 'finalinport.html' is the file that I am trying to have downloaded. If I replace the second parameter of fwrite to just a plain string, then everything works and I get the string that I wrote in a file inside of the zip. But not when I'm using Stream->getContents(), which leads me to believe that it is something going on with the stream. I cannot wrap my head around what can be happening. I've been on this for a week and a half now so any suggestions would be great.
public function downloadTranslations(Request $request, $id)
{
$target_locales = $request->input("target_locale");
$has_source = $request->input("source");
$client = new API(Auth::user()->access_token, ZKEnvHelper::env('API_URL', 'https://myaccount.com'));
$document = Document::find($id);
$job_document = JobDocument::where('document_id', $id)->first();
$job = Job::find($job_document->job_id);
$file = tempnam('tmp', 'zip');
$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);
$name_and_extension = explode('.', $document->name);
if($target_locales == null){
$target_locales = [];
foreach ($job->target_languages as $target_language) {
$target_locales[] = $target_language['locale'];
}
}
foreach($target_locales as $target_locale){
$translation = $client->downloadDocument($document->document_id, $target_locale);
$filename = $name_and_extension[0] . ' (' . $target_locale . ').' . $name_and_extension[1];
if($translation->get('message') == 'true') {
//API brings back file in stream type
$stream = Stream::factory($translation->get('body'));
$newFile = tempnam(sys_get_temp_dir(), 'lingo');
$handle = fopen($newFile, 'w');
fwrite($handle, $stream->getContents());
$zip->addFile($newFile, 'eh.html');
fclose($handle);
}
else if($translation->get('message') == 'false'){
//API brings back file contents
$zip->addFromString($filename, $translation->get('body'));
}
}
$translation = $client->downloadDocument($document->document_id, null, null);
$filename = $name_and_extension[0]. ' (Source).'.$name_and_extension[1];
$zip->addFromString($filename, $translation->get('body'));
sleep(10);
$zip->close();
return response()->download($file, $name_and_extension[0].'.zip')->deleteFileAfterSend(true);
}
I'm unfamiliar with PHP streams and I don't have a debugger set up so I keep thinking it has something to do with how I am handling the stream. Because the other condition (the else if) is coming back as content of the file (string) and the if statement, the data is coming back as a stream resource, which I am unfamiliar with.
Stream::factory
is used in Guzzle 5, use json_encode for Guzzle 6.

My php script won't open files that aren't in its root directory

This is a php script for a user login system that I am developing.
I need it to read from, and write to, the /students/students.txt file, but it won't even read the content already contained in the file.
<?php
//other code
echo "...";
setcookie("Student", $SID, time()+43200, "/");
fopen("/students/students.txt", "r");
$content = fread("/students/students.txt", filesize("/students/students.txt"));
echo $content;
fclose("/students/students.txt");
fopen("/students/students.txt", "w");
fwrite("/students/students.txt", $content."\n".$SID);
fclose("/students/students.txt");
//other code
?>
You are not using fopen() properly. The function returns a handle that you then use to read or edit the file, for example:
//reading a file
if ($handle = fopen("/students/students.txt", "r"))
{
echo "info obtained:<br>";
while (($buffer = fgets($handle))!==false)
{ echo $buffer;}
fclose($handle);
}
//writing/overwriting a file
if ($handle = fopen("/students/students.txt", "w"))
{
fwrite($handle, "hello/n");
fclose($handle);
}
Let me know if that worked for you.
P.S.: Ty to the commentators for the constructive feedback.
There are many ways to read/write to file as others have demonstrated. I just want to illustrate the mistake in your particular approach.
fread takes a file handle as param, NOT a string that represents the path to the file.
So your line:
$content = fread("/students/students.txt", filesize("/students/students.txt")); is incorrect.
It should be:
$file_handle = fopen("/students/students.txt", "r");
$content = fread($file_handle, filesize("/students/students.txt"));
Same thing when you write contents to file using fwrite. Its reference to the file is a File Handle opened using fopen NOT the filepath. when opening a file using fopen() you can also check if the $file_handle returned is a valid resource or is false. If false, it means the fopen operation was not successful.
So your code:
fopen("/students/students.txt", "w");
fwrite("/students/students.txt", $content."\n".$SID);
fclose("/students/students.txt");
Needs to be re-written as:
$file_handle = fopen("/students/students.txt", "w");
fwrite($file_handle, $content."\n".$SID);
fclose($file_handle);
You can see that fclose operates on file handles as well.
File Handle (as per php.net):
A file system pointer resource that is typically created using fopen().
Here are a couple of diagnostic functions that allow you to validate that a file exists and is readable. If it is a permission issue, it gives you the name of the user that needs permission.
function PrintMessage($text, $success = true)
{
print "$text";
if ($success)
print " [<font color=\"green\">Success</font>]<br />\n";
else
print(" [<font color=\"red\">Failure</font>]<br />\n");
}
function CheckReadable($filename)
{
if (realpath($filename) != "")
$filename = realpath($filename);
if (!file_exists($filename))
{
PrintMessage("'$filename' is missing or inaccessible by '" . get_current_user() . "'", false);
return false;
}
elseif (!is_readable($filename))
{
PrintMessage("'$filename' found but is not readable by '" . get_current_user() . "'", false);
return false;
}
else
PrintMessage("'$filename' found and is readable by '" . get_current_user() . "'", true);
return true;
}
I've re-written your code with (IMO) a cleaner and more efficient code:
<?php
$SID = "SOMETHING MYSTERIOUS";
setcookie("Student", $SID, time()+43200, "/");
$file = "/students/students.txt"; //is the full path correct?
$content = file_get_contents($file); //$content now contains /students/students.txt
$size = filesize($file); //do you still need this ?
echo $content;
file_put_contents($file, "\n".$SID, FILE_APPEND); //do you have write permissions ?
file_get_contents
file_get_contents() is the preferred way to read the contents of a
file into a string. It will use memory mapping techniques if supported
by your OS to enhance performance.
file_put_contents
This function is identical to calling fopen(), fwrite() and
fclose() successively to write data to a file. If filename does not
exist, the file is created. Otherwise, the existing file is
overwritten, unless the FILE_APPEND flag is set.
Notes:
Make sure the full path /students/students.txt is
correct.
Check if you've read/write permissions on /students/students.txt
Learn more about linux file/folder permissions or, if you don't access to the shell, how to change file or directory permissions via ftp
Try to do this:
fopen("students/students.txt", "r");
And check to permissions read the file.

Why file_put_contents() not always rewrites a file?

I wonder, why PHP file_put_contents() function works in a weird way.
I used it in a loop to write some logs to file and all was fine (new lines were appended even if no flag was specified). When I started the script again, it re-created my file.
From PHP doc:
If filename does not exist, the file is created. Otherwise, the
existing file is overwritten, unless the FILE_APPEND flag is set.
OK, so my question is: Why (when used in one loop) it doesn't overwrite my file (without FILE_APPEND flag of course)? Bug or feature? :)
Edit: Example context of use when this happened:
$logFile = dirname ( __FILE__ ) . '/example.log';
foreach($something1 as $sth1) {
$logData .= "Something\n";
foreach($something2 as $sth2) {
if($something_else) {
$logData .= "Line: \t" . $sth2 . "\n";
file_put_contents($logFile, $logData);
}
}
}
As it has been very clearly mentioned in this link under the flags content(which you should have read) it clearly states that if file filename already exists, append the data to the file instead of overwriting it(when this flag is set). So when the flag for FILE_APPEND is set it appends and when not it rewrites. Hope this helped you.
Alternative Way
<?php
$file = 'file.txt';
$append = true;
if (file_exists($file)) {
if ($append) {
// append file
$file = fopen($file, 'a+');
} else {
// overwrite file
$file = fopen($file, 'a');
}
} else {
// create file
$file = fopen($file, 'a');
}
fwrite($file, 'text');
fclose($file);
?>
here is a php fopen documentation
and php file
and read on its related topics
ok, when you are run the script each time try to rename the log file with random number or currentdate timestamp and try to save it in your DB
by this when you again run the script and can take the log file name from DB and update it when you needed

Parsing and Writing Files in PHP

I'm attempting to open a directory full of text files, and then read each file line-by-line, writing the information in each line to a new file. Within each text file in the directory I'm trying to iterate, the information is formed like:
JunkInfo/UserName_ID_Date_Location.Type
So I want to open every one of those text files and write a line to my new file in the form of:
UserName,ID,Date,Location,Type
Here's the code I've come up with so far:
<?php
$my_file = 'info.txt';
$writeFile = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file
$files = scandir('/../DirectoryToScan');
foreach($files as $file)
{
$handle = #fopen($file, "r");
if ($handle)
{
while (($buffer = fgets($handle, 4096)) !== false)
{
$data = explode("_", $buffer);
$username = explode("/", $data[0])[1];
$location = explode(".", $data[3])[0];
$type = explode(".", $data[3])[1];
$stringToWrite = $username . "," . $data[1] . "," . $data[2] . "," . $location . "," . $type;
fwrite($writeFile, $stringToWrite);
}
if (!feof($handle))
{
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
}
fclose($writeFile);
?>
So my problem is, this doesn't seem to work. I just never get anything happening -- the output file is never written and I'm not sure why.
There is one potential issue with the scandir() line:
$files = scandir('/../DirectoryToScan');
The path begins with a /, which means that it is looking in the root of the server. So, the directory it's trying to read is /DirectoryToScan. To fix it, you can just remove the leading /. Of course, this could be a sample path for this example and may not actually apply to reality, or maybe you really do have a directory in the root of your system named that - in these cases, feel free to ignore this bit =P.
The next thing is when you're using fopen() on the files you're iterating through. scandir() returns the name of the file, not the full path. You'll need to concat the directory name and the file each time:
$dir = '../DirectoryToScan/';
$files = scandir($dir);
foreach($files as $file) {
$handle = #fopen($dir . $file, "r");
I'm currently running an older version of PHP, so directly-accessing array indexes from return-functions, such as with explode("/", $data[0])[1], doesn't work for me (it was added in PHP 5.4).
Other than that, the rest of your code looks like it should work fine (minus any potential logic/data errors that I may have overlooked).

What am I doing wrong? PHP script with nothing visibly wrong

<?php
$file = fopen("configuration.conf","w+");
$settings['LogEnabled'] = "true";
$settings['Pass'] = "pass";
$settings['ShowWarning'] = "true";
fwrite($file,serialize($settings));
$path = "configuration.conf";
$file2 = file_get_contents($path);
$settings2=unserialize($file2);
echo($settings2['LogsEnabled']);
?>
It ought to show "true" when run. Whats wrong?
I tried fread and fopen for $file2, but neither work.
EDIT: It does not throw an error.
The file has permissions 0740
Not sure if it matters, but you have 'LogEnabled' in the serialize section and 'LogsEnabled' in the unserialize section.
Could that 's' be throwing you off?
Flush (and preferably close the file), before reading its contents.
/* Write stuff to $file */
fflush($file);
fclose($file);
/* Read stuff from file */

Categories