file_put_contents append executes successfully but the file is not appended - php

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?

Related

file exists but I cannot open it using php

I can open and write in file using vim command but i cant open it using PHP
$myFile = "v.txt";
if(!file_exists($myFile)){
print 'File not found';
}else if(!$fh = fopen($myFile, 'w+')){
print 'Can\'t open file \n';}.
else{
print 'Success open file';
}
Do a
ls -l
on the directory that contains the file. Make sure the user that's running your web server has access read rights to the file

fopen() works, dio_open() doesn't?

Seeing some issues running fopen() when dio_open() is working just fine. Here's a test script I wrote to check the issue as it was appearing in a new installation I'm trying to get working.
<?php
echo "Current User: " . get_current_user() . "<br/>";
echo "UID: " . getmyuid() . "<br/>";
echo "GID: " . getmygid() . "<br/>";
echo "<br/>";
$foTest = fopen("test.txt","r");
echo fread($foTest,4);
$fd = dio_open('test.txt', O_RDONLY);
$read = dio_read($fd);
echo $read;
$file = dio_open('test.txt', O_WRONLY | O_CREAT);
?>
The script outputs the following:
Current User: infinitywhack UID: 1004 GID: 1002
test Warning: dio_open(): cannot open file test.txt with flags 0 and
permissions 0: No such file or directory in
/var/www/infinity.whacknet.com/public_html/test.php on line 9
Warning: dio_read() expects parameter 1 to be resource, boolean given
in /var/www/infinity.whacknet.com/public_html/test.php on line 10
Warning: dio_open(): cannot open file test.txt with flags 65 and
permissions 0: Permission denied in
/var/www/infinity.whacknet.com/public_html/test.php on line 12
This shows the user and group (infinitywhack:www) which is correct. The "test" output here is the content of the test.txt file, that is the code that is running with fopen(). The errors are only given by dio functions.
Here are the permissions for both files:
[root#death public_html]# ls -la test.*
-r-xr-xr-x. 1 infinitywhack www 342 May 12 23:36 test.php
-rwxrwxrwx. 1 infinitywhack www 5 May 12 23:06 test.txt
I've been scratching my head all night on this one, there's very little documentation on anything dio from what I have found. Very little saying what is needed here. The only thing I could think of was suExec but there aren't any directives in use that would cause this, although surely those same directives would fail for fopen as well if that were the case?
Any help here would be much appreciated!
I think STLMikey & Ahmet are on the right track.
Try dio_open(__DIR__ . DIRECTORY_SEPARATOR . 'test.txt', ...)
In this source code at least, dio_open makes no attempt to construct an absolute path. The filename parameter is passed to the operating system unchanged.
The No such file or directory & Permission denied errors are coming from the OS, not the dio library. So it seems likely your server is looking for test.txt in the wrong place.
firsty make sure your file is exist.
Also your php file permissions should be 0777 to create file
and you can add a folder to set permission "777" automaticly by this command
$folder=mkdir( "yourdirname", 0777);
And than you should try to understand the problem
$file="test.txt";
//maybe your server cannot find the root
// if it does not solve the problem write root file command
// $file=dirname(__FILE__).DIRECTORY_SEPARATOR."test.txt";
if (file_exists($file)) {
//its ok try to continue
} else {
echo "the text file is not exits !";
}

PHP file doesn't rewrite

I make a site map, and make it with php file, that generate it from mysql. I change host and now I have problem with writing into file. I can't understand something.
Here is my example:
<?php
$xml = 'bla bla xml'; //... some xml generating code
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/my_site_map.xml', 'w');
if($fp)
echo 'we opened it';
else
echo 'we failed';
$fwrite=fwrite($fp, $xml, strlen($xml));
if($fwrite==false)
echo "another fail";
fclose($fp);
echo "we done";
?>
The question is: my file my_site_map.xml have a permission 664 (rw-rw-r--), and I can't use this script if I open this php page from browser, so, if I try to do this I'll see: "we failed another fail we done"; But if I open this through crontab and see a log file, I can see this: "we opened it we done". I want exactly this but the main problem is that the file isn't have been rewritten. Why? And how can I fix this? Thanks.
My server is nginx not an Apache, didn't thought that this info will valuable
Well I don't have enough rep to comment so this will have to be an answer.
I'm going to take a stab in the dark and say the file is owned by your user or root, not the process that is running the webserver. Nor is the file owned by the group the webserver process is run under.
So either chown/chgrp the file to be owned by the apache(?!) process running, e.g. chown apache file or set the file to have write permissions to everyone, e.g. chmod 666 file
Don't chmod 777 as commented above unless it's an executable file and you want anyone to be able to run it. The 1st solution is a better practice than just giving anyone read access to a file.
Edit: In comment to the comments on the original answer above, if the file isn't an executable then don't give it 7 for any permisions. 6 is read/write and is suitable for a text file you are opening to write to (even 2 is if it comes to that).
Edit 2: Try catching any exceptions that your fopen function runs in a try catch block:
try {
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/my_site_map.xml', 'w');
} catch (Exception $e) {
echo "The error is" . $e->getMessage();
}
For PHP code here are the links to change it on the fly. You can change it to what ever make your edits then change it back as needed.
http://php.net/manual/en/function.chmod.php
http://php.net/manual/en/function.chown.php
http://php.net/manual/en/function.chgrp.php
Examples are included on each link with the documentations. Find the permissions that works best for what your doing. There isn't a one size fits all for permissions since it really depends on your end product (web app, page, what ever).

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?
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.

PHP move_uploaded_file() error?

I using following code and it is successfully uploading files on my local machine. It is showing "Successfully uploaded" on my local machine.
// Upload file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . "myFile.txt" );
if( $moved ) {
echo "Successfully uploaded";
} else {
echo "Not uploaded";
}
But when I used this code on my online server then it is not uploading file and just showing message "Not uploaded".
How can I know that what is the problem and how can I get the actual problem to display to the user ?
Edit the code to be as follows:
// Upload file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . "myFile.txt" );
if( $moved ) {
echo "Successfully uploaded";
} else {
echo "Not uploaded because of error #".$_FILES["file"]["error"];
}
It will give you one of the following error code values 1 to 8:
UPLOAD_ERR_INI_SIZE =
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE =
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL =
Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE =
Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR =
Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE =
Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION =
Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.
Try this:
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/images/';
if (is_dir($upload_dir) && is_writable($upload_dir)) {
// do upload logic here
} else {
echo 'Upload directory is not writable, or does not exist.';
}
This will instantly flag any file permission errors.
Check that the web server has permissions to write to the "images/" directory
How can I know that what is the problem
Easy. Refer to the error log of the webserver.
how can I get the actual problem to display to the user ?
NEVER do it.
An average user will unerstand nothing of this error.
A malicious user should get no feedback, especially in a form of very informative error message.
Just show a page with excuses.
If you don't have access to the server's error log, your task become more complicated.
There are several ways to get in touch with error messages.
To display error messages on screen you can add these lines to the code
ini_set('display_errors',1);
error_reporting(E_ALL);
or to make custom error logfile
ini_set('log_errors',1);
ini_set('error_log','/absolute/path/tp/log_file');
and there are some other ways.
but you must understand that without actual error message you can't move. It's hard to be blind in the dark
move_uploaded_file() will return:
FALSE if file name is invalid
FALSE and issue a warning in the error log if the apache process does not have read/write permissions to source or destination directories
PHP Error Log
My php error log was at: /var/log/httpd/error_log and had these errors:
Warning: move_uploaded_file(images/robot.jpg): failed to open stream: Permission denied in /var/www/html/mysite/mohealth.php on line 78
Warning: move_uploaded_file(): Unable to move '/tmp/phpsKD2Qm' to 'images/robot.jpg' in /var/www/html/mysite/mohealth.php on line 78
move_uploaded_file() tries to move files from a temporary directory to a destination directory. When apache process tried to move files, it could not read the temporary or write to the destination dir.
Find which user is running Apache (Web Server)
Check which user is running the apache service by this command: ps aux | grep httpd. The first column is the user name.
Check Read Permission at Temporary Dir: Your can find the path to your temp dir by calling echo sys_get_tmp_dir(); in a php page. Then on the command line, issue ls -ld /tmp/temporary-dir to see if the apache user has access to read here
Check Write Permission at Destination Dir: issue ls -ld /var/www/html/destination-directory to see if the apache user has access to write here
Add permissions as necessary using chown or chgrp
Restart Apache using sudo service httpd restart
Do you checks that file is uploaded ok ? Maybe you exceeded max_post_size, or max_upload_filesize. When login using FileZilla you are copying files as you, when uploading by PHP wiritng this file is from user that runs apache (for exaplme www-data), try to put chmod 755 for images.
or run suexec and never have to change permissions again.
In php.ini search for upload_max_filesize and post_max_size. I had the same problem and the solution was to change these values to a value greater than the file size.
Please check that your form tag have this attribute:
enctype="multipart/form-data"
$uploadfile = $_SERVER['DOCUMENT_ROOT'].'/Thesis/images/';
$profic = uniqid(rand()).$_FILES["pic"]["name"];
if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
{
$moved = move_uploaded_file($_FILES["pic"]["tmp_name"], $uploadfile.$profic);
if($moved)
{
echo "sucess";
}
else
{
echo 'failed';
}
}
On virtual hosting check your disk quota.
if quota exceed, move_uploaded_file return error.
PS : I've been looking for this for a long time :)
Please check permission "images/" directory
I ran into a very obscure and annoying cause of error 6.
After goofing around with some NFS mounted volumes, uploads started failing.
Problem resolved by restarting services
systemctl restart php-fpm.service
systemctl restart httpd.service

Categories