Skip to content

Instantly share code, notes, and snippets.

@chirag-shinde
Last active April 21, 2021 07:39
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chirag-shinde/d1321e3dd99623687cde to your computer and use it in GitHub Desktop.
Save chirag-shinde/d1321e3dd99623687cde to your computer and use it in GitHub Desktop.
PHP Script to Upload CSV to MongoDB. Method Two of Two.
<!-- MongoDB has a command named mongoimport which can be used to directly upload a CSV file into a particular collection of
a database with the first line of the csv as the keys and the following rest of the csv as the values for the respective keys
The format of mongoimport is as folllows
"mongoimport --db database_name --collection collection_name --file csv_file_name --type csv"
now we can use variables to store our database and collection's name.
we upload the file to get the filename and it's path and then simple substitute the database_name and collection_name etc
with our variables and run the command through shell via php by using the exec function of php-->
<?php
//Your Database Connection include file here.
//This Entire PHP part can be placed in a seperate action file
if(isset($_POST['submit']))
{
//Upload Directory path.
$uploaddir = 'uploads/';
//FilePath with File name.
$uploadfile = $uploaddir . basename($_FILES["file"]["name"]);
//Check if uploaded file is CSV and not any other format.
if (($_FILES["file"]["type"] == "text/csv")){
//Move uploaded file to our Uploads folder.
if (move_uploaded_file($_FILES["file"]["tmp_name"], $uploadfile))
{
//Import uploaded file to Database. $collection is defined in the connection file or can be defined here too
$command = "mongoimport --db joins --collection " . $collection . " --file " . $uploadfile ." --type csv --headerline" ;
shell_exec($command);
}
}
else{
echo "Please Upload a CSV file Only!";
}
}
?>
<!--Simple Form(no css) to Upload the File-->
<html>
<head>
<form action='#' method='post' enctype='multipart/form-data'>
Choose file to import:<br><br>
<input type='file' name='file' id='file'><br><br>
<input type='submit' name='submit' value='extract'></form>
</head>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment