Excel file upload in PHP - php

I am trying to upload Excel file using PHP. I am using WAMP server and written PHP code to upload Excel file in the same folder.
I have saved an Excel file so if I upload the saved file then it works fine but if I try to upload another Excel file from different location i.e. from desktop it is showing that abc.xls is not readable.
My code is as follows:
<?php
ini_set("display_errors",1);
require_once 'excel_reader2.php';
require_once 'db.php';
if(isset($_POST["btnImport"]))
{
if(!empty($_FILES["excelFile"]["tmp_name"]))
{
$fileupload = $_FILES["excelFile"]["name"];
$fileName = explode(".",$_FILES["excelFile"]["name"]);
if($fileName[1]=="xls"||$fileName[1]=="xlsx")
{
$data = new Spreadsheet_Excel_Reader($fileupload);
//echo "Total Sheets in this xls file: ".count($data->sheets)."<br /><br />";
$html="<table border='1'>";
for($i=0;$i<count($data->sheets);$i++) // Loop to get all sheets in a file.
{
if(count(#$data->sheets[$i]['cells'])>0) // checking sheet not empty
{
// echo "Sheet $i:<br /><br />Total rows in sheet $i ".count($data->sheets[$i]['cells'])."<br />";
for($j=1;$j<=count($data->sheets[$i]['cells']);$j++) // loop used to get each row of the sheet
{
$html.="<tr>";
for($k=1;$k<=count($data->sheets[$i]['cells'][$j]);$k++) // This loop is created to get data in a table format.
{
$html.="<td>";
#$html.=$data->sheets[$i]['cells'][$j][$k];
$html.="</td>";
}
#$data->sheets[$i]['cells'][$j][1];
#$ques = mysql_real_escape_string($data->sheets[$i]['cells'][$j][1]);
$opt1 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][2]);
$opt2 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][3]);
$opt3 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][4]);
#$opt4 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][5]);
#$correct = mysql_real_escape_string($data->sheets[$i]['cells'][$j][6]);
#$Level = mysql_real_escape_string($data->sheets[$i]['cells'][$j][7]);
#$Category = mysql_real_escape_string($data->sheets[$i]['cells'][$j][8]);
#$explain = mysql_real_escape_string($data->sheets[$i]['cells'][$j][9]);
$nithi = "INSERT INTO `question` VALUES (NULL,'".$ques."','".$opt1."','".$opt2."','".$opt3."','".$opt4."','".$correct."','".$Level."','".$Category."','".$explain."')";
if (!mysql_query($nithi,$connection))
{
die('Error: ' . mysql_error());
}
$result = mysql_query("SET NAMES utf8");//the main trick
$cmd = "select * from TAMIL";
$result = mysql_query($cmd);
}
}
}}}}
if(#$result){
echo "Questions uploaded successfully";
}
?>
How can I upload Excel file from different location?

When a file is uploaded in PHP, it is put into temp folders.
In your code, there is no call for moving the uploaded file from temporary location into the desired one. Instead you are only checking $_FILES["excelFile"]["tmp_name"] and then directly using $_FILES["excelFile"]["name"] which is obviously incorrect.
Use move_uploaded_file() function to move the file, see the docs: http://php.net/move_uploaded_file

Related

PHPExcel xlsx file into array ....Reader_Exception: Could not open

