PHP function fopen() doesn't work

Hi. I was always using this code to check if the file exists and create it if not.

$daily = $_SERVER['DOCUMENT_ROOT']."names/".$datename.".txt";
if(!file_exists($daily))
{
	$datedir = date('F');
	$dirfile = "names/".$datedir;
	if(!is_dir($dirfile))
	{
	        mkdir($dirfile, 0755);
	}
	$fp = fopen($daily, "w");
	fclose($fp);
}

Suddenly it stoped working and i get warning:

fopen(/storage/ssd4/334/1098334/public_htmlnames/April/05.txt): failed to open stream: No such file or directory in /storage/ssd4/334/1098334/public_html/index.php

So the issue is that function fopen() can’t create new file in existing directory. I’ve already checked permissions in directory, there is no problem with that.

Try this

$daily = $_SERVER['DOCUMENT_ROOT']."/names/".$datename.".txt";
if(!file_exists($daily)){
	$datedir = date('F');
	$dirfile = "names/".$datedir;
	if(!is_dir($dirfile)){
	        mkdir($dirfile, 0755);
	}
	$fp = fopen($daily, "w");
	fclose($fp);
}

That code is actually same as my, i probably used wrong BB-code so tabulation symbols were deleted. Sorry for that.

It’s not the same, I actually added a / before names/

Unfortunately that doesn’t solve the problem. It seems like i got some restrictions because this code worked perfectly for a long time. Is that possible?

hey Can I see your whole code? (With where $datename came from)

Or can you give me your webaddress?

1 Like

Sure, here’s the full code.

$datename = date('F/d');
$daily = $_SERVER['DOCUMENT_ROOT']."/names/".$datename.".txt";
if(!file_exists($daily))
{
        $datedir = date('F');
        $dirfile = "names/".$datedir;
        if(!is_dir($dirfile))
        {
        	mkdir($dirfile, 0755);
        }
        $fp = fopen($daily, "w");
        fclose($fp);
}

Why not try using file_put_contents(); ?
http://php.net/manual/en/function.file-put-contents.php

Thank you for advice. I’ve tried using this function but i got same result. The file couldn’t be created.

$daily = $_SERVER['DOCUMENT_ROOT']."/names/".$datename.".txt";
if(!file_exists($daily)){
	$datedir = date('F');
	$dirfile = "names/".$datedir;
	if(!is_dir($dirfile)){
	        mkdir($dirfile, 0755);
	}
	file_put_contents($daily, "");
}

And the error is? :slight_smile:

No errors or even warnings after execution, but file is not created. I also tested this code with other directories and it didnt work.

Can you try creating it without variables interfering with the path?
Something like

file_put_contents("test.php","Hey!");

I was checking my code again and again and i accidentally found stupid code mistake. Thank you for help and sorry for taking up your time. Problem is solved.

1 Like