Php Fopen Files - php

Hello Guys i want to ask about a php script that should Open the file normally it's downloaded to my application automatically to a file named " \home\exactarget\offers\suppression " but sometimes some problems happens within the Automatic Donwload so i have to download the file and upload to a that Folder what i doesn't know is How that File Must be , this is hwo the file is when it's been auto-downloaded ( sp5-10-2182-MD5.txt ) so thsi Code IS where the app must read what is in that file it's Called Check Suppression
Thank You very much !
<?php
Include('../Includes/bdd.php');
$requete = $bdd->query('select id_offer,suppressionFile_Offer,TypeSuppressionFile_Offer from offer');
while($row = $requete->fetch())
{
$idOffer = $row['id_offer'];
$suppressionFile = $row['suppressionFile_Offer'];
$typeSuppression = $row['TypeSuppressionFile_Offer'];
if($typeSuppression =='text')
{
$subRequete = $bdd->query('select id_Email , email_Email from email');
while($subRow = $subRequete->fetch())
{
$file = fopen('Suppression/'.$suppressionFile,'a+');
$idEmail = $subRow['id_Email'];
$email = $subRow['email_Email'];
while($emailSuppression = fgets($file))
{
if(trim($email) == trim($emailSuppression))
{
$requeteSuppression = $bdd->prepare('insert into unsuboffer values(?,?)');
$requeteSuppression->execute(array($idEmail,$idOffer));
echo $email.'<br/>';
break;
}
}
fclose($file);
}
}
else
{
$subRequete = $bdd->query('select id_Email , md5(email_Email) from email');
while($subRow = $subRequete->fetch())
{
$file = fopen('Suppression/'.$suppressionFile,'a+');
$idEmail = $subRow['id_Email'];
$email = $subRow[1];
while($emailSuppression = fgets($file))
{
if(trim($email) == trim($emailSuppression))
{
$requeteSuppression = $bdd->prepare('insert into unsuboffer values(?,?)');
$requeteSuppression->execute(array($idEmail,$idOffer));
echo $email.'<br/>';
break;
}
}
fclose($file);
}
}
}
?>

Related

SpreadSheet - Uncaught InvalidArgumentException: File "file.xlsx" does not exist

I am uploading an xlsx file in a folder and later reading it to insert the information into the database, however the spreadsheet plugin is not finding the file, it is going to a folder that does not make sense, below is code that I'm using.
The correct file path is: arquivosRetorno/file.xlsx
but he is looking for in PHP Fatal error: Uncaught InvalidArgumentException: File "file.xlsx" does not exist. in /vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php:137
$allowed_extension = array('xls', 'csv', 'xlsx');
$file_array = explode(".", $_FILES["arquivo"]["name"]);
$file_extension = end($file_array);
if(in_array($file_extension, $allowed_extension)){
$file_name = time() . '.' . $file_extension;
move_uploaded_file($_FILES['arquivo']['tmp_name'], 'arquivosRetorno/'.$file_name);
$file_type = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file_name);
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($file_type);
$spreadsheet = $reader->load($file_name);
unlink($file_name);
$data = $spreadsheet->getActiveSheet()->toArray();
foreach($data as $row){
if($row[5] > 0){
$numeroIdentificacaoContribuicoes = $row[5];
$situacao = trim($row[7]);
$dataBaixaLiquidacao = trim($row[2]);
$dataPedacos = explode("/",$dataBaixaLiquidacao);
$dataBD = $dataPedacos[2]."-".$dataPedacos[1]."-".$dataPedacos[0];
if($row[5]>40107){
if ($numeroIdentificacaoContribuicoes != null || $numeroIdentificacaoContribuicoes != '') {
$bd->SQL = "SELECT * FROM entradas WHERE id2 = ".$numeroIdentificacaoContribuicoes;
$bd->Executa();
$status = $bd->Regs[0]["status"];
if ($situacao == 'Liquidado') {
if($status == "" || $status == "boleto nao foi pago" || $status == null){
$bd->SQL = "UPDATE entradas SET status = 'boleto pago', data_boleto = '".$dataBD."' WHERE id2 = ".$numeroIdentificacaoContribuicoes."";
$bd->Executa();
$bd2->SQL = "UPDATE transacoes SET status_transacao = '9995' WHERE numeropedido = ".$numeroIdentificacaoContribuicoes."";
$bd2->Executa();
}
}else{
if($status != "boleto pago"){
$bd->SQL = "UPDATE entradas SET status = 'boleto nao foi pago', data_boleto = '".$dataBD."' WHERE id2 = ".$numeroIdentificacaoContribuicoes."";
$bd->Executa();
echo "<br>";
echo $bd2->SQL = "UPDATE transacoes SET status_transacao = '9994' WHERE numeropedido = ".$numeroIdentificacaoContribuicoes."";
$bd2->Executa();
}
}
}
}
}
}
$message = '<div class="alert alert-success">Arquivo importado com sucesso</div>';
}else{
$message = '<div class="alert alert-danger">Apenas arquivos .xls .csv or .xlsx são aceitos</div>';
}
Change the call to:
$reader->load($file_name)
to:
$reader->load('arquivosRetorno/' . $file_name)

