why temp file doesn't echo its data its echo file path - php

I want to store a random key for every user in temp file . But what is the problem in my code it's echo the file path and can't create a temp file .
<?php
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
$data = random_string(50);
$filename = tempnam(sys_get_temp_dir(), 'prefix');
$fp = fopen($filename, 'w');
fwrite($fp, $data);
fclose($fp);
?>
call this file by:
<?php
$temp_file = tempnam(sys_get_temp_dir(), '');
echo $temp_file;
?>
result is something like this:/tmp/LnRFYu
/tmp dir is empty haven't create anything .
what is the problem on my code

There is no issue with the temp file creation code, so I don't really see what you are asking. I'm assuming you want to be able to view the contents of a specific temp file that has been created.
To do that your can use file_get_contents($file_name);
Like so
$contents = file_get_contents(sys_get_temp_dir() . 'temp_file_name.tmp');
echo $contents;

Related

Generate a new .txt file every 24 hour

I'm trying to make a visitor counter with php that will create yy-mm-dd.txt everyday and contain the number of visitors that day and after 12 AM it will create a new yy-mm-dd.txt file.
As example today is 2019-06-02 so the text file will be 2019-06-02.txt and in the next day, 2019-06-03.txt file will be automatically created.
Here is what I tried but it is not creating new 2019-06-03.txt file after 12 AM. It keeps the same 2019-06-02.txt file
<?php
$date = date('Y-m-d');
$fp = fopen('dates/'.$date.'.txt', "r");
$count = fread($fp, 1024);
fclose($fp);
$count = $count + 1;
$fp = fopen('dates/'.$date.'.txt', "w");
fwrite($fp, $count);
fclose($fp);
?>
How to fix it?
Your code should be working fine. We can also add is_dir and file_exists checks, and we can use either fopen, fwrite and fclose or file_get_content/file_put_content, if we like. We can also add a default_timezone such as:
date_default_timezone_set("America/New_York");
Then, our code would look like something similar to:
date_default_timezone_set("America/New_York");
$dir = 'dates';
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$count = 1;
$date = date('Y-m-d');
$filename = $dir . '/' . $date . '.txt';
if (!file_exists($filename)) {
$fp = fopen($filename, "w");
fwrite($fp, $count);
fclose($fp);
} else {
$count = (int) file_get_contents($filename) + 1;
if ($count) {
file_put_contents($filename, $count);
} else {
print("Something is not right!");
}
}
Better use file_get_contents then file_put_contents:
<?php
$count = 1;
$content = file_get_contents(date('Y-m-d').'txt');
if($content !== FALSE){
$count+=(int)$content;
}
file_put_contents(date('Y-m-d').'txt', $count);
?>

PHP to Increase counter by 1 and save in a txt file

I am trying my php script to read the current count from "counter.txt" file and add 1 and save it back in the counter text file.
$filename = 'counter.txt';
// create the file if it doesn't exist
if (!file_exists($filename)) {
$counter_file = fopen($filename, "w");
fwrite($counter_file, "0");
$counter = 0;
} else {
$counter_file = fopen($filename, "r");
// will read the first line
$counter = fgets($counter_file);
}
// increase $counter
$counter++;
// echo counter
echo $counter;
// save the increased counter
fwrite($counter_file, "0");
// close the file
fclose($counter_file);
The script reads and echos the number fine but it doesn't save the file with the increased number.
Please help
This may not be helpful if this is just a learning exercise to familiarize yourself with the various file functions, but this could be a lot simpler using file_get_contents and file_put_contents.
$file = 'counter.txt';
// default the counter value to 1
$counter = 1;
// add the previous counter value if the file exists
if (file_exists($file)) {
$counter += file_get_contents($file);
}
// write the new counter value to the file
file_put_contents($file, $counter);
Of course, whether or not this will work either this way or the way you're trying to do it totally depends on whether or not the file is writable, so you'll also need to be sure its permissions are set properly.
Works for me:
$counter = 1;
$file_name = 'test.'.$counter.'.ext';
if (file_exists($file_name)) {
$counter++;
fopen('test'.$counter.'.ext' , "w");
}
else {
fopen('test'.$counter.'.ext' , "w");
}
<?php
$filename = 'counter.txt';
// create the file if it doesn't exist
if (!file_exists($filename)) {
$counter_file = fopen($filename, "w");
fwrite($counter_file, "1");
fclose($counter_file);
} else {
$counter_file = fopen($filename, "w+");
$fsize = filesize($filename);
// will read the whole file
$counter = (int) fread($counter_file, $fsize);
$counter++;
fwrite($counter_file, $counter);
fclose($counter_file);
}

