Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Wednesday, June 29, 2016

PHP File Append

So far we have learned how to open, close, read, and write to a file. However, the ways in which we have written to a file so far have caused the data that was stored in the file to be deleted. If you want to append to a file, that is, add on to the existing data, then you need to open the file in append mode.

PHP - File Open: Append

If we want to add on to a file we need to open it up in append mode. The code below does just that.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, a);

If we were to write to the file it would begin writing data at the end of the file.

PHP - File Write: Appending Data

Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, a) or die("cant open file");
$stringData = "New Stuff 1 ";
fwrite($fh, $stringData);
$stringData = "New Stuff 2 ";
fwrite($fh, $stringData);
fclose($fh);

You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.

The contents of the file testFile.txt would now look like this:

Contents of the testFile.txt File:

Floppy Jalopy
Pointy Pinto
New Stuff 1
New Stuff 2

PHP - Append: Why Use It?

The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have a log of some sort. These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed on the machine.
A log is basically used to document events that occur over a period of time, rather than all at once. Logs: a perfect use for append!

PHP File Upload

A very useful aspect of PHP is its ability to manage file uploads to your server. Allowing users to upload a file to your server opens a whole can of worms, so please be careful when enabling file uploads.

PHP - File Upload: HTML Form

Before you can use PHP to manage your uploads, you must first build an HTML form that lets users select a file to upload. See our HTML Form lesson for a more in-depth look at forms.

HTML Code:

<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>

Here is a brief description of the important parts of the above code:

  • enctype="multipart/form-data" - Necessary for our to-be-created PHP file to function properly.
  • action="uploader.php" - The name of our PHP page that will be created, shortly.
  • method="POST" - Informs the browser that we want to send information to the server using POST.
  • input type="hidden" name="MA... - Sets the maximum allowable file size, in bytes, that can be uploaded. This safety mechanism is easily bypassed and we will show a solid backup solution in PHP. We have set the max file size to 100KB in this example.
  • input name="uploadedfile" - uploadedfile is how we will access the file in our PHP script.

Save that form code into a file and call it upload.html. If you view it in a browser it should look like this:

Display:



Choose a file to upload:



After the user clicks submit, the data will be posted to the server and the user will be redirected to uploader.php. This PHP file is going to process the form data and do all the work.

PHP - File Upload: Whats the PHP Going to Do?

Now that we have the right HTML form we can begin to code the PHP script that is going to handle our uploads. Typically, the PHP file should make a key decision with all uploads: keep the file or throw it away. A file might be thrown away from many reasons, including:

  • The file is too large and you do not want to have it on your server.
  • You wanted the person to upload a picture and they uploaded something else, like an executable file (.exe).
  • There were problems uploading the file and so you cant keep it.
This example is very simple and omits the code that would add such functionality.

PHP - File Upload: uploader.php

When the uploader.php file is executed, the uploaded file exists in a temporary storage area on the server. If the file is not moved to a different location it will be destroyed! To save our precious file we are going to need to make use of the $_FILES associative array.

The $_FILES array is where PHP stores all the information about files. There are two elements of this array that we will need to understand for this example.

  • uploadedfile - uploadedfile is the reference we assigned in our HTML form. We will need this to tell the $_FILES array which file we want to play around with.
  • $_FILES[uploadedfile][name] - name contains the original path of the user uploaded file.
  • $_FILES[uploadedfile][tmp_name] - tmp_name contains the path to the temporary file that resides on the server. The file should exist on the server in a temporary directory with a temporary name.
Now we can finally start to write a basic PHP upload manager script! Here is how we would get the temporary file name, choose a permanent name, and choose a place to store the file.

PHP Code:

// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES[uploadedfile][name]);
$_FILES[uploadedfile][tmp_name];

NOTE: You will need to create a new directory in the directory where uploader.php resides, called "uploads", as we are going to be saving files there.

We now have all we need to successfully save our file to the server. $target_path contains the path where we want to save our file to.

PHP - File Upload: move_uploaded_file Function

Now all we have to do is call the move_uploaded_file function and let PHP do its magic. The move_uploaded_file function needs to know 1) The path of the temporary file (check!) 2) The path where it is to be moved to (check!).