1.8.0"
the goal of my web application is to have a button that the user clicks on.
The code behind will start to scan all the folders that are in the main rdv folder.
in the rdv folder it contains three folders named 1000, 1001, 1002 these contain .xlsx files.
retrieves the last file .xlsx saved in each of the folders
but after that it doesn't work.
Fatal error: Uncaught PHPExcel_Reader_Exception: Could not open 2.xlsx
for reading!
so how i can fix the fatal error and how is possible to read the file to continue the code, i want to get 3 values in the .xlsx file and insert into my database.
thank you for your time.
include 'database.php';
require 'PHPExcel/Classes/PHPExcel.php';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
// receives the 'someAction' value from the index page button.
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction']))
{
func();
}
function func()
{
//calcul the nomber of folder in folder rdv
$howManyFolder = count(glob('rdv/*', GLOB_ONLYDIR));
//retrieves the last file saved in each of the folders and insert into database
for ($i = 0; $i < $howManyFolder; $i++) {
$files = scandir("rdv/100$i", SCANDIR_SORT_DESCENDING);
echo "Recover all files in the folder 100" . $i . "<br>";
print_r($files ); echo "<br>";
echo "get the last file inserted in the folder at index 0 <br>";
$newest_file = $files[0]; print_r($newest_file); echo "<br>";
//load the file .xlsx (but the code bug here -_-)
$objExcel=PHPExcel_IOFactory::load($newest_file);
//get all value insinde the .xlsx file
$dossier = $objExcel->getActiveSheet()->getCell('A3')->getValue();
$facture = $objExcel->getActiveSheet()->getCell('B21')->getValue();
$date = $objExcel->getActiveSheet()->getCell('Q1')->getValue();
//call function to insert these values inside dataBase.
insertInto($dossier, $facture, $date );
}
}
XML Parser:
https://www.php.net/manual/en/book.xml.php
Parsing an XML document: https://www.php.net/manual/en/function.xml-parse.php
<?PHP
$stream = fopen('large.xml', 'r');
$parser = xml_parser_create();
// set up the handlers here
while (($data = fread($stream, 16384))) {
xml_parse($parser, $data); // parse the current chunk
}
xml_parse($parser, '', true); // finalize parsing
xml_parser_free($parser);
fclose($stream);

What's wrong?, I want to copy the image file to my other directory after upload, and input it to the mysql database too

this is my code
<?php
include 'koneksi.php';
$judul_artikel = $_POST['judul_artikel'];
$isi_artikel = $_POST['isi_artikel'];
$tanggal_artikel = date('Y-m-d');
$tag_artikel = $_POST['tag_artikel'];
$filetmp = $_FILES["gambar_artikel"]["tmp_name"];
$filename = $_FILES["gambar_artikel"]["name"];
$filetype = $_FILES["gambar_artikel"]["type"];
$filepath = "img/".$filename;
move_uploaded_file($filetmp, $filepath);
$query = mysql_query('INSERT INTO artikel(judul_artikel,isi_artikel,tanggal_artikel,tag_artikel,gambar_artikel) VALUES ("'.$judul_artikel.'","'.$isi_artikel.'","'.$tanggal_artikel.'","'.$tag_artikel.'","'.$filepath.'")')or die(mysql_error());
if ($query) {
header('location:artikel.php?notif=berhasil');
} else {
header('location:artikel.php?notif=gagal');
}
?>
the problem I face is, I want to copy the image file to another directory after I upload it, and input it into the mysql database too, but when I execute, the file that I upload is not copied in the directory that I want, and is not inputted into the mysql database, how to handle it ?
try to wrap it inside if condition like this
if(move_uploaded_file($filetmp, $filepath)){
echo "success";
}else{
echo "failed";
}
and make sure you set the folder permission

Cannot upload image using filepath in MS-Azure Blob Storage

