Find out if a directory exists in php - php

I want to know whether or not a directory exists.
If not, I would like to create the directory.
My code is below:
$da = getdate();
$dat = $da["year"]."-".$da["mon"]."-".$da["mday"];
$m = md5($url)."xml";
if(is_dir($dat))
{
chdir($dat);
$fh = fopen($m, 'w');
fwrite($fh, $xml);
fclose($fh);
echo "yes";
}
else
{
mkdir($dat,0777,true);
chdir($dat);
$fh = fopen($m, 'w');
fwrite($fh, $xml);
fclose($fh);
echo "not";
}

Use is_dir, which checks whether the path exists and is a directory then mkdir.
function mkdir_if_not_there($path) {
if (!is_dir($path)) {
// Watch out for potential race conditions here
mkdir($path);
}
}

Use is_dir:
$pathname = "/path/to/dir";
if(is_dir($pathname)) {
// do something
}

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 fwrite not writing

I'm trying to write a nickname from teamspeak to a file.
It goes through all the checks, but when I check the file afterwards, nothing gets written.
$file = "test.txt";
$fh = fopen($file, 'w');
if(file_exists($file))
{
echo "exist";
}else{
echo "absent";
}
if(is_writable($file))
{
echo "writable";
}else {
echo "cant write";
}
if (false === $fh) {
throw new RuntimeException('Unable to open log file for writing');
}
foreach($Summoners as $su){
$name = $su["TsNICK"];
echo $name;
fwrite($fh, $name);
echo "Wrote to file";
}
fclose($fh);
I can't really tell why your code isn't working, but you should consider rewriting it to this:
$file = "test.txt";
if (false === ($fh = fopen($file, 'w'))) {
throw new RuntimeException('Unable to open log file for writing');
}
foreach($Summoners as $su) {
$name = $su["TsNICK"];
echo $name;
fwrite($fh, "$name\n");
}
fclose($fh);
If you wish to always append to a file, you would need mode 'a' instead of 'w'.

Create file in directory

I am trying to create a file in a sub directory but it is not creating it
$tempFilename = "xml/tempfile.xml";
if(file_exists($tempFilename))
{
unlink($tempFilename);
}
$file = fopen($tempFilename,"w");
$fileTemplate = ($xml);
You can use file_put_contents
file_put_contents($tempFilename, '23');
Use fwrite :
$tempFilename = "xml/tempfile.xml";
// Test if directory exists.
$dirname = dirname($tempFilename);
if (!is_dir($dirname))
{
mkdir($dirname);
}
if(file_exists($tempFilename)){
unlink($tempFilename);
}
$file = fopen($tempFilename,"w");
// Write what you need
fwrite($file, 'content of my file');
fclose($file);
try this
first you need to create directory
$path = '/xml';
mkdir($path, 0777, true);
$tempFilename = "/xml/tempfile.xml";
if(file_exists($tempFilename))
{
unlink($tempFilename);
}
$file = fopen($tempFilename,"w");
fwrite($file, '23');
fclose($fp);

Create html file with php script

I want to create a php script that will check if a certain html file exist or not. if it doesn't exist, then create a new one and give it a name.
I have tried the code below, but still not working.
$file = file_get_contents(site_url('appraisal/createReport'));
$filename = 'Service_delivery_report_'.date('Y-m-d', time()).'.html';
$filepath = dirname(__DIR__).'/views/sd_reports/'.$filename;
write_file($filepath, $file);
if(! file_exists ($filename))
{
$fp = fopen($filename, 'w');
fwrite($fp, $file);
fclose($fp);
}
I'm not familiar with the method you're using called 'site_url'. From a quick google search it looks like it's a method in Word Press. Ignoring the site_url method, you might want to test using a specific url, like http://ted.com for example. I've specified is_file rather than file_exists because file_exists will return true even if the path you've specified is a directory, whereas is_file will only return true if the path is an actual file. Try this code, setting the $site variable to a site url or path to a file.
I've also switched some code around, doing a check first to see if the file exists before attempting to read in the contents of $site. This way, if the file already exists, you're not needlessly reading in the contents of $site.
$filename = "Service_delivery_report_" . date("Y-m-d",
time()). ".html";
$filepath = realpath("./") . "/views/sd_reports/" . $filename;
if (!is_file($filepath))
{
$site = "http://somesite.com/somepage";
if ($content = file_get_contents($site))
{
file_put_contents($filepath,
$content);
}
else
{
echo "Could not grab the contents of some site";
}
}
Use file_exists();
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
Then, if it doesn't exist, create a file with fopen();, like so:
$handle = fopen($filename, "w");
Try this
$file = file_get_contents(site_url('appraisal/createReport'));
$filename = 'Service_delivery_report_'.date('Y-m-d', time()).'.html';
if(! file_exists ($filename))
{
$f = fopen($filename, "w");
fwrite($f, $file);
fclose($f);
}
else
echo "file already exist";

Add number to fopen link if that file name already exists

Basically, I want to continue adding numbers each time the file already existed. So if $url.php exists, make it $url-1.php. If $url-1.php exists, then make it $url-2.php, and so forth.
This is what I already came up with, but I think it'll only work the first time.
if(file_exists($url.php)) {
$fh = fopen("$url-1.php", "a");
fwrite($fh, $text);
} else {
$fh = fopen("$url.php", "a");
fwrite($fh, $text);
}
fclose($fh);
I use while loops for scenarios like this.
$filename=$url;//Presuming '$url' doesn't have php extension already
$fn=$filename.'.php';
$i=1;
while(file_exists($fn)){
$fn=$filename.'-'.$i.'.php';
$i++;
}
$fh=fopen($fn,'a');
fwrite($fh,$text);
fclose($fh);
All that said, this direction of solutions does not scale well. You do not want to be checking over a 100 file_exists routinely.
Use a while loop with a counter variable $i. Keep incrementing the counter until file_exists() returns false. At that point, the while loop exits and you call fopen() on the filename with the current value for $i;
if(file_exists("$url.php")) {
$fh = fopen("$url-1.php", "a");
fwrite($fh, $text);
} else {
$i = 1;
// Loop while checking file_exists() with the current value of $i
while (file_exists("$url-$i.php")) {
$i++;
}
// Now you have a value for `$i` which doesn't yet exist
$fh = fopen("$url-$i.php", "a");
fwrite($fh, $text);
}
fclose($fh);
i was looking for something similar like this and extended Shad's answer for my needs. i need to make sure that a fileupload doesn't overwrite files which already exist on a server.
i know it's not "save" yet, cause it doesn't handle files without extension. but maybe it is a little help for somebody.
$original_filename = $_FILES["myfile"]["name"];
if(file_exists($output_dir.$original_filename))
{
$filename_only = substr($original_filename, 0, strrpos($original_filename, "."));
$ext = substr($original_filename, strrpos($original_filename, "."));
$fn = $filename_only.$ext;
$i=1;
while(file_exists($output_dir.$fn)){
$fn=$filename_only.'_'.$i.$ext;
$i++;
}
}
else
{
$fn = $original_filename;
}
<?php
$base_name = 'blah-';
$extension = '.php';
while ($counter < 1000 ) {
$filename = $base_name . $counter++ . $extension;
if ( file_exists($filename) ) continue;
}
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);

Categories