Creating a txt file using php in linux - php

We have few fields in the HTML page and this is being written into a file using php.
The file has the data, however, running a bash script which takes this file with a .txt as extension is not working.
When the file is opened and re-saved manually the bash script will work properly!
I've tried changing the permissions of the file but the bash script is still not using this file. Any help on this is greatly appreciated.
PHP Script:
$name = "test.txt";
$handle = fopen($name, "w");
fwrite($handle, "my message");
fclose($handle);
Bash Script:
INPUT="$1"
OLDIFS=$IFS
IFS=,
[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
while read message number ; do
echo $message # or whaterver you want to do with the $line variable
#j=$[$(line)]
echo $number
echo "$message" | gnokii --sendsms $number --smsc $SMSC
done < $INPUT
IFS=$OLDIFS

You probably want to use fclose($handle) rather than unlink()
Edit OK then, "Because..."
fclose($handle) closes the file referenced by the handle: $handle
unlink() takes a file path string as a parameter, rather than a resource.
If used as intended, unlink() will actually delete the file.

unlink() as mentioned would delete the file. Just created a plain script like this
<?php
$name = "/var/www/test.txt";
$handle = fopen($name, "w");
fwrite($handle, "test,9944");
fclose($handle);
?>
This script works f9 with storing the data. But running bash script on this with the file input as test.txt does nothing. But again opening and saving with the same file name and it works.

finally got the answer its the end of file that is missing in text file that is created by php. anyway thank you all for contributing.

Related

PHP create file in same directory as script

$content = "some text here";
$fp = fopen("myText.txt","w");
fwrite($fp,$content);
fclose($fp);
The above code creates a file in the folder where the PHP script is present. However when the script is called by Cpanel Cron then file is created in home directory.
I want file to be created in the same folder where the php script is present even if its run by cron. How to do that ?
Try using __DIR__ . "/myText.txt" as filename.
http://php.net/manual/en/language.constants.predefined.php
Try something like this, using the dirname(__FILE__) built-in macro.
<?php
$content = "some text here";
$this_directory = dirname(__FILE__);
$fp = fopen($this_directory . "/myText.txt", "w");
fwrite($fp, $content);
fclose($fp);
?>
__FILE__ is the full path of the currently running PHP script. dirname() returns the containing directory of a given file. So if your script was located at /mysite.com/home/dir/prog.php, dirname(__FILE__) would return...
/mysite.com/home/dir
Thus, the appended "./myText.txt" in the fopen statement. I hope this helps.

Save the console text into a txt file? (PHP)

actual I finished writing my program. Because it is only a plugin and it runs on a external server I still want to see if I get some errors or something else in the console.
I wrote every console input with echo ...;. My question now is if it is possible to get the text of the console?
Because then I could easily safe it in a .txt file and could get access to it from the web :) - Or is there another way to get the console text?
I could probably just say fwrite(...) instand of echo ...;. But this will cost a lot of time...
Greetings and Thank You!
An alternative that could be usefull on windows would be to save all the output buffer to a txt, first check your php configuration for the console app implicit_flush must be off then
<?php
ob_start(); //before any echo
/** YOUR CODE HERE **/
$output = ob_get_contents(); //this variable has all the echoes
file_put_contents('c:\whatever.txt',$output);
ob_flush(); //shows the echoes on console
?>
If your goal is to create a text file to access, then you should create a text file directly.
(do this instead of echoing to console)
$output = $consoleData . "\n";
$output .= $moreConsoleData . "\n";
(Once you've completed that, just create the file:)
$file = fopen('output.txt', 'a');
fwrite($file, $output);
fclose($file);
Of course, this is sparse - you should also check that the file exists, create it if necessary, etc.
For console (commando line interface) you can redirect the output of your script:
php yourscript.php > path-of-your-file.txt
If you haven't access to a command line interface or to edit the cronjob line, you can duplicate the starndar output at the begining of the script:
$fdout = fopen('path-to-your-script.txt', 'wb');
eio_dup2($fdout, STDOUT);
eio_event_loop();
fclose($fdout);
(eio is an pecl extension)
If you are running the script using the console (i.e. php yourscript.php), you can easily save the output my modifying your command to:
php yourscript.php > path/to/log.txt
The above command will capture all output by the script and save it to log.txt. Change the paths for your script / log as required.

how to create a php file using another php file inside your webhost

I've created a php file that creates another php file,
heres the code:
if (isset($_POST["Submit"])) {
$name=$_POST['name'];
$string = '<?php
echo "'. $_POST["message"]. '";
?>
';
$fp = fopen("$name.php", "w");
fwrite($fp, $string);
fclose($fp);
}
it successfully created a php file using xampp in my local machine,
but when i upload it to my webhosting site, everytime i click submit, it doesnt create any file i written.
I dont get what is wrong with it,
somebody said that i need to connect it to my ftp server,
but i dont get it.
Advance thanks guys for the help.
Check your rigths on a dir where you want to save the file. It must be 664.
I think you have 3 things to solve here.
1) File permission
2) Rewriting a file
3) I thing there is an error on your line with $string because you are already in a php code
Try this
<?php
//If the form is submited
if (isset($_POST["Submit"]))
{
//we parse the informations
$name=addslashes($_POST['name']);
$string = addslashes($_POST["message"]);
//We will recreate the file even if it was existing
$fp = fopen("$name.php", "w+");
fwrite($fp, $string);
fclose($fp);
//We give access permission to the file
chmod("$name.php", 0777);
}
?>
And also if you are creating the file in a directory, use your ftp software like FileZilla to connect to your ftp and right click on the directory and click on Chmod. Make a Chmod 0777 on that directory. And everything should work fine.
Submit verification
Now if still it does not work, you can search bit by bit for the error by creating a file name test.php with this code
<?php
//we parse the informations
$name='my_one_file';
$string = '<h1>It is working<h1>';
//We will recreate the file even if it was existing
$fp = fopen("$name.php", "w+");
fwrite($fp, $string);
fclose($fp);
//We give access permission to the file
chmod("$name.php", 0777);
echo "<a href='$name.php' target='_blank'> <h1> $name.php</h1> </a>";
?>
And then you launch yourwebsite/test.php in your browser. If it works you should have a file name my_one_file.php on your server. If it shows a link then the problem is with your if (isset($_POST["Submit"])). Meaning we have to cross check your html form.
Touch Verification
Finaly if it is still not working then we can verify if the file needs to be created first on your server before being modified like some server do.
For that you will still create a test.php file with the following code
<?php
$name='my_one_file';
$string = 'My message';
touch("$name.php");
//We will recreate the file even if it was existing
$fp = fopen("$name.php", "w+");
fwrite($fp, $string);
fclose($fp);
//We give access permission to the file
chmod("$name.php", 0777);
echo "<a href='$name.php' target='_blank'> <h1> $name.php</h1> </a>";
?>
And then lauch yourwebsite/test.php. If it works you should have a file name my_one_file.php on your server.

