I have a PHP upload page to bulk upload to the MySQL database.
I was hoping someone could point me in the right direction. After the CSV file has successfully uploaded, I want to run a new action for each row/line of the CSV file.
Below is my upload PHP script;
if(isset($_POST["Import"])){
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
{
require('../config.php');
$conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Database connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `cases` (`case_id`, `clt_title`, `clt_first`, `clt_last`, `clt_add`, `clt_add2`, `clt_add3`, `clt_town`, `clt_county`, `clt_postcode`, `clt_ni`, `clt_dob`, `clt_tel`, `clt_email`, `case_type`, `case_cost`, `case_premium`, `case_term`, `case_source`, `case_drawdown`, `case_redemption`, `case_status`, `case_claim`, `case_incident`, `opp_name`, `opp_add`, `opp_add2`, `opp_add3`, `opp_town`, `opp_county`, `opp_post`, `sol_id`, `sol_ref`, `fund_id`, `invest_id`, `loan_balance`, `prem_charge`, `prem_start`, `up_prem`, `def_prem`, `capcov_prem`, `case_owner`, `received`)
values ('".$getData[0]."', '".$getData[1]."', '".$getData[2]."', '".$getData[3]."', '".$getData[4]."', '".$getData[5]."', '".$getData[6]."', '".$getData[7]."', '".$getData[8]."', '".$getData[9]."', '".$getData[10]."', '".$getData[11]."', '".$getData[12]."', '".$getData[13]."', '".$getData[14]."', '".$getData[15]."', '".$getData[16]."', '".$getData[17]."', '".$getData[18]."', '".$getData[19]."', '".$getData[20]."', '".$getData[21]."', '".$getData[22]."', '".$getData[23]."', '".$getData[24]."', '".$getData[25]."', '".$getData[26]."', '".$getData[27]."', '".$getData[28]."', '".$getData[29]."', '".$getData[30]."', '".$getData[31]."', '".$getData[32]."', '".$getData[33]."', '".$getData[34]."', '".$getData[35]."', '".$getData[36]."', '".$getData[37]."', '".$getData[38]."', '".$getData[39]."', '".$getData[40]."', '".$getData[41]."', '".$getData[42]."')";
$result = mysqli_query($conn, $sql);
if(!isset($result))
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"../../admin/cases.php?ct=%\"
</script>";
}
else {
echo header("Location: http://example.com/fpdf.php?ct=$id");;
}
}
fclose($file);
}
After this upload is complete, I would like to run another PHP script which is held in another file. I tried to run header("Location: http://example.com/myOtherPage.php"); but it's not working correctly.
Edit: The next action would be to create a pdf using FPDF, I have the FPDF File set up and working correctly but this is currently a manual process.
Related
I've got a PHP file that uploads a CV submitted via html form to a ftp server, but I cannot figure out how to specify the path, it seems. It comes back with error:
ftp_fput(): The system cannot find the path specified. in /var/www/*/phpmailer/sendmail.php on line 288
The code looks like this:
$finalCV = $id_nr . "." . $ext;
//
$location = "uploads/" . $finalCV;
//This next line was added to move the uploaded file to a folder on the local webserver,
//but now we would rather upload it directly to the ftp server
move_uploaded_file($_FILES['applCV']['tmp_name'], $location);
//Move uploaded & renamed CV to RES01
if($fp = fopen($location, 'r'))
echo "File Open Successful. ";
else {
echo "File Open Unsuccessful. ";
}
if($conn_id = ftp_connect("theftpserver"))
echo "FTP Connection Established Successfully. ";
else {
echo "FTP Connection Failed. ";
}
$ftpuser = "wynand";
$ftppasswd = "*******";
if($login = ftp_login($conn_id, $ftpuser, $ftppasswd)) {
echo "FTP Login Successful. ";
}
else {
echo "FTP Login Unsuccessful. ";
}
if(ftp_fput($conn_id, $somefile, $fp, FTP_ASCII)) {
echo "Successfully uploaded CV. ";
}
else {
echo "There was a problem uploading CV. ";
}
In short: I am uploading to /var/tmp multiple excel files, then convert them into .csv(2 different converters for .xls and .xlsx). The resulting file, result.csv should be inserted into database. It all worked until we decided to allow to upload multiple files simultaneously(adding multiple attribute to html input tag). Problem: data not inserted into table
<?php
// database connection goes here;
include 'convertt2a.php';
if (isset($_POST["submit"])) {
$updir = "/var/tmp/result.xlsx";
$n= count($_FILES['rawexcel']['name']);
for ($i=0; $i<$n; $i++) {
$upfile = $updir.basename($_FILES['rawexcel']['name'][$i]);
$ext = pathinfo ($_FILES['rawexcel']['name'][$i], PATHINFO_EXTENSION);
if(is_uploaded_file ($_FILES ["rawexcel"]["tmp_name"][$i]))
{
move_uploaded_file ($_FILES["rawexcel"]["tmp_name"][$i], $updir);
if ($ext == 'xlsx' ) { exec("/usr/local/bin/cnvt /var/tmp/result.xlsx /var/tmp/result.csv "); } else
if ($ext == 'xls' ) { exec("/usr/local/bin/xls2csv -x /var/tmp/result.xls* -b WINDOWS-1251 -c /var/tmp/result.csv -a UTF-8"); }
echo "File successfully uploaded and converted to .csv ";
}
else {
echo "error uploading file ".$upfile;}
if (isset($_POST['provider'])) {
//select action to perform on case of different providers
if ($_POST['provider']=='tele2altel'){echo t2a("tele2");}
}
echo "cycle ".$i."ended here; </br>";
}}
else {echo "not isset post method";}
?>
t2a function:
function t2a ($string){
//opening .csv file, inserting into table in SAMPLEBANK TELE2ALTEL
$row =0;
if (($handle = fopen("/var/tmp/result.csv", "r"))!==FALSE){
while (($data = fgetcsv($handle, 1000, ","))!==FALSE) {
$row ++;
//we got data in $data[$i] array
if ($row==4) {$idb=$data[2];}
if ($row >6) {
$da=$data[0]; $imei = $data[1]; $ab=$data[2];$ty = NULL;
$du=$data[6]; $op = $data[3];$dir =$data[5];
$num= strlen($dir);
if ($num>=28) {$ty= $dir; $dir=NULL;}
if ($ab!==''){
$sql= "INSERT INTO tele2altel(Abonent,Opponent, Type, Data, Duration, idBase, IMEI,direction)
values ('$ab','$op','$ty','$da','$du', '$idb','$imei','$dir')";
$res = mysqli_query($conn, $sql);}
}}
fclose($handle);
} else {echo "unable to read file";}
$s = "Successfully inserted into DB";
return $s;
}
My output:
File successfully uploaded and converted to .csv
cycle i ended here;
Successfully inserted into DB, i times(number of files to be uploaded)
I have checked seapartely .csv files, they are being converted correctly. Thus, the error is in t2a function. I will appreciate any help.
Include the another file in it.
<?php include('yourfilename'); ?>
I think the line below is opening the wrong file...
fopen("/var/tmp/result.xlsx", "r")
Should be
fopen("/var/tmp/result.csv", "r")
The thing that was needed for this code to work was clarification of type of return for function:
function t2a ($string):string {}
solved the problem.
I have worked out the PHP code required to upload data from a .csv file to a database, not using CakePHP3.x, but I am struggling integrating this into my framework. I don't want to upload the file to the database, only read the data from the CSV file.
This is my code that works on the localhost to upload the data to my database.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$fp = fopen("CSV_Upload_Test.csv", "r");
while( !feof($fp)) {
if( !$line = fgetcsv($fp, 1000, ',', '"')) {
continue;
}
$mysqlimport = "INSERT INTO divisiontwosix.csvtestsystems VALUES('".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[4]."')";
mysql_query($mysqlimport) or die(mysql_error());
}
fclose($fp);
This is my code for the CakePHP installation on my server, but I can't seem to find (or more likely ask the correct question to find) an answer on how to implement it.
This is my Controller:
public function upload()
{
$system = $this->Systems->newEntity();
//Check if file has been uploaded.
if(!empty($this->request->data['Systems']['upload']['name']))
{
$file = $this->request->data['Systems']['upload'];
}
if ($this->request->is('post')) {
$system = $this->Systems->patchEntity($system, $this->request->data);
// add upload data to controller function upload
$file = $_REQUEST['text'];
$fp = fopen("$file","r");
while( !feof($fp)) {
if( !$line = fgetcsv($fp, 1000, ',', '"')) {
continue;
}
$mysqlimport = "INSERT INTO divtwosix.systems VALUES('".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[4]."')";
mysql_query($mysqlimport) or die(mysql_error());
}
fclose($fp);
if ($this->Systems->save($system)) {
$this->Flash->success(__('The system has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The system could not be saved. Please, try again.'));
}
}
$estimates = $this->Systems->Estimates->find('list', ['limit' => 200]);
$this->set(compact('system', 'estimates'));
$this->set('_serialize', ['system']);
}
And this is my form (upload.ctp) as you can see I have tried a couple of things:
<?= $this->Form->create($system) ?>
<fieldset>
<legend><?= __('Upload System') ?></legend>
<?php
echo $this->Form->create('User', array('url' => array('action' => 'create'), 'enctype' => 'multipart/form-data'));
// echo $this->Form->create($system, ['type'=>'file']);
echo $this->Form->input('estimates_id', ['label'=>'Select Estimate Name','options' => $estimates]);
// echo $this->Form->input('file', ['label'=>'Upload works with CSV files only','type' => 'file']);
echo $this->Form->input('text', ['label'=>'Input File location']);
?>
</fieldset>
<?= $this->Form->button(__('Upload')) ?>
And the error I get is
fopen(C:\Users\jrogers\Desktop\Book1.csv): failed to open stream: No such file or directory [APP/Controller/SystemsController.php, line 86]
or
fopen(Book1.csv): failed to open stream: No such file or directory [APP/Controller/SystemsController.php, line 86]
It is not my intent to add the file to the database, but only to add the data from the .csv file to the database. I realize I am probably missing something simple, but would greatly appreciate the assistance. The examples I am finding only show how to upload the file to the database and not how to read the data from the local file. Thanks in advance for your help.
In legacy php scripts uploaded files should be accessed through $_FILES array so you should modify your code like this example
$file = $_FILES['text']['tmp_name'];
$fp = fopen($file,"r");
Good luck
source: http://php.net/manual/en/features.file-upload.post-method.php
note: I'm not a cake user but IMO it should have a proper way for accessing uploaded files
I have to migrate a legacy database up to MySQL using PHP. One of the components of the old system is a large (>1000) list of attached files (mostly .pdf, some are .doc/.docx).
I have so far done the following:
created mysql table, with a blob to contain the file (this method has
been chosen for valid reasons)
imported all the data except the attachments
extracted all the attachments into a folder, naming each file with a unique name
added and populated in mysql a column containing the unique name of the attachment
created a file containing the full names of all the attachments in the folder.
To add a single file is the only solution that I found in stack
But my requirement is to RECURSIVELY go through the list of filenames and find the matching row in mysql, then insert the file from the folder into the blob
example ...
I have a text file with entries like this (filename, date created, size)..
024048DE44C-RUE_MA.pdf,05/24/2013,80233
024048DE44C-RUE.pdf,06/21/2013,85151
... (1000 more)
I have a file with name 024048DE44C-RUE_MA.pdf in the folder
I have a row column filename containing 024048DE44C-RUE_MA.pdf in mysql database
I think the solution is something like this, but need help in the middle bit.
$myfile = fopen("filelist.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
$attfile =fgets($myfile);
...upload the file
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'dbase');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `deal_attachment` (
`deal_att_name`, `deal_att_mime`, `deal_att_size`, `deal_att_content`, `deal_att_created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
}
fclose($myfile);
Why don't you just use mysql LOAD_FILE function if you already have a table with the filename?
UPDATE mytable SET blobdata=LOAD_FILE(concat("/path/to/", filename));
Your files need to be on your mysql server in order for it to work.
If your only problem is how to read the CSV file you can do:
list($filename,$date, $size)=explode(",", $attfile);
Adam's suggestion worked perfectly for me with the important proviso in Windows that file path must contain double backslashes (so you would construct it like this
$path = 'c:\\dir\\subdir\\' . trim($filename) ;.
Following snippet of code shows the call ..
$query = "UPDATE `attachments` SET `att_content`=LOAD_FILE('" .$path . "') WHERE `att_name` = '" . $filename ."'" ;
$result = mysqli_query($dbcon,$query) ;
// Check if it was successful (maybe add some more insurance by going back to the database to see if the file is there - it can be that no error was reported but LOAD_FILE didn't work (like if the path is invalid)
if (false === $result) {
echo mysqli_error($dbcon);
die ;
} else { echo 'Success! Your file was successfully added!'; }
I'm making a file uploader using PHP and want to restrict it to PDFs and Microsoft Word files. However, it's currently allowing uploads from all file types to the database. How can I restrict it to only allowing PDFs and Microsoft Word files?
Here is my code:
<?php
# Check if a file has been uploaded
if (isset($_FILES['uploaded_file']))
# Make sure the file was sent without errors
if ($_FILES['uploaded_file']['error'] == 0) {
# Connect to the database
$dbLink = mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("webproject", $dbLink) or die(mysql_error());
/* if(mysql_connect()) {
die("MySQL connection failed: ". mysql_error());
} */
# Gather all required data
$filename = mysql_real_escape_string($_FILES['uploaded_file']['name']);
$filemime = mysql_real_escape_string($_FILES['uploaded_file']['type'] == "application/pdf" || $_FILES["uploaded_file"]["type"] == "application/msword");
$size = $_FILES['uploaded_file']['size'];
$data = mysql_real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$subjects = $_POST['subjects'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
# Create the SQL query
$query = "
INSERT INTO file(
Filename, Filemime, Filesize, Filedata, subjects, name, email, phone, Created
)
VALUES (
'{$filename}', '{$filemime}', {$size}, '{$data}', '{$subjects}','{$name}','{$email}','{$phone}', NOW()
)";
# Execute the query
$result = mysql_query($query, $dbLink);
# Check if it was successfull
if ($result) {
echo "Success! Your file was successfully added!";
} else {
echo "Error! Failed to insert the file";
echo "<pre>" . mysql_error($dbLink) . "</pre>";
}
} else {
echo "Error!
An error accured while the file was being uploaded.
Error code: " . $_FILES['uploaded_file']['error'];
}
# Close the mysql connection
mysql_close($dbLink);
# Echo a link back to the mail page
echo "<p><a href='index.html'>Click here to go back home page!.</a></p>";
?>
I am not sure how your code actually works, but if you replace your second if at the top by this, the program will run only if the type is pdf or word, other files will cause this error: "Error! An error accured while the file was being uploaded. Error code: ". $_FILES['uploaded_file']['error'];" to occur
if($_FILES['uploaded_file']['error'] == 0 && ($_FILES['uploaded_file']['type']=='application/pdf' || $_FILES['uploaded_file']['type']=='application/msword' || $_FILES["uploaded_file"]["type"] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'))
Your first if: if (isset($_FILES['uploaded_file'])) has no braces... that's not a very good practice.
Here is a extract from a function I sometimes use:
function CheckFile ($file){
$mimeTypes = array(
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/excel",
"application/vnd.ms-excel",
"application/x-excel",
"application/x-msexcel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
$fileExtensions = array("pdf", "doc", "docx", "xls", "xlsx");
if (in_array($file['type'], $mimeTypes) &&
in_array(end(explode(".", $file["name"])), $fileExtensions)) {
return true;
}
}
Call it with CheckFile($_FILES['uploaded_file']) It will return true if the doc is a pdf word or excel file
Edit:
One way to use it would be like so:
if (!CheckFile($_FILES['uploaded_file'])){
?>
<p>Sorry, your file was not of the correct type</p>
<?php
exit();
}