![]() |
PHP File functions
Create a file
Write into a file Overwriting Read a file Upload a file Create a file: Before you start reading, please notice that I'm from Finland! :) Hey! At this tutorial you will learn a lot ! How to create a file, write into a file, read a file and upload a file with PHP! We will start at the creating a file! It's very simple! We will use functions called fopen and fclose. Code:
Code:
$Filehandle = fopen($File, 'w') or die("Can't create or open the file!"); (PS. Remember functions fopen and fclose) Write into a file: Now you know how to create / open and close the file, let's get into writing to file! Writing to file is useful way to eg. keep up on the chat log, purchase log or user register log. We will use fwrite function to write into a file! CODE: Code:
Remember to include the previous code ! Code:
$text_Data = "Hello! I just writed into a file with PHP ! Kinda cool!"; fwrite($FileHandle,$text_Data); Now we're using fwrite function, it uses the $FileHandle variable and writes the variable's ($text_Data) text into a text file! Now if you tried to write a couple times with this same code, you might notice that it overwrites the previous texts, because 'w' code always starts writing from the beginning of the file. Try to change code 'w' to 'a' and the writings will start at the end of the file and won't overwrite the previous texts! Read a file: Now you know how to create / open, write and close the file, It's time to learn how to read the file and show it in the web page! Code:
You might notice its the exactly the same code as we learned first (Creating / open the file). But now we changed the 'w' to 'r' ('r' = Read) ! So now the fopen function will read the variable's file ($File)! Upload a file: Uploading a file is a little more harder, because we are going to use HTML and PHP together and PHP code is little more harder. We will start at the creating a HTML upload FORM! Code:
action="upload.php" = When submit button is pressed it will lead us to upload.php page! enctype="multipart/form-data" = We will need this enctype for making our PHP functions working! input type="hidden" name="MAX_FILE_SIZE" value="100000" = This code makes us maxium file size which is 100KB. PS: Create a another file called "upload.php" Code:
Code:
if(move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) { the path of temporary file! With this function we're using if function, so if uploaded file can be moved to urfolder/ you will get message "Your file has been uploaded! Yay!" else you will get error message! |
All times are GMT -7. The time now is 07:49 PM. |
Powered by vBulletin Copyright © 2020 vBulletin Solutions, Inc.