This will allow the user to select a file from their directory to upload using a HTML form
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<label>Select CSV File:</label>
<input type="file" name="doc_upload" />
<br/>
<input type="submit" name="submit" value="Import"/>
</form>
</body>
</html>
This code is put under the form above
//start of read code
if(isset($_POST["submit"]))
{
if($_FILES['doc_upload']['name'])
{
$filename = explode(".", $_FILES['file']['name']);
if($filename[1] == 'csv')
{
$handle = fopen($_FILES['file']['tmp_name'], "r");
while($data = fgetcsv($handle))
{
$item1 = mysqli_real_escape_string($conn, $data[0]);
$item2 = mysqli_real_escape_string($conn, $data[1]);
}
This code on the left:
Checks to see if a file has been uploaded
Checks to see if file is a CSV by exploding the file name
Creates a handler to read through the file line by line
Starts a while loop to read through the file line by line until get to the end of the document
Through each iteration of the loop, store each field element in a variable
Security
$item1 = mysqli_real_escape_string($conn, $data[0]);
This line removes any security threats like SQL injection code by removing any extra characters in the strings
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
The fread() function reads from an open file.
r - Open a file for read only. File pointer starts at the beginning of the file
w -Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a - Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x - Creates a new file for write only. Returns FALSE and an error if file already exists
r+ - Open a file for read/write. File pointer starts at the beginning of the file
w+ - Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a+ -Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x+ - Creates a new file for read/write. Returns FALSE and an error if file already exists
The feof() function is useful for looping through data of unknown length.
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>