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

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)

Related

I cannot upload variables to database

I tried to upload video filenames and other variables to the database, but the insert statement won't work. Anyway the videofile-name and the thumbnail-filename are both uploaded to the right folders.
I've checked and there's nothing wrong with the sql statement. But why won't it work can anyone tell me?
PHP code
<?php
session_start();
if (isset($_POST['submit'])) {
$videoName = $_POST['videoName'];
$videoDesc = $_POST['description'];
$category = $_POST['category'];
$level = $_POST['level'];
$userId = $_SESSION['userId'];
$videoFile = $_FILES["videoFile"];
$videoFileName = $videoFile['name'];
$videoFileType = $videoFile['type'];
$videoFileTempName = $videoFile['tmp_name'];
$videoFileError = $videoFile['error'];
$videoFileExt = explode(".", $videoFileName);
$videoFileActualExt = strtolower(end($videoFileExt));
$videoAllowed = array("mp4", "mov", "avi");
$thumbFile = $_FILES["thumbnail"];
$thumbFileName = $thumbFile["name"];
$thumbFileType = $thumbFile["type"];
$thumbFileTempName = $thumbFile["tmp_name"];
$thumbFileError = $thumbFile["error"];
$thumbFileExt = explode(".", $thumbFileName);
$thumbFileActualExt = strtolower(end($thumbFileExt));
$thumbAllowed = array("jpg", "jpeg", "png");
if (in_array($videoFileActualExt, $videoAllowed)) {
if(in_array($thumbFileActualExt, $thumbAllowed)) {
if ($videoFileError === 0) {
if ($thumbFileError === 0) {
$videoFullName = $videoFile . "." . uniqid("", true) . "." . $videoFileActualExt;
$videoFileDestination = "../video/" . $videoFullName;
$thumbFullName = $thumbFile . "." . uniqid("", true) . "." . $thumbFileActualExt;
$thumbFileDestination = "../thumbnail/" . $thumbFullName;
include 'dbh.inc.php';
if(empty($videoName) or empty($videoDesc)) {
header("Location: ../uploadVideo.php?upload=empty");
exit();
} else {
move_uploaded_file($videoFileTempName, $videoFileDestination);
move_uploaded_file($thumbFileTempName, $thumbFileDestination);
$sql = "INSERT INTO video (filnavn, thumbnail, videoName, descript, idMusician, categoryName, idLevel) VALUES ('$videoFullName', '$thumbFullName', '$videoName', '$videoDesc', $userId, '$category', $level);";
mysqli_query($conn, $sql);
header("Location: ../uploadVideo.php?upload=success");
exit();
}
} else {
echo "You had a thumbnail error!";
exit();
}
} else {
echo "You had a video error!";
exit();
}
} else {
echo "You need to upload a proper thumbnail file type";
exit();
}
} else {
echo "You need to upload a proper video file type!";
exit();
}
} else {
}
You cannot insert or in this way in the if() condition, you must always use the logical operator as
if(empty($videoName) || empty($videoDesc))
Because of that your execution of code must have stopped at that point.

Php Fopen Files

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);
}
}
}
?>

edit uploaded image with using class.upload.php