I am developing a web application using Microsoft Azure services. I am following this link to upload an image to my blob storage, but there are a few bits and pieces missing in the document that leads to certain issues. For instance, how do we define the variable $fileToUpload and how will it relate to the variable $myfile? Also, if we want to choose to upload a file from our system when the application is running, in which of the two variables should we have the absolute file path to my image? The code I have written till now to upload an image is as follows:
function imageupload(string $current_user){
$pt_id = $_POST['patientid'];
if (strcmp($pt_id,"")==0){
echo "Select PatientID to continue";
}else{
$accountexists = load($current_user, $pt_id);
if ($accountexists == 0){
$error = "Patient Id does not exist";
echo $error;
}else{
$img_path = $_POST['uploadI'];
if (strcmp($img_path, "")==0){
echo "Enter valid image path <br />";
}
else{
require_once 'vendor/autoload.php';
$connectionString = '****';
// Create blob client.
$blobClient = BlobRestProxy::createBlobService($connectionString);
# Create the BlobService that represents the Blob service for the storage account
$containerName = $current_user;
$num = rand(10,10000);
$num2 = (string) $num;
$fileToUpload = $pt_id."_".$num2;
# Upload file as a block blob
echo "Uploading image: ".PHP_EOL;
echo $img_path;
echo "<br />";
$content = fopen($img_path, "r");
//Upload blob
$blobClient->createBlockBlob($containerName, $fileToUpload, $content);
echo "Image uploaded successfully! <br />";
}
}
}
}
In this code, I am storing my path to the image in the variable $img_path. And this is the code I am using for displaying the image later:
// Gets all the images from the hospital's container and filters out the images corresponding to a particular patient.
// For the patient, the image would be saved on cloud with name as: <patientid>_<some random number>
// Eg- patient id= pt1 , so image name could be- pt1_3682
function uploadedimage(string $current_user, string $HospitalId, string $PatientId){
$containerName = $HospitalId;
$url = "";
try{
// Get blob.
require_once 'vendor/autoload.php';
// use MicrosoftAzure\Storage\Common\ServicesBuilder;
$connectionString = '****';
$blobClient = BlobRestProxy::createBlobService($connectionString);
$blob_list = $blobClient->listBlobs($containerName);
$blobs = $blob_list->getBlobs();
$strlen = strlen($PatientId);
$array_user = array();
// echo "These are the blobs present in the container: ";
foreach($blobs as $blob)
{
$name = $blob->getName();
$namesub = substr($name,0, $strlen);
if (strcmp($namesub, $PatientId) == 0){
array_push($array_user, $blob);
}
}
}
catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
$url = "";
try {
foreach($array_user as $blob)
{
$name = $blob->getName();
$url = $blob->getUrl();
echo "<img src=\"".$url."\" alt=\"image post\"></br></br>";
}
}
catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
But I cannot seem to view my image in the html that I have specified. All I get is the default text "image post". Thus I have concluded there is something I am missing in my code due to which the images are not being uploaded but I can't seem to figure that out from the azure tutorial.
Edit: I checked my blob properties and they are all of 0 size, which means that they are not being uploaded properly. Also I realised that there are some images that were pushed to the cloud along with my code in my git folder. So if there is a particular image by the name abc.png already existing in the same directory as my code on Azure and while uploading this image from my web application, if in the path text box I specify only abc.png, that image gets uploaded in my container in it's correct size, but if that same image is present on my desktop and if I specify the complete filepath of my local system for this image (or some other image not present in the git directory existing on azure) as C:/Desktop/abc.png, it gets uploaded as only 0 bytes image (which is essentially not being uploaded properly). What can be the issues if it is not able to take images from my system and can only take the images already existing in it's git directory?

Uploading 1000 images via url using PHP

I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress

the filename .xls is not readable

I want to download file .xls and then upload it to database oracle. but I am getting an error "the filename .xls is not readable".
Below is my script:
<? require_once (dirname(__FILE__)."/upload/upBc.php");
if(!empty($_FILES["file"])){
echo $file = $_FILES["file"];
}else{
/*$file = "/opt/lampp/htdocs/avar/pp/ccr/test.xls";*/
$file = '/www.upload.com/pm_ms/test.xls';
/* $file = "website_data_". date('ymd').".xls";*/
}
$upload = new upload();
$upload->setFile($file);
$upload->getFileType();
$upload->getFileName();
$upload->getFileDir();
$upload->readDataTbc();
$dataD = array ();
$dataD = $upload->getDataTbc();
echo "<table border = 1>";
for($i=1;$i < count($dataD);$i++){
echo "<tr>";
for($j=0;$j < $upload->getHSize();$j++){
echo " <td>".$dataD[$i][$j]."</td>";
}
echo"</tr>";
}
echo"</table>";
echo"data length=". count($dataD);
$upload->commitDataTbc();
?>
If I use $file = "/opt/lampp/htdocs/avar/pp/ccr/test.xls";. in my program it works
but if I use $file = '/www.upload.com/pm_ms/test.xls';. I get the error THE FILENAME test.xls is Not Readable
That's probably because /www.upload.com/ doesn't exist on your server.
Do you know the actual path to the file? By prefixing the URI with / this makes it absolute, which means that it's trying to read literally from /www.upload.com on your server. If you're looking to make this relative you could try ./upload.com/ or simply upload.com/ as the path prefix.
If you are however trying to load it from the website upload.com (instead of a folder from your server) you have two options:
(If Supported) Set the filename as a URL ie. $file = 'http://www.upload.com/pm_ms/test.xls';
Download the file and then open it locally.
For #2:
$file = 'test.xls';
$ctnts = file_get_contents('http://www.upload.com/pm_ms/test.xls');
file_put_contents($file, $ctnts);

Categories