How to prevent PHP excel import from removing leading zero in a column?

I tried a tutorial here in https://phppot.com/php/import-excel-file-into-mysql-database-using-php/ to import XLSX file to my database (using PHP)
But the problem is, if the column value started with leading zero, after import, I found out that the leading zero was removed.
How to prevent this?
By the way, my phpmyadmin table for that particular column to be imported is structured as Text column, not integer
I've tried adding '' to treat the file as string but shows no success
$conn = mysqli_connect("localhost","root","test","phpsamples");
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"]))
{
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row)
{
$name = "";
if(isset($Row[0])) {
$name = mysqli_real_escape_string($conn,$Row[0]);
}
$description = "";
if(isset($Row[1])) {
$description = mysqli_real_escape_string($conn,$Row[1]);
}
if (!empty($name) || !empty($description)) {
$query = "insert into tbl_info(name,description) values('".$name."','".$description."')";
$result = mysqli_query($conn, $query);
if (! empty($result)) {
$type = "success";
$message = "Excel Data Imported into the Database";
} else {
$type = "error";
$message = "Problem in Importing Excel Data";
}
}
}
}
}
else
{
$type = "error";
$message = "Invalid File Type. Upload Excel File.";
}
}
Add a leading apostrophe (only if $description starts with a 0, of course), it will force Excel to read the cell as a text.
if ($description[0] === '0') {
$description = "'" . $description;
}

How to take input from user and save that into other file

I want to take input from user and save that into other file while keepping current data.
I want to take below details from user
server type : cpanel , FTP , windows , other (drop down)
Hostname
Username
Password
And save that in backup.php file. In backup php file I already have format
<?php
include xmlapi.php
$hostname= "";
$username = "";
$password = " ";
?>
I want details provided by user in this file. I can generare php file to ask these details but not sure how to insert data in backup.php while keeping existing data
can I get some help on it ?
Thanks
Using this config :
<?php
include xmlapi.php
$hostname = "";
$username = "";
$password = "";
?>
This will write user submitted data to that file :
<?php
$filename = "backup.php";
$user_data = $_POST; // contains $_POST['hostname'], $_POST['username'], etc
if(file_exists($filename))
{
$error_line = '';
foreach ($user_data as $config_name => $new_value)
{
$out = '';
$file = fopen($filename,'r+');
while(!feof($file))
{
$line = fgets($file);
$pattern_open = preg_match('/\$'.$config_name.'[ ]*=\s/i', $line, $matches_open);
$pattern_close = preg_match('/;.*\n/i', $line, $matches_close);
$out .= $matches_open != FALSE ? $matches_open[0] . "'" . $new_value . "'" . $matches_close[0] : $line;
}
fclose($file);
if (!file_put_contents($filename, $out))
{
if ($config_name === key($user_data))
{
$error_line .= "$config_name";
}
else
{
$error_line .= "$config_name, ";
}
}
}
if ($error_line != NULL)
{
echo 'Error at line : ' . $error_line;
}
else
{
echo 'Config saved';
}
}
else
{
echo 'File not found!';
}

excel file upload to database using Php

