Rakesh
Rakesh

Reputation: 2790

PHP create text file on server

In my php application i want to create a error log in a text format so tried like this its working fine in my local machine

if(!$mail->Send())
{
 echo "Message could not be sent. <p>";
 echo "Mailer Error: " . $mail->ErrorInfo;
 $stringData = "Error Info: ".$mail->ErrorInfo."\t\t";
 $stringData .= "Email to reciepient \t Regnumber: ".$RegNo." \t  Apllicant Name: ".$ApplicantName." Failed --- end ----";


 $fp = fopen($_SERVER['DOCUMENT_ROOT']."/lib/email_errorlog.txt","wb");
 fwrite($fp,$stringData);
 fclose($fp);

 exit;
  }

i have already seen discussion in PHP Create and Save a txt file to root directory but its not working for me. The problem is, there is no error is showing but text file is not creating. Need to set any permission on the server?

Upvotes: 0

Views: 3944

Answers (2)

Vyktor
Vyktor

Reputation: 21007

You may check whether file (or rather parent directory) is writeable before trying to create file.

And according to php manual fopen():

Returns a file pointer resource on success, or FALSE on error.

So you could use this + $php_errormsg or get_last_error() to build correct file writing code:

$fp = fopen($_SERVER['DOCUMENT_ROOT']."/lib/email_errorlog.txt","wb");
if( $fp === false){
    // Notification about failed opening
    echo "Cannot open file: " + $php_errormsg; // Not that wise in production
    exit();
}

fwrite($fp,$stringData);
fclose($fp);
exit();

But with correct configuration all errors should be in error log.

Upvotes: 0

JvdBerg
JvdBerg

Reputation: 21866

You have to make sure that:

  • the folder /lib exists in the document root
  • the webserver process has permission to write to that folder.

If you create the folder with your ftp account, the webserver process will have no access. You can set permissions to 777, but then everyone has access. Best would be to set permission to 770 and make the group of the folder the webserver group id.

Upvotes: 2

Related Questions