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?
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.
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.
Related
I am trying to log Parsing errors to a log file. Here's the snippet of code that is used to write to the log file.
if(!array_key_exists(1,$match))
{
$result = file_put_contents("$mapdir/$log_fname","\n$link",FILE_APPEND | LOCK_EX);
if($result===False) echo "Write failed";
else echo "$result bytes written to $mapdir/$log_fname - ";
echo "Link error: $link\n";
return False;
}
This returns-
104 bytes written to configs/test/log - Link error: FR3.SYD - 10GigabitEthernet5/1 - TRDU PUBLICP|10GE|PIPE NETWORKS|18398|LLNW-00004034 [EQX: NETPROV-981]
Which means that the contents were successfully written but when I open the file written to by vi command I see the same file. No content has been added.
Notes-
The file I am writing to exists.
Permissions for all have been set to 777 using chmod -R
I am also writing to several config files in the same location with this script successfully using file_put_contents.
Then why do you think I am facing this problem now with the log file?
The PHP file_put_contents function works perfectly fine when the file exists. If the file does not exist I receive the error "failed to open stream: No such file or directory".
$file = '../templates/stuff.xml';
if (!file_exists($file)) {$file = '../'.$file;}
$var['xhtml'] = $_POST['post_xhtml'];
$file_contents = serialize($var);
file_put_contents($file,$file_contents);
I tried the same thing with fopen and fwrite using the correct flags (w, w+ and tried the others) yet still had the same problem: if the file already existed it worked just fine, otherwise it would give me the same error message.
I know the file path is correct. I'm using Windows 7 for local development.
When the file doesn't exist, you are prepending ../ to the path, thus you are trying to write to:
../../templates/stuff.xml
Are you sure that the folder ../../templates exists (and that PHP can write to it)?
Before you write to a file, you need to check that the folder exists. Try using is_dir():
if(is_dir(dirname($file))){
file_put_contents($file, $file_contents);
}
I ran into a really bizarre problem. I am trying to perform writing to file using fopen().
This is what I tried in writetofile.php:
$fw = fopen('/test.txt', 'w');
fwrite($fw, 'hello world' . "\r\n");
fclose($fw);
This is the error I keep getting:
Warning: fopen(/test.txt):
failed to open stream: Permission denied in C:\inetpub\wwwroot\writetofile.php on line 41
Warning: fwrite() expects parameter 1 to be resource, boolean given...
I am 100% sure I have permissions to the server. I am the Administrator. Furthermore, I temporarily gave full permissions to everyone. I even tried running the php script locally, directly from the server using localhost. I am not using apache, I am using IIS. I tried restarting IIS after modifying permissions. I am not running php in safe mode.
Any idea on what might be causing this issue?
/test.txt would be a file in the ROOT directory of your filesystem, where user accounts generally do NOT have write privileges (unless you're running this code as root). This is especially true of PHP running under the webserver's user account.
You probably want just test.txt (no leading slash)` which will try to put the file into the script's "current working directory" - usually the same directory the script itself is in.
1- when you rollout website, delete all logs folder names
2- inside the code create folder name as below and create the logs insides
3- write at top of file. (during init the web)
$ClientUserName = gethostbyaddr($_SERVER['REMOTE_ADDR']);
function Data_Log($dataline)
{
global $ClientUserName;
$dir = 'UserInputLog' ;
$fileName = $ClientUserName. '_ServerWebLog.txt';
if(is_dir($dir) === false)
mkdir($dir);
$fileName = $dir. '\\'.$fileName;
$myfile = fopen($fileName, "a") or die("Unable to open file!");
fwrite($myfile, "$dataline\r\n");
fclose($myfile);
}
I did a script, which has to load a file from a ftp-server then parses it. The code relies on tempname to store the temporarily store the ftp-file. On my developement server (with php 5.3.10), this works flawlessly, however on the client machine (with php 5.2.17) it does not and gives me:
Warning: ftp_rawlist() [function.ftp-rawlist]: Unable to create temporary file. Check permissions in temporary files directory.
Can someone give me a clue what i could do?
(I am a little weak on the possibiities of php)
I used this code:
define ("LOCALFILE",tempnam('/tmp', 'data-'));
define ("USER","myusername");
define ("PASS","mypassword");
define('SERVER', "ftpserver.com");
define ("DIR","/path/");
function getFTPFile(){
// connect
if(!($conn_id = #ftp_connect(SERVER))){
Error::throwOne("Could not connect to ".SERVER);
};
// login
if(!($login_result = #ftp_login($conn_id, USER, PASS))){
Error::throwOne("LOGIN INCORRECT! user:".USER." pass:".PASS);
};
// try to change the directory to somedir
if (!ftp_chdir($conn_id, DIR)) {
Error::throwOne("Couldn't change directory\n");
};
if(!($a = ftp_rawlist($conn_id, '-1t'))){
Error::throwOne("Couldn't get ftp_rawlist\n");
};
$server_file=($a[0]);
if (!ftp_get($conn_id, LOCALFILE, $server_file, FTP_BINARY)) {
Error::throwOne("Couldn't get file\n");
};
ftp_close($conn_id);
};
The error looks to me like system-generated and have nothing to do with your tmpname. Internally, FTP stores the file in its own temp file in temp filename in standard temp directory up to the point when it's downloaded - then moves it to the location you specified.
Try putting this code before your download code:
$tmpdir = sys_get_temp_dir();
echo "Temp dir: $tmpdir\n";
echo is_writable($tmpdir) ? "Temp dir is writable" : "Temp dir is not writable";
This will tell you if you have permissions to write to the system temp dir. I further suggest that you use this $tmpdir variable instead of hardcoding "/tmp" in your code.
I found the issue.
Since my hoster does not like the /tmp directory ( who would blame them )
i need to first set
putenv('TMPDIR=/the tmp-dir my provider gave me');
which then works with tempname
I found this occurred on Windows Server 2016 - and it was because my %TEMP% environment variable pointed to a subdirectory that didn't exist for whatever reason.
It did point to the correct one when I ran it as Administrator, though.
i want to create a .txt file with the 777 permission for file creation i am using the following code
if(file_exists($myFile) == true)
{
$err = "File Already Exist in The usrlogactity. Try Another Username";
}
else
{
$fh = fopen($myFile, 'w') or die("can't open file");
}
$file = "usrlogactity/$myFile";
$ftp_server="02.79.103.130";
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, "use1234", "pass123");
// try to chmod $file to 644
if (ftp_chmod($conn_id, 0777, $file) !== false)
{
//echo "$file chmoded successfully to 777\n";
}
else
{
//echo "could not chmod $file\n";
}
// close the connection
ftp_close($conn_id);
if i execute this code in server it create the file with the 644 permission ,
but gives error. how to i create the .txt file with the 777 permissiom please guide me
The error is
No such file or directory in usrlogactity/$myFile on line 13
To change local file permissions you have to use PHP function chmod(), not using ftp for this
Doing it via FTP you're trying to access this file with ftp user, not www user, and, therefore, no success.
And, you see, how it's important to post your code, not to tell about it? ;-)
it depends on the server if your scripts are allowed to and why do you need 777 for a text file you don't execute a text file you read its 644 is all you need,
but permissions should not be changed by a script different configurations leads to completely different results,
Some servers are idiots and run Apache as root, which mean php writes a file that root owns,
Some use suExec and then your login to your account owns the file
others use Apache user to control your file
so your script could work on one and not on another if you moved the site due to the file becoming unreadable
Allso check safemode on your php install