I am trying to upload excel .xls file but got an error when I am trying to import autoload file my web page going blank and when I comment it its works. I can't Import file of spout extenstion of reader. Here this is my code.
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;
require_once 'http://localhost/muddy/admin/spout-2.7.2/src/Spout/Autoloader/autoload.php';//Error cant import
here in this require once cant upload file if I write this code my web page going blank !
if (!empty($_FILES['file']['name'])) {
echo "ks";
$pathinfo = pathinfo($_FILES["file"]["name"]);
if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
&& $_FILES['file']['size'] > 0 ) {
$inputFileName = $_FILES['file']['tmp_name'];
// Read excel file by using ReadFactory object.
$reader = ReaderFactory::create(Type::XLSX);
// Open file
$reader->open($inputFileName);
$count = 1;
foreach ($reader->getSheetIterator() as $sheet) {
echo "ks22";
// Number of Rows in Excel sheet
foreach ($sheet->getRowIterator() as $row) {
echo "ks32";
// It reads data after header. In the my excel sheet,
// header is in the first row.
if ($count > 1) {
echo "ks4";
// Data of excel sheet
$data['Member_no'] = $row[0];
$data['Member_name'] = $row[1];
$data['Gender'] = $row[2];
$data['Club_name'] = $row[3];
$data['member_since'] = $row[4];
$data['Expiry_date'] = $row[3];
$member_no = $data['Member_no'];
$member_name = $data['Member_name'];
$gender = $data['Gender'];
$club_name = $data['Club_name'];
$member_since = $data['member_since'];
$expiry_date = $data['Expiry_date'];
$query="INSERT INTO `mmholdin_management`.`Club_member` (Member_no`, `Member_name`, `Gender`, `Club_name`, `member_since`, `Expiry_date`) VALUES ($member_no ,$member_name, $gender,$club_name,$member_since,$expiry_date)";
echo $query;
if(mysql_query($query))
{
$msg = "Record Saved!";
//header("Location:managecustomer.php");
exit;
}
else
{
$msg = "Unable to Save!";
}
print_r(data);
}
$count++;
}
}
// Close excel file
$reader->close();
} else {
echo "Please Select Valid Excel File";
}
} else {
//echo "Please Select Excel File";
}
try this example.
$file = "your-file.xls";
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name = $filesop[0];
$email = $filesop[1];
$sql = mysql_query("INSERT INTO xls (name, email) VALUES ('$name','$email')");
}
if($sql){
echo "You database has imported successfully";
}else{
echo "Sorry! There is some problem.";
}
check this: https://www.studytutorial.in/how-to-upload-or-import-an-excel-file-into-mysql-database-using-spout-library-using-php

You have an error in your SQL syntax error message when inserting record