PHP Code:

$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES[uploadedfile][name]);
if(move_uploaded_file($_FILES[uploadedfile][tmp_name], $target_path)) {
echo "The file ". basename( $_FILES[uploadedfile][name]).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}

If the upload is successful, then you will see the text "The file filename has been uploaded". This is because $move_uploaded_file returns true if the file was moved, and false if it had a problem.
If there was a problem then the error message "There was an error uploading the file, please try again!" would be displayed.

PHP - File Upload: Safe Practices!

Note: This script is for education purposes only. We do not recommend placing this on a web page viewable to the public.

These few lines of code we have given you will allow anyone to upload data to your server. Because of this, we recommend that you do not have such a simple file uploader available to the general public. Otherwise, you might find that your server is filled with junk or that your servers security has been compromised.

We hope you enjoyed learning about how to work with uploading files with PHP. In the near future we will be adding an advanced lesson that will include more security and additional features!



Thursday, June 23, 2016

Creating a file based log system

If we have a website we would certainly want to know the impressions of our website visitors. 

In addition to knowing about information of visitors, a log file is also useful to help analyse the security.

I will go directly to explain the log system file in PHP script: 

<?php 
// checking the bowsers type 
$agent = $_SERVER [HTTP_USER_AGENT]; 

// * checking where the script is executed from -- GET (URL) 
$uri = $_SERVER [REQUEST_URI]; 

// * checking visitors IP 
$ip = $_SERVER [REMOTE_ADDR]; 

/ * checking where the script is referred from 
$ref = $_SERVER [HTTP_REFERER]; 

// * checking visitors proxy
$original = $_SERVER [HTTP_X_FORWARDED_FOR]; 

// * checking visitors connection 
$via = $_SERVER [HTTP_VIA]; 

// * variable date 
$dtime = date (r); 

// * note if  visitors use transparent Proxy 
// * Then the $_SERVER [HTTP_X_FORWARDED_FOR] will display the visitors IP 
// * otherwise $_SERVER [ REMOTE_ADDR] will display the Proxy 
// * For clear about Proxy i will explain in another tutorial 

// * This is a description of variable entry_line: 
$entry_line = "Time: $dtime | Original IP: $ip | Browser: $agent | URL: $uri | referrer: $ref | Proxy: $original | Connection: $via 
";   // * <- Attention! This must be a new line or you press enter to create a new line 

/ * "fopen ()" function for opening files, "a" is the most important.!, 
/ * This works if the file "trace.txt" does not exist in the server then PHP will create 
$fp = fopen ( "trace.txt", "a"); 

