I know this subject already exist but in my case is a little more difficult.
I'm reading .EDI files (current succeed) on PHP, the process:
1.- I upload a .edi file from a html form.
2.- I send those attributes from the form to read on my php code.
I got the code like this:
if(isset($_FILES['ufile']['name'])){
$tmpName = $_FILES['ufile']['tmp_name'];
$newName = "" . $_FILES['ufile']['name'];
if(!is_uploaded_file($tmpName) ||
!move_uploaded_file($tmpName, $newName)){
echo "<table><tr><td><strong>Failed to read file ".$_FILES['ufile']['name']."</strong></td></tr></table>";
} else {
echo "<br>";
//coloca o conteudo do arquivo para a variavel $arquivo
$ponteiro = fopen ($_FILES['ufile']['name'],"r");
$arquivo = '';
while (!feof ($ponteiro)) {
$arquivo = $arquivo.fgets($ponteiro,4096);
}
fclose ($ponteiro);
if (unlink($_FILES['ufile']['name']) != 1) echo "Erro ao deletar arquivo!";
$padrao = fnc_resgata_padrao($arquivo);
if ($padrao == "COARRI"){
$a = fnc_processa_coarri(trim($arquivo));
prc_mostra_coarri($a);
}
elseif ($padrao == "CODECO") {
$a = fnc_processa_codeco(trim($arquivo));
prc_mostra_codeco($a);
}
else {
echo "<table><tr><td><strong>Invalid file</strong></td></tr></table>";
}
}
} else {
echo "You need to select a file. Please try again.";
}
The problem is, in this way only read the first line of the .EDI file and not all lines. I'm trying to understand that i must print an array but i don't know how to do it because my $a has the values i'm interested.
If the post is hard to understand, please let me know.
update 1
I just deleted some lines of the code, nothing important.
Related
First off, the upload folder is given 777, and my old upload script works, so the server accepts files. How ever this is a new destination.
I use krajee bootstrap upload to send the files. And I receive a Jason response. The error seems to be around move uploaded file. I bet it's a simple error from my side, but I can't see it.
<?php
if (empty($_FILES['filer42'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['filer42'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($_FILES["filer42"]["tmp_name"][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {.
$output = [];
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
?>
I think field name is the issue. Because you are getting image name with filer42 and upload time, you are using pictures.
Please change
$_FILES["pictures"]["tmp_name"][$i]
to
$_FILES["filer42"]["tmp_name"][$i]
And check now, Hope it will work. Let me know if you still get issue.
The error is not in this script but in the post.
I was using <input id="filer42" name="filer42" type="file">
but it have to be <input id="filer42" name="filer42[]" type="file" multiple>
as the script seems to need an arrey.
It works just fine now.
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 need to check whether a folder contains csv files or not. Using PHP
I need to show an error message if someone try to upload any csv into a specific folder if there is already existing a csv.
Use glob() to find all files matching a wildcard. It returns an array of the matches, so you can check if the array is empty.
$files = glob("$dirname/*.csv");
if (!empty($files)) {
die("Error: The directory already has a .csv file");
}
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "Die Datei $filename existiert";
} else {
echo "Die Datei $filename existiert nicht";
}
?>
From: http://php.net/manual/de/function.file-exists.php
Loop over the files of directory to check whether it contains csv or not.
$files=scandir("/path/to/dir");
foreach($files as $fileName)
{
if(preg_match("/\.csv$/", $fileName))
{
throw new Exception("/path/to/dir contains csv file with filename: $fileName");
}
}
$dir = 'folder';
echo (count(glob("$dir/*.csv")) === 0) ? 'Empty' : 'Not empty';
You can use glob() function. http://php.net/manual/tr/function.glob.php
Also #Barmar answer is look like doing job well.
<?php
$directory = new DirectoryIterator(__DIR__);
if ($fileinfo->isFile()) {
$fileExt = $fileinfo->getExtension();
if($fileExt=="csv")
{
echo "File found";
}
else
{
echo "File not found";
}
}
?>
Reference:[http://php.net/manual/en/directoryiterator.getextension.php]
I have a secure file upload function that's part of my website
and I'm using an antivirus to help me checking the file a user trying to upload.
This is my uploadprocess.php file
$target_tmp = "D:\avscan\u\\";
$file = basename( $_FILES['uploaded_file']['name']) ;
if($file != "")
$_SESSION['file'] = $file;
$target = 'C:\xampp\htdocs\ssd\Uploads\\';
$file_path = $target_tmp.$file;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path))
{
$safe_path = escapeshellarg($file_path);
$command = 'scancl'. $safe_path. ' --stdout';
$out = '';
$int = -1;
$output = exec($command, $out, $int);
echo "The output is" .$output;
echo $int;
exit(0);
//Checking for Virus.
if ($int == 0) {
$target = $target.$file;
//echo $target; exit(0);
copy($file_path, $target);
$uploaded = "The file ". $_SESSION['file']. "has been uploaded";
$clean = 'File is Clean.';
$_SESSION['status'] = $clean;
$_SESSION['upload'] = $uploaded;
header("location: ../upload.php");
exit(0);
}
// File is a virus.
else {
$mal = 'Contains Malware';
$deny_up = "Unable to Upload Your File!";
$_SESSION['status'] = $mal;
$_SESSION['upload'] = $deny_up;
header("location: ../upload.php");
exit(0);
}
}
else
{
echo "SORRY, There was a Problem Uploading Your File."; exit(0);
$err_upload = "SORRY, There was a Problem Uploading Your File.";
$_SESSION['err'] = err_upload;
header("location: ../upload.php");
exit(0);
}
It prints me value of 1 for the $int for all files (malicious and non ones) This is my second try with a different AV now I'm using Avira and before I was using clamscan
can someone share me some hints, and tell me what's going on
PS the system is installed on XAMPP if that makes any difference
Can you be more specific about what's not working here? In theory what you doing seems fine at least for ClamAV since it has these return codes (from man clamscan):
RETURN CODES
0 : No virus found.
1 : Virus(es) found.
2 : Some error(s) occured.
Maybe it want to log the output of the exec call, if you are not getting the exit code you expect the reason should be in the output (like missing a command line flag).
I have searched the forum but the closest question which is about the control stream did not help or I did not understand so I want to ask a different question.
I have an html form which uploads multiples files to a directory. The upload manager that handles the upload resides in the same script with a different code which I need to pass the file names to for processing.
The problem is that the files get uploaded but they don't get processed by the the other code. I am not sure about the right way to pass the $_FILES['uploadedFile']['tmp_name']) in the adjoining code so the files can be processed with the remaining code. Please find below the script.
More specif explanation:
this script does specifically 2 things. the first part handles file uploads and the second part starting from the italised comment extracts data from the numerous uploaded files. This part has a variable $_infile which is array which is suppose to get the uploaded files. I need to pass the files into this array. so far I struggled and did this: $inFiles = ($_FILES['uploadedFile']['tmp_name']); which is not working. You can see it also in the full code sample below. there is no error but the files are not passed and they are not processed after uploading.
<?php
// This part uploads text files
if (isset($_POST['uploadfiles'])) {
if (isset($_POST['uploadfiles'])) {
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/Uploads/';
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
}
echo "Files successfully uploaded . <br/>" ;
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode(',', $uploaded_files);
*/* This is the start of a script to accept the uploaded into another array of it own for* processing.*/
$searchCriteria = array('$GPRMC');
//creating a reference for multiple text files in an array
**$inFiles = ($_FILES['uploadedFile']['tmp_name']);**
$outFile = fopen("outputRMC.txt", "w");
$outFile2 = fopen("outputGGA.txt", "w");
//processing individual files in the array called $inFiles via foreach loop
if (is_array($inFiles)) {
foreach($inFiles as $inFileName) {
$numLines = 1;
//opening the input file
$inFiles = fopen($inFileName,"r");
//This line below initially was used to obtain the the output of each textfile processed.
//dirname($inFileName).basename($inFileName,'.txt').'_out.txt',"w");
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inFiles)) {
$line = fgets($inFiles);
$lineTokens = explode(',',$line);
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile,$line)===FALSE){
echo "Problem w*riting to file\n";
}
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(',',$line);
$searchCriteria2 = array('$GPGGA');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile2,$line)===FALSE){
echo "Problem writing to file\n";
}
}
}
}
echo "<p>For the file ".$inFileName." read ".$numLines;
//close the in files
fclose($_FILES['uploadedFile']['tmp_name']);
fflush($outFile);
fflush($outFile2);
}
fclose($outFile);
fclose($outFile2);
}
?>
Try this upload class instead and see if it helps:
To use it simply Upload::files('/to/this/directory/');
It returns an array of file names that where uploaded. (it may rename the file if it already exists in the upload directory)
class Upload {
public static function file($file, $directory) {
if (!is_dir($directory)) {
if (!#mkdir($directory)) {
throw new Exception('Upload directory does not exists and could not be created');
}
if (!#chmod($directory, 0777)) {
throw new Exception('Could not modify upload directory permissions');
}
}
if ($file['error'] != 0) {
throw new Exception('Error uploading file: '.$file['error']);
}
$file_name = $directory.$file['name'];
$i = 2;
while (file_exists($file_name)) {
$parts = explode('.', $file['name']);
$parts[0] .= '('.$i.')';
$new_file_name = $directory.implode('.', $parts);
if (!file_exists($new_file_name)) {
$file_name = $new_file_name;
}
$i++;
}
if (!#move_uploaded_file($file['tmp_name'], $file_name)) {
throw new Exception('Could not move uploaded file ('.$file['tmp_name'].') to: '.$file_name);
}
if (!#chmod($file_name, 0777)) {
throw new Exception('Could not modify uploaded file ('.$file_name.') permissions');
}
return $file_name;
}
public static function files($directory) {
if (sizeof($_FILES) > 0) {
$uploads = array();
foreach ($_FILES as $file) {
if (!is_uploaded_file($file['tmp_name'])) {
continue;
}
$file_name = static::file($file, $directory);
array_push($uploads, $file_name);
}
return $uploads;
}
return null;
}
}