I'm getting the error message when uploading a form in php.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near"
I've followed instructions from other posts as follows, to no avail:
1-Wrapped the column heading names in backticks.
2-Made sure all strings were passed as strings, and ints as ints.
3-Cleaned up any strings before sending out.
4-Made sure the connection to the database works and we can query from it.
5-Checked and re-checked my html code.
Here's my php code:
<?php
include('../config/config.php');
// Redirect browser if the upload form WAS NOT submited.
if (!isset($_POST['submit_upload']))
{
header("location: upload.html");
}
// Continue if the upload form WAS SUBMITED
else
{
// Set the upload directory path
$target_path = realpath( dirname( __FILE__ ) ) . "/uploads/audio/";
// Array to store validation errors
$error_msg = array();
// Validation error flag, if this becomes true we won't upload
$error_flag = false;
// We get the data from the upload form
$filename = $_FILES['file']['name'];
$temp_filename = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
$mimetype = $_FILES['file']['type'];
// Convert all applicable characters to HTML entities
$filename = htmlentities($filename);
$mimetype = htmlentities($mimetype);
// Check for empty file
if ($filename == "")
{
$error_msg[] = 'No file selected!';
$error_flag = true;
}
// Check the mimetype of the file
if ($mimetype != "audio/x-mp3" && $mimetype != "audio/mp3")
{
$error_msg[] = 'The file you are trying to upload does not contain expected data.
Are you sure that the file is an MP3 one?';
$error_flag = true;
}
// Get the file extension, an honest file should have one
$ext = substr(strrchr($filename, '.') , 1);
if ($ext != 'mp3')
{
$error_msg[] = 'The file type or extention you are trying to upload is not allowed!
You can only upload MP3 files to the server!';
$error_flag = true;
}
// Check that the file really is an MP3 file by reading the first few characters of the file
$open = #fopen($_FILES['file']['tmp_name'], 'r');
$read = #fread($open, 3);
#fclose($open);
if ($read != "ID3")
{
$error_msg[] = "The file you are trying to upload does not seem to be an MP3 file.";
$error_flag = true;
}
// Now we check the filesize.
// The file size shouldn't include any other type of character than numbers
if (!is_numeric($filesize))
{
$error_msg[] = 'Bad filesize!';
$error_flag = true;
}
// If it is too big or too small then we reject it
// MP3 files should be at least 1MB and no more than 10 MB
// Check if the file is too large
if ($filesize > 10485760)
{
$error_msg[] = 'The file you are trying to upload is too large!
Please upload a smaller MP3 file';
$error_flag = true;
}
// Check if the file is too small
if ($filesize < 1048600)
{
$error_msg[] = 'The file you are trying to upload is too small!
It is too small to be a valid MP3 file.';
$error_flag = true;
}
// Function to sanitize values received from the form. Prevents SQL injection
function clean($conn, $str)
{
$str = #trim($str);
if (get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysqli_real_escape_string($conn, $str);
}
// Sanitize the POST values
$title = clean($conn, $_POST['title']);
$context = clean($conn, $_POST['context']);
$source = clean($conn, $_POST['source']);
$interviewer = clean($conn, $_POST['interviewer']);
$interviewee = clean($conn, $_POST['interviewee']);
$intervieweeAge = (int)$_POST['intervieweeAge'];
$geoRegion = clean($conn, $_POST['geoRegion']);
$language = clean($conn, $_POST['language']);
$recDate = clean($conn,$_POST['recDate']);
$keywords = $_POST['keywords'];
if ($title == '')
{
$error_msg[] = 'Title is missing';
$error_flag = true;
}
if ($interviewee == '')
{
$error_msg[] = 'Interviewee name/anonymous is missing';
$error_flag = true;
}
// If there are input validations, show errors
if ($error_flag == true)
{
foreach($error_msg as $c => $p) echo "Error " . $c . ": " . $p . "<br />";
}
// Else, all checks are done, move the file.
else
{
if (is_uploaded_file($temp_filename))
{
// Generate an uniqid
$uniqfilename = $interviewee . '_' . str_replace("_", "", $recDate) . '.mp3';
$filePath = '/uploads/audio/' . $uniqfilename;
// If the file was moved, change the filename
if (move_uploaded_file($temp_filename, $target_path . $uniqfilename))
{
// Again check that the file exists in the target path
if (#file_exists($target_path . $uniqfilename))
{
// Assign upload date to a variable
$upload_date = date("Y-m-d");
// Create INSERT query
$qry = "INSERT INTO FDM177_AUDIO_CLIPS (title,context,source,interviewer,interviewee,intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES('$title','$context','$source','$interviewer',$interviewee',$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
if ($result)
{
$id = mysqli_insert_id($conn);
echo "File uploaded. Now it is called :" . $uniqfilename . "<br />" . $date . "<br />";
}
else
{
echo "There was an error uploading the file, please try again!";
}
if(1) {
//if (is_array($keywords) || is_object($keywords)) {
foreach($keywords as $k) {
// $idQuery = "SELECT keyword_ID from KEYWORDS WHERE keywordName=" . $k";
$idQuery = mysqli_query($conn, "SELECT * FROM FDM177_KEYWORDS WHERE (`keywordName` LIKE '%".$k."%')") or die(mysql_error());
$matchingKArray = mysqli_fetch_array($idQuery);
$keyword_FK = $matchingKArray[keyword_ID];
// echo $kQuery;
echo $keyword_FK;
$qry = "INSERT INTO FDM177_JNCT_KWDS_CLIPS (keyword_FK, clip_FK)
VALUES ('$keyword_FK', '$id')";
$result = mysqli_query($conn, $qry);
if ($result)
{
echo 'inserted with keyword.' . $k . ' <br />';
}
}
}
else {
echo "keywords are missing";
}
}
}
else {
echo "There was an error uploading the file, please try again!";
}
}
else
{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
The problem occurs at the first MYSQL query that starts as MYSQL query INSERT INTO FDM177_AUDIO_CLIPS...
What am I missing?
Thank you!
quotes breaking in one query '$interviewer',$interviewee',
$qry = "INSERT INTO FDM177_AUDIO_CLIPS
(title, context, source,interviewer, interviewee,
intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES
('$title', '$context', '$source', '$interviewer', '$interviewee',
$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";

Categories