/ /* "fputs ()" function for writing into the log file 
fputs ($fp, $entry_line); 

// * "fclose ()" function to close the file 
fclose ($fp); 

?> 

This file based log system using php function is pretty useful instead of using mysql connection

Saturday, June 18, 2016

File Upload and View With PHP and MySQL

We already have a Simple File Uploading tutorial in this blog and now This tutorial demonstrates how you can upload a files using PHP and Store uploaded file into the MySQL Database . With PHP it's easy to upload any files that you want to the server, you can upload MP3 , Image , Videos , PDF etc... files, this will also help you that how can you fetch uploaded files from MySQL Database and view them on Browser, so let's take a look.
File Upload and View with PHP and MySQL
Read more »

Wednesday, June 15, 2016

File Uploader PHP Script

What is File Uploader PHP Script?


UPU (UGiA PHP Uploader) is a file uploader which allows you upload files to web server with no size limit in php. With UPU, you can monitor the uploading status with a progress bar. UPU supports multiple files upload mixed with common html form elements.

Download File Uploader PHP Script

Tuesday, June 7, 2016

PHP File Read

My apologies for taking so long to actually get to the point where you get information from files. In this lesson we will teach you how to read data from a file using various PHP functions.

PHP - File Open: Read

Before we can read information from a file we have to use the function fopen to open the file for reading. Heres the code to read-open the file we created in the PHP File Write lessons.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, r);

The file we created in the last lesson was named "testFile.txt". Your PHP script that you are writing should reside in the same directory as "text.txt". Here are the contents of our file from File Write.

testFile.txt Contents:

Floppy Jalopy Pointy Pinto

Now that the file is open, with read permissions enabled, we can get started!

PHP - File Read: fread Function

The fread function is the staple for getting data out of a file. The function requires a file handle, which we have, and an integer to tell the function how much data, in bytes, it is supposed to read.
One character is equal to one byte. If you wanted to read the first five characters then you would use five as the integer.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, r);
$theData = fread($fh, 5);
fclose($fh);
echo $theData;

Display:

Flopp

The first five characters from the testFile.txt file are now stored inside $theData. You could echo this string, $theData, or write it to another file.

If you wanted to read all the data from the file, then you need to get the size of the file. The filesize function returns the length of a file, in bytes, which is just what we need! The filesize function requires the name of the file that is to be sized up.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, r);
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;

Display:

Floppy Jalopy Pointy Pinto

Note: It is all on one line because our "testFile.txt" file did not have a
tag to create an HTML line break. Now the entire contents of the testFile.txt file is stored in the string variable $theData.


PHP - File Read: gets Function

PHP also lets you read a line of data at a time from a file with the gets function. This can or cannot be useful to you, the programmer. If you had separated your data with new lines then you could read in one segment of data at a time with the gets function.

Lucky for us our "testFile.txt" file is separated by new lines and we can utilize this function.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, r);
$theData = fgets($fh);
fclose($fh);
echo $theData;

testFile.txt Contents:

Floppy Jalopy

The fgets function searches for the first occurrence of " " the newline character. If you did not write newline characters to your file as we have done in File Write, then this function might not work the way you expect it to.

Saturday, June 4, 2016

PHP File Truncate

As we have mentioned before, when you open a file for writing with the paramater w it completely wipes all data from that file. This action is also referred to as "truncating" a file. Truncate literally means to shorten.

PHP - File Open: Truncate

To erase all the data from our testFile.txt file we need to open the file for normal writing. All existing data within testFile.txt will be lost.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, w);
fclose($fh);

PHP - Truncate: Why Use It?

Truncating is most often used on files that contain data that will only be used for a short time, before needing to be replaced. These type of files are most often referred to as temporary files.
For example, you could create an online word processor that automatically saves every thirty seconds. Every time it saves it would take all the data that existed within some HTML form text box and save it to the server. This file, say tempSave.txt, would be truncated and overwritten with new, up-to-date data every thirty seconds.

This might not be the most efficient program, but it is a nice usage of truncate.


Wednesday, May 25, 2016

PHP File Delete

You know how to create a file. You know how to open a file in an assortment of different ways. You even know how to read and write data from a file!

Now its time to learn how to destroy (delete) files. In PHP you delete files by calling the unlink function.

Sunday, May 15, 2016

Simple File Uploading With PHP

In this tutorial you are going to learn , How to upload files using PHP and moves uploaded files into the specified files folder, Using some PHP global variable like $_FILES['controller_name'] , move_uploaded_files() , you can move uploaded file into the folder it's easy, for that we have to create html form and embed few lines of PHP code into the single file, let's have a look.
Simple file uploading Script with PHP
Read more »

Wednesday, May 11, 2016

How to Remove php html Extensions with htaccess File

hello friends, in today's tutorial you will learn how to remove .php and .html file extensions from URLs using .htaccess file, you might have seen that some sites did not displays .php or .html extension even they are created in core, normal php, you can also do the same for your site or projects using .htaccess file, recently i was working on my project and i wanted to remove the extensions from my website, in order to make the URLs more user friendly. so i was thinking why not to share this simple .htaccess tip with you, well this was first .htaccess post on my blog and i will post some more tips and tutorials on this blog stay tuned, let's have a look.
How to Remove .php, .html Extensions with .htaccess File
Read more »

Thursday, May 5, 2016

PHP File Unlink

When you view the contents of a directory you can see all the files that exist in that directory because the operating system or application that you are using displays a list of filenames. You can think of these filenames as links that join the files to the directory you are currently viewing.
If you unlink a file, you are effectively causing the system to forget about it or delete it!

Before you can delete (unlink) a file, you must first be sure that it is not open in your program. Use the fclose function to close down an open file.

Thursday, March 3, 2016

Download Duplicate File Detective 5 1 52 Pro Edition


link