PHP fwrite() not working

I'm writing a function in php, client side I have a canvas image which I use toDataUrl() along with a file name to save the image on the server. The here's the code:
<?php
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$data = json_decode($imageData, true);
$file = $data["file"];
$image = $data["data"];
$filteredData=substr($image, strpos($image, ",")+1);
$unencodedData=base64_decode($filteredData);
$fp = fopen( 'image/' . $file , 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
?>
The thing is that this code works. And for two out of three of the pages I used it on it works fine. The problem is when I copy and pasted it a third time to implement it again, for some reason the file is made on the server except that no data get's written into the file. I don't think it's a problem client side because I write in a debug alert message in the javascript and a debug echo into the PHP and both are able to print out the data fine. I made this short debug file:
<?php
$fp = fopen('data.txt', 'wb');
if(is_writable('data.txt')){
echo "file is writable<br>";
}
if(fwrite($fp, 'test') == FALSE){
echo "failed to write data<br>";
}
fclose($fp);
?>
And the output is
file is writable
failed to write data
I've tried using chmod and setting everything, the folder, the text file before I write to it to 0777 and I still get the same result; the file is made but no data is written into it. Is there anything I'm missing or any other approaches that might help. I haven't found anything on google and am still baffled as to why the same code worked exactly as expected twice before suddenly stopping for no apparent reason.
Thanks in advance.
I know this is an old post, but I had a very similar problem and found a solution (for me at least)! I ran out of disk space on my server, so it could create a 0 byte file, but wouldn't write to it. After I cleared out some space (deleted a 13gb error.log file) everything started working again as expected.
If fopen works but fwrite mysteriously doesn't, check your disk space. 'df -h' is the command to check disk space on a linux server.
instead of $fp = fopen('data.txt', 'wb'); give $fp = fopen('data.txt', 'w'); and try
Changed "wb" to "w"
When you write $fp = fopen('data.txt', 'w'); for your domain website.com having root at /var/www/website/ and if the php file is located at /var/www/website/php/server/file/admin.php or something similar, it will actually create a file at /var/www/website/data.txt
Try giving absolute path or path relative to your domain root to create files like,
$fp = fopen('php/server/file/data.txt', 'w');
Try the find command to see if the file is created anywhere else in the folder directory by using the following in Ubuntu,
find /var/www/website/ -name 'data.txt'
I had this issue, probably can help you solve if you have similar issue.

Php fopen write in css file -> file empty

i have this following php code :
$filename = '/front/style.css';
$cssfile='#h1{font-size:12px}';
if($id_file=fopen($filename, "w+"))
{
echo'file exist';
$id_file=fopen($filename, "w+");
flock($id_file,1);
fwrite($id_file,$cssfile);
flock($id_file,3);
fclose($id_file);
}
else
{
echo "file don t exist";
}
My file is empty but with space.
My file exist and it s writable.
I have nothing in my apache logs.
I m using Mamp with php 5.3.2.
Any ideas ?
Thx
A few mistakes I can see are:
You are using fopen to check if a file exists. That does not work. With the w+ mode PHP will try to create the file if it does not exist. Use the file_exits function to check the existence of a file.
You are opening the same file twice.
Also use PHP constants(LOCK_SH, LOCK_UN) for the second argument of flock. That will make your program more readable.
Updated
Have you checked if its writing to a different directory than you expect? Check your path to see where it defaults to, or even just do a search for the file and see where else it turns up. getcwd() will show what the current working dir is.
Have you checked the return value of fwrite to see if the write is actually working? If fwrite is successful, then try read the file in the code using the same $id_file and see if there is anything there while the program is still running.
You are calling fopen twice. w+ truncates the file and you are writing to the 2nd $id_file so my guess is that its being truncated when the 1st $id_file is being closed.
You can use this approach if your file empty after using fopen w+ option.
// only read
$filename = '/path/to/blah.txt';
$myfile = fopen($filename, "r");
$mydata = fread($myfile, filesize($filename));
$mynewdata = $mydata + 'abc';
fclose($myfile);
// only write
$myfile = fopen($filename, "w");
fwrite($myfile, $mynewdata);
fclose($myfile);

Categories