The actual file writing procedures do not necessarily call the fwrite function right away. Instead, the file path should be declared first: $filepath='/opt/lampp/htdocs/phpformtotextfilebasic/textfolder/ This should be relative to the root directory. or else the error “Could not open file!” will be displayed. This is also the output of: <?php echo $_SERVER['SCRIPT_FILENAME']; ?> If you do not know the full relative path with respect to the root, create a PHP file, name it path.php and upload it to the directory where you need to determine the path. After that, view path.php in the web browser and there will be revealed the full path relative to the root. In Linux web hosting, it might look like this: /home/www/php-developer.org/formtotextproject/textfolder/writethistextfile.txt If you use (not a full path): $filepath='/phpformtotextfilebasic/textfolder/writethistextfile.txt'; It will display an error that says fopen could not open the file. Also, be careful with the spelling of the path name, as any error wil also lead to the “Could not open the file” error. Now that the path has been set, you are ready to open a file using a file handler: $filehandler= fopen($filepath, 'w') or die('ERROR: Could not open file!'); Since this is a file writing tasks, 'w' is used to signify the “writing” mode. By default, if writethistextfile.txt is not yet created, fopen will create and prepare this file for writing. Finally, now that the file has been opened and is ready for writing, the actual text contents from the web form will be written to the file using the command: fwrite($filehandler,$textinputs) or die('ERROR: Could not write to file'); The file handler can be closed after the writing tasks: fclose($filehandler); You can download the complete script discussed above here. If you would like to test this, you can enter any text you like and then click the “Write this text to a text file” button. Go to the textfolder directory and open the file; you should see the text you have just submitted. Sample screen shot:
blog comments powered by Disqus |
|
|
|
|
|
|
|