0

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);
1

4 Answers 4

2
if(! file_exists ($filename))
  {
  $fp = fopen($filename, 'w');
  fwrite($fp,  $file);
  fclose($fp);
  }
Sign up to request clarification or add additional context in comments.

Comments

1

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";
    }
}

Comments

0

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");

Comments

0

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";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.