Cakephp 3.0 read local file contents using fget - php

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

Related

File_get_contents(): failed to open stream: Connection refused

I am trying to download a previously uploaded file, form database and uploads folder in php codeigniter. I am using code below but downloading empty file.
controller.php
public function downloadFile($incidents_id)
{
$file = $this->incidents_model->getfile($incidents_id);
//echo $file; die;
$this->load->helper('download');
$path = file_get_contents(base_url()."uploads/".$file); //(the error shows on this line)
// echo $path; die;
$name = $file; // new name for your file
// echo $name ; die;
force_download($name, $path); // start download`
}
incidents_model.php
function getfile($Incident_id )
{
$file = $this->db->select('file');
$this->db->from('incidents');
$this->db->where('incidents_id' , $Incident_id );
$query = $this->db->get();
// return $query->row();
if ($query->num_rows() > 0) {
return $query->row()->file;
}
return false;
}
view.php
<div class="form-group col-md-4">
Download file
</div>
so running this code download an empty file.
echo $file; die; displays the file name which been saved in db and in uploads folder
echo $path; die; generates an error:
Severity: Warning
Message:
file_get_contents(http://localhost:8080/ticketing_tool_v2/uploads/Screenshot
2021-03-04 at 5.59.38 PM.png): failed to open stream: Connection
refused
Filename: admin/Incidents.php
Line Number: 380
Reviewing the documentation for file_get_contents you'll observe there's many different ways you can use it. For your purposes you would need to allow inbound connections to the filesystem.
The other way you could do this for better future proofing is to use the CodeIgniter file helper - https://codeigniter.com/userguide3/helpers/file_helper.html
Before reading the file from path, please check whether a path points to a valid file.
public function downloadFile($incidents_id) {
try {
$this->load->helper('download');
$file = $this->incidents_model->getfile($incidents_id);
$data = file_get_contents(base_url("uploads/" . $file));
$name = $file; // new name for your file
force_download($name, $data); // start download`
} catch (Exception $e) {
//exception handling code goes here
print_r($e);
}
}

CSV Bulk Upload to complete action after successfully uploaded

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.

How to call functions from another php file?

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.

Downloading files from FTP failing

I checked over some other answers before I came here to publish a question, I'm having trouble with the following script, no matter what i've tried it will not download a file from the FTP even after listing the files that are in directory (obviously)
Because I'm organised I like to simplify everything into a class,
class FTPHandler
{
private $connection;
public function FTPConnect($host, $user, $pass)
{
$ftp = ftp_connect($host);
$login = ftp_login($ftp, $user, $pass) or die("FTP: Login Failed");
if ($login) {
$this->connection = array("host" => $host, "user" => $user, "pass" => $pass);
return $ftp;
}
echo "FTP Login Failed";
}
public function ListAllFiles($stream, $dir)
{
ftp_pasv($stream, true);
$ls = ftp_nlist($stream, $dir);
return $ls;
}
public function get_conx_info() {
return $this->connection;
}
}
Using the following code:
define("APP_DIR", "./app/");
$ftp = new FTPHandler();
$handle = $ftp->FTPConnect("ftp.example.com.au", "exampleuser", "examplepass");
$files = $ftp->ListAllFiles($handle, APP_DIR);
foreach ($files as $val)
{
if ($val != "." && $val != ".." && $val != "processed") {
$local_file = $val;
$remote_file = APP_DIR.$val;
if (ftp_get($handle, $local_file, $remote_file)) {
echo "Successfully retrieved: $remote_file <br/>";
}
else
{
echo "Failed retrieving file: $remote_file <br/>";
}
}
}
My return is always:
Failed retrieving file: ./app/adsl-1989-csv.csv
Failed retrieving file: ./app/adsl-1989-sig.png
Failed retrieving file: ./app/dd-1964-csv.csv
Failed retrieving file: ./app/dd-1964-sig.png
Failed retrieving file: ./app/dd-1967-csv.csv
Failed retrieving file: ./app/dd-1967-sig.png
Failed retrieving file: ./app/dd-1972-csv.csv
Failed retrieving file: ./app/dd-1972-sig.png
Failed retrieving file: ./app/dd-1973-csv.csv
Failed retrieving file: ./app/dd-1973-sig.png
Failed retrieving file: ./app/dd-1974-csv.csv
Failed retrieving file: ./app/dd-1974-sig.png
Failed retrieving file: ./app/dd-1975-csv.csv
Failed retrieving file: ./app/dd-1975-sig.png
Failed retrieving file: ./app/dd-1978-csv.csv
Any assistance is highly appreciated as I have to have this automated to alleviate a few thousand per week off the employee budget.
I ended up discovering that the FTP server itself was at fault.
The error was fixed by changing from the default Active Ports as it was dropping majority of packets.
So if anyone out there is experiencing the same issue, worth taking a look at doing the same.
Thank you to Fred -ii- for your attempt in assisting me.

Uploading a file using WebDav protocol from Unix

I need to transfer a file from my Unix machine to a Windows machine. Problem is i can transfer a file already created on my machine via ftp from unix to any machine. also i can open webdav connection create new file and save it there.
What i am unable to do is to write my code to upload my file fro my local location using webdav.
i tried using pear client but due to lack of documentation, i am still not able to achieve the task .
Here is my attempt:
include("/usr/share/pear/HTTP/WebDAV/Client.php");
global $filename, $logger;
try {
/* $client = new HTTP_WebDAV_Client();
$user="username";
$pass = "pwd";
$dir = "webdavs://".$user.":".$pass."#hostname/";
var_dump($client->stream_open($dir."test4.txt","w",null,$path));
$client->stream_write("HELLO WORLD! , I am great ");
$client->stream_close();
$client->dir_opendir($dir,array());
var_dump($client->dirfiles);
$req =new HTTP_Request($dir);
$req->setBasicAuth($user, $pass);
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$result = $req->addFile('file_upload_field', $filename);
if (PEAR::isError($result)) {
echo $result->getMessage();
} else {
$response = $req->sendRequest();
if (PEAR::isError($response)) {
echo $response->getMessage();
} else {
echo $req->getResponseBody();
}
}*/
$ftp_server = "hostname-ftp";
//$ftp_server = "hostname-webdav";
$connection = ftp_connect($ftp_server);
ftp_login($connection, 'user', 'pwd);
ftp_put($connection, $filename, $filename, FTP_BINARY);
unlink($filename);
} catch(Exception $e){
$message = "There was a problem while uploading" . $filename;
$logger->error($message);
}
It was a togh call, but i figured it out. I am adding my code snippet so it may be helpful for someone. Instead of uploading the file, i converted that file into data stream and then copied that data stream to my call that writes stream on webdav server.
try {
$filecsv = file_get_contents($filename);
$client = new HTTP_WebDAV_Client_Stream();
$user="user";
$pass = "pass";
$dir = "webdavs://".$user.":".$pass."#hostname/";
$client->stream_open($dir."db_user_exports.csv","w",null,$path);
$client->stream_write($filecsv);
$client->stream_close();
unlink($filename);
} catch(Exception $e){
$message = "There was a problem while uploading" . $filename;
$logger->error($message);
}

Categories