How to increment unique filename based on directory array

I'm creating an upload form that when uploading files will check to see if a file with the same name already exists in the directory. If a file with the same name is found, the script should increment the file by appending the file name with a number such as test1.txt test2.txt and so on until a match is not found. This is what I have come up with so far but wanted to see if there is a different approach I should take.
Also note, my filenames are already cleaned before they enter this part of the script so my filename and extension functions are simplified.
function filename($file){
return substr($file,0,strrpos($file,'.'));
}
function extension($file){
return strtolower(substr(strrchr($file,'.'),1));
}
$new_file = 'test.txt';
$dir = 'files';
$files = scandir($dir);
$exclude = array('.','..');
foreach($files as $file){
if(!in_array($file,$exclude)){
$file_array[] = $file;
}
}
$i = 1;
while(in_array($new_file,$file_array)){
$filename = filename($new_file);
$extension = extension($new_file);
if($i>1){
$num = strlen($filename);
$filename = substr($filename,0,-1);
$new_file = $filename.$i.'.'.$extension;
} else {
$new_file = $filename.$i.'.'.$extension;
}
echo $new_file.'<br>';
echo $i.'<br>';
$i++;
}
echo $new_file;

mkdir() not actually creating the directory

Basically when I click my submit button the code should create a random string that is 5 characters in length. Then it should make a folder (relative position) with the name being the random string generated. Then it should create an index file and write the "content" variable to the file. Unfortunately it never even makes the directory. Any help? I can't figure out what's wrong.
<?php
$characters = "abcdefghijklmnopqrstuvwxyz"; // Valid Folder Characters
if(isset($_POST["submit"])) {
$folder = randomString($characters, 5);
$file = fopen($folder . "/index.html", "w");
$content = "File Content";
mkdir($folder, 0777);
fwrite($file, $content);
fclose($file);
}
// Generate Random Folder Name
function randomString($valid_chars, $length) {
$random_string = "";
$num_valid_chars = strlen($valid_chars);
for($i = 0; $i < $length; $i++) {
$random_pick = mt_rand(1, $num_valid_chars);
$random_char = $valid_chars[$random_pick - 1];
$random_string .= $random_char;
}
return $random_string;
}
?>
Make sure you have writable permission where or in which directory you are creating new directory and for check try
if (!mkdir($folder, 0777, true)) {
die('Failed to create folders...');
}
Also you need to first create dir then file open
if(isset($_POST["submit"])) {
$folder = randomString($characters, 5);
if (!mkdir($folder, 0777, true)) {
die('Failed to create folders...');
}
$file = fopen($folder . "/index.html", "w");
$content = "File Content";
fwrite($file, $content);
fclose($file);
}
Try this out
$oldmask = umask(0);
if(!file_exists($dir)) mkdir($dir, 0777);
umask($oldmask);

Add a new line to a CSV file

If I have a CSV saved on a server, how can I use PHP to write a given line, say 142,fred,elephants to the bottom of it?
Open the CSV file for appending (fopen­Docs):
$handle = fopen("test.csv", "a");
Then add your line (fputcsv­Docs):
fputcsv($handle, $line); # $line is an array of strings (array|string[])
Then close the handle (fclose­Docs):
fclose($handle);
You can use an object oriented interface class for a file - SplFileObject http://php.net/manual/en/splfileobject.fputcsv.php (PHP 5 >= 5.4.0)
$file = new SplFileObject('file.csv', 'a');
$file->fputcsv(array('aaa', 'bbb', 'ccc', 'dddd'));
$file = null;
This solution works for me:
<?php
$list = array
(
'Peter,Griffin,Oslo,Norway',
'Glenn,Quagmire,Oslo,Norway',
);
$file = fopen('contacts.csv','a'); // 'a' for append to file - created if doesn't exit
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file);
?>
Ref: https://www.w3schools.com/php/func_filesystem_fputcsv.asp
If you want each split file to retain the headers of the original; this is the modified version of hakre's answer:
$inputFile = './users.csv'; // the source file to split
$outputFile = 'users_split'; // this will be appended with a number and .csv e.g. users_split1.csv
$splitSize = 10; // how many rows per split file you want
$in = fopen($inputFile, 'r');
$headers = fgets($in); // get the headers of the original file for insert into split files
// No need to touch below this line..
$rowCount = 0;
$fileCount = 1;
while (!feof($in)) {
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$out = fopen($outputFile . $fileCount++ . '.csv', 'w');
fputcsv($out, explode(',', $headers));
}
$data = fgetcsv($in);
if ($data)
fputcsv($out, $data);
$rowCount++;
}
fclose($out);

Categories