I made simple upload system with using class.upload.php and it works great while adding new into database. But i have problem when i need to edit my entry. While editing entry i don't want to edit image but it sent it blank, also if i select image again it sent it blank too. Here is my code.
Can explain my problem.
<?php require_once("conn.php");
require_once ("class.upload.php");
$catid = $_POST['catid'];
$title = $_POST['title'];
$descc = $_POST['descc'];
$keyw = $_POST['keyw'];
$message = $_POST['message'];
$Image = $_FILES['Image'];
$randnum = rand();
$foo = new upload($Image);
$filee = './Image';
if ($foo->uploaded) {
$foo->image_resize = true;
$foo->file_new_name_body = $randnum;
$foo->image_x = 550;
$foo->image_y = 440;
$foo->process($filee);
if ($foo->processed) {
echo 'Image uploaded.';
echo $foo->file_dst_name;
$foo->clean();
} else {
echo 'Error. : ' . $foo->error;
}
}
$Image7 = $foo->file_dst_name;
if($_GET[pass] == 1)
{
if(!isset($_POST[catid]) || empty($_POST[catid])){
$hata = "Required area.";
}
if(!isset($_POST[title]) || empty($_POST[title])){
$hata = "Required area.";
}
if(!isset($_POST[descc]) || empty($_POST[descc])){
$hata = "Required area.";
}
if(!isset($_POST[keyw]) || empty($_POST[keyw])){
$hata = "Required area.";
}
if(!isset($_POST[message]) || empty($_POST[message])){
$hata = "Required area.";
}
if(!$hata){
mysql_query("UPDATE product SET
catid='$_POST[catid]',
title='$_POST[title]',
descc='$_POST[descc]',
keyw='$_POST[keyw]',
message='$_POST[message]',
Image='$_POST[Image]'
WHERE id='$_POST[id]'
");
$mesaj = "OK!";
}
}
$sonuc = mysql_query("select * from product WHERE id='$_GET[product]'");
$edit = mysql_fetch_array($sonuc);
$sonuc1 = mysql_query("select * from category");
$edit1 = mysql_fetch_array($sonuc1);
?>
try to change the update query
at Image='$_POST[Image]'
with Image='$Image7'
Fatih you can use a variable (i.e. $saved_image_name) instead of $POST[Image] at sql query. Set this variable to new name if uploaded else old value of db field.
...
...
$foo = new upload($Image);
$filee = './Image';
$saved_image_name = " Image "; // name of db field.
if ($foo->uploaded) {
$foo->image_resize = true;
$foo->file_new_name_body = $randnum;
$foo->image_x = 550;
$foo->image_y = 440;
$foo->process($filee);
if ($foo->processed) {
echo 'Image uploaded.';
echo $foo->file_dst_name;
// Note the quotes
$saved_image_name = " '$foo->file_dst_name' ";
$foo->clean();
} else {
echo 'Error. : ' . $foo->error;
}
}
// no use anymore $Image7 = $foo->file_dst_name;
...
...
if(!$hata){
mysql_query("UPDATE product SET
catid='$_POST[catid]',
title='$_POST[title]',
descc='$_POST[descc]',
keyw='$_POST[keyw]',
message='$_POST[message]',
Image= $saved_image_name // note the quotes
WHERE id='$_POST[id]'
");
...
...

Can't store a .pdf file in a blob in mySQL

So I am trying to upload a PDF file into a mySQL blob, the table row gets inserted but in the fileContent which is the mediumBlob type it appears always as [BLOB 0 B] and when the file is downloaded, it is downloaded with 0 bytes. Ive echoed $content and it shows the special characters of the pdf file.
$erro = '';
$tipo = '';
if (isset($_POST['submit']) && isset($_POST['text']) && $_POST['text'] !== null && isset($_POST['userID']))
{
if(preg_match('/^[a-z0-9-]+$/',$_POST['text']) && strlen($_POST['text']) < 15 )
{
if (substr($_FILES['file']['name'], -3, 3) == "pdf" && $_FILES["file"]["size"] < 1000000)
{
if ($_FILES["file"]["error"] > 0)
{
$erro = "Problema: " . $_FILES["file"]["error"];
$tipo = 'erro';
}
else
{
$_FILES["file"]["name"] = $_POST['text'].'.pdf';
$erro = "Ficheiro guardado com sucesso.";
$tipo = 'sucesso';
}
}
else
{
$erro = "Apenas .PDF com menos de 10 Mb são permitidos!";
$tipo = 'erro';
}
}
else
{
$erro = "Nome inválido";
$tipo = 'erro';
}
if ($tipo == 'sucesso')
{
$content = $db->real_escape_string(file_get_contents($_FILES['file']['tmp_name']));
if ($_FILES["file"]["size"] > 0)
{
$smt = $db->prepare('INSERT into uploads (userRefID,fileName,fileType,fileSize,fileContent,uploadDate) values(?,?,?,?,?,?)');
$smt->bind_param('issibs', $_POST['userID'], $_FILES["file"]["name"], $_FILES["file"]["type"], $_FILES["file"]["size"], $content ,date(c));
$smt->execute();
$smt->close();
}
}
}
What am I doing wrong?
According to this comment you should not pass the blob directly in bind_param, but with send_long_data.
From the documentation of send_long_data here's an example:
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();

not updating in database

This is my code
$id = $_POST['id'];
$category = $_POST['category'];
$title = $_POST['title'];
$short_content = $_POST['short_content'];
$long_content = $_POST['long_content'];
$date = $_POST['date'];
$lang = $_POST['language'];
//echo $id." ".$category." ".$title." ".$short_content." ".$lang." ".$date;
if(empty($id)){
echo "<h3 align=\"center\">Please fill ID</h3>";
}
if(empty($category)){
echo "<h3 align=\"center\">Please fill Category</h3>";
}
if(empty($title)){
echo "<h3 align=\"center\">Please fill Title</h3>";
}
if(empty($date)){
echo "<h3 align=\"center\">Please fill Date</h3>";
}
if(empty($lang)){
echo "<h3 align=\"center\">Please fill Lang</h3>";
}
if(!empty($_FILES['img']['name'])){
$extension = end(explode(".",$_FILES['img']['name']));
//echo "file format: ".$extension."<br>";
$name = $_FILES['img']['name'];
$size = $_FILES['img']['size'];
if(file_exists("views/admin/uploads/".$name)){
echo "<h3 align=\"center\">".$_FILES['img']['name']." exists</h3>
<h3 align=\"center\">Go back</h3>";
return false;
}
if($extension != "jpg" && $extension != "png" && $extension != "gif" && $extension != "JPG"){
echo "<h3 align=\"center\">File with format: ".$extension." is not aviable to upload</h3>
<h3 align=\"center\">Go back</h3>";
return false;
}
}
if(!empty($id) && !empty($category) && !empty($title) && !empty($date) && !empty($lang)){
$query = mysql_query("UPDATE `news` SET `id`='$id', category`='$category',`title`='$title',`img`='$name',`short_content`='$short_content',`content`='$long_content',`date`='$date',`lang`='$lang' WHERE `id`='$id'");
move_uploaded_file($_FILES['img']['tmp_name'],"views/admin/uploads/".$name);
echo "<h2 align=\"center\">Successfully updated!</h2>";
}
It's should update table row, but it dont. The input value are sending ok. Please give me a solution..
Which part of code is wrong?????
I don't know will this fix your problem (yes, I don't have time to test this), but be happy about that I made your code much more readable.
In the future, it would be much easier answer if you 1. make your code readable and 2. give your mysql database dump.
Create classes.php file and add this code inside it. Change your host, dbname, username and password if needed.
// Connecting to database
class mysql{
public $db;
public function connect(){
$this->db = new PDO(
"mysql:host=localhost;dbname=xxxxx;",
"root",
""
);
}
}
// Update thing
class stuff extends mysql{
public function updateThing($id,$cat,$title,$img,$shortContent,$content,$date,$lang){
$this->statement = $this->db->prepare("UPDATE `news` SET `category`= $2,`title` = $3,`img` = $4,`short_content` = $5,`content` = $6,`date` = $7,`lang` = $8 WHERE `id` = $1");
$this->statement->execute(array($id,$cat,$title,$img,$shortContent,$content,date("Y-m-d H:i:s",strtotime($date)),$lang));
print_r($this->statement->fetchAll());
}
}
And then throw these into file what updates things:
include_once("classes.php");
$id = $_POST['id'];
$cat = $_POST['category'];
$title = $_POST['title'];
$shortContent = $_POST['short_content'];
$longContent = $_POST['long_content'];
$date = $_POST['date'];
$lang = $_POST['language'];
$stuff = new stuff;
$stuff->connect();
$errors = array();
if(empty($id)){
$errors[] = "Please fill ID";
}
if(empty($cat)){
$errors[] = "Please fill Category";
}
if(empty($title)){
$errors[] = "Please fill Title";
}
if(empty($date)){
$errors[] = "Please fill Date";
}
if(empty($lang)){
$errors[] = "Please fill Lang";
}
if(!empty($_FILES['img']['name'])){
$extension = end(explode(".",$_FILES['img']['name']));
$name = $_FILES['img']['name'];
$size = $_FILES['img']['size'];
if(file_exists("views/admin/uploads/".$name)){
$errors[] = "File with this name already exists!";
}
if($extension != "jpg" && $extension != "png" && $extension != "gif" && $extension != "JPG"){
$errors[] = "Unknown file format!";
}
}
if(count($errors)==0){
$stuff = new stuff;
$stuff->connect();
$stuff->updateThing($id,$cat,$title,$img,$shortContent,$longContent,$date,$lang);
move_uploaded_file($_FILES['img']['tmp_name'],"views/admin/uploads/".$name);
echo "<h2>Successfully updated!</h2>";
}else{
print "<h3>Errors!</h3><ul><li>".join("</li><li>",$errors)."</li></ul>";
}

Categories