Problems reading excel file with PHPExcel - php

I am having trouble reading a file with PHPExcel. Here is the error I'm getting:
( ! ) Fatal error: Class 'PHPExcel_Cell' not found in /Applications/MAMP/htdocs/TestRailIntegration/Classes/PHPExcel/Reader/Excel2007.php on line 739
Call Stack
# Time Memory Function Location
1 0.0023 649920 {main}( ) ../testRailScripting.php:0
2 0.0030 755712 PHPExcel_IOFactory::load( ) ../testRailScripting.php:23
3 0.0038 797288 PHPExcel_Reader_Excel2007->load( ) ../IOFactory.php:193
And here is my code:
<?php
include './Classes/PHPExcel.php';
echo 'Hello world' . "\n";
$FileName = $_FILES["fileName"]["name"];
$inputFileName=$_FILES["fileName"]["tmp_name"];
echo $inputFileName;
if(file_exists("uploadedFiles/".$_FILES["fileName"]["name"])){
echo $_FILES["fileName"]["name"]." already exists";
}
else{
move_uploaded_file($_FILES["fileName"]["tmp_name"],"uploadedFiles/".$_FILES["fileName"]["name"]);
echo $_FILES["fileName"]["name"]." has been moved";
}
$PHPExcelObj = PHPExcel_IOFactory::load($inputFileName);
?>

I see you moved the file to "uploadedFiles" folder so:
$PHPExcelObj = PHPExcel_IOFactory::load("uploadedFiles/".$inputFileName);

Related

Newbie trying to figure out PHP [duplicate]

This question already has answers here:
PHP - Failed to open stream : No such file or directory
(10 answers)
Closed 5 years ago.
I am just trying to make a simple PHP program that allows me to generate my page quickly.
I am completely new at PHP.. And I have no clue what I am doing.
/index.php
<?php
include "/base/startup.php";
echo "Test";
startPage("Home");
?>
I'm getting a 500 server error with this.. Please tell me what I'm doing wrong. Thank you.
/base/startup.php
$HOME = "/";
$SCRIPT = <<<EOD
EOD;
$IMPORTS = array(
"/scripts/script.js"
);
$STYLES = array(
"/styles/style.css"
);
function prnt($string) {
echo $string;
}
function map($func, $arr) {
foreach($arr as $i) {
call_user_func($func, $i);
}
}
function linkScript($script) {
prnt("<script src='$script'></script>");
}
function linkStyle($style) {
prnt("<link rel='stylesheet' href='$style'/>");
}
function startPage($title, $script="", $imports=array(), $styles=array()) {
$pre_tags = array(
"<html>",
"<head>"
);
$post_tags = array(
"</head>",
"<body>"
);
map(prnt, $pre_tags);
prnt("<title>$title</title>");
map(linkScript, $IMPORTS);
map(linkScript, $imports);
map(linkStyle, $STYLES);
map(linkStyle, $styles);
map(prnt, $post_tags);
}
function genNav() {
$nav_links = array(
"Home"=>$HOME,
"Walkthroughs"=>$HOME . "/walkthroughs/",
"Dex"=>$HOME . "dex.php"
);
prnt("<div class='nav'>");
foreach ($nav_links as $key => $value) {
prnt("<a class='link' href='" . $value . "'/>" . $key . "</a>");
}
}
function endPage() {
$endTags = array(
"</body>",
"</html>"
);
}
?>
This is the error:
Warning: include(/base/startup.php): failed to open stream: No such file or directory in /var/www/html/index.php on line 2
Warning: include(): Failed opening '/base/startup.php' for inclusion (include_path='.:/usr/share/php') in /var/www/html/index.php on line 2
Test
Fatal error: Uncaught Error: Call to undefined function startPage() in /var/www/html/index.php:4 Stack trace: #0 {main} thrown in /var/www/html/index.php on line 4
Since you mentioned you are on a Linux machine, it looks like the issue is caused because of the / here. The / is considered the root directory of linux machine. So removing the / must most probably work:
<?php
include "base/startup.php"; // Try removing the slash.
echo "Test";
startPage("Home");
?>
Since you haven't enabled the display of errors, the issue would be, there's no /base in your system and it would have thrown an error, like Fatal: Include file not found., which is not displayed because of your configuration, instead it would have shown Error 500 silently.
Update
Along with the above error, after seeing your code, the next one is you need to quote the function names. So replace the stuff with:
map("prnt", $pre_tags);
prnt("<title>$title</title>");
map("linkScript", $IMPORTS);
map("linkScript", $imports);
map("linkStyle", $STYLES);
map("linkStyle", $styles);
map("prnt", $post_tags);
The next error is, you haven't included the global variables correctly inside the function. You need to use:
global $IMPORTS, $STYLES;
Now your code works as expected.
And finally finishing the endPage() function:
function endPage() {
$endTags = array(
"</body>",
"</html>"
);
foreach($endTags as $tag)
echo $tag;
}

ZipArchive: `failed to open stream: Is a directory`

I keep getting a failed to open stream: Is a directory error while trying to unzip a file with PHP.
This is usually an issue with the destination path.
However, in my case, the destination is fine: I can unzip different files using the same code, or unzip the same file without PHP.
The ZipArchive::extractTo documentation did not help. Nor did other SO threads on this error message.
FYI, this is a Q&A post.
Here is the source code as requested in a comment. I shared the Dropbox link publicly, seeing as this matter is dependent on the format of the ZIP input (/ path in ZIP file, see answer.)
/** Config **/
$url = 'https://www.dropbox.com/sh/nx5792q9syppaoo/AAAJZBWlGNAd_EkmQaFvEwe0a?dl=1';
/** Where to save **/
$zipped = ABSPATH . 'tmp/updates/dialogues.zip'; /* Keep in mind this is public-facing. */
$outputdirectory = ABSPATH . 'tmp/updates/testing'; /* The trailing slash is optinal. */
/** Download the dialogues **/
echo 'Fetching the dialogues...<br>';
if ( ( $dropboxfile = fopen( $url, 'r' ) ) === FALSE ) { /* == has higher precedent over = */
echo 'FATAL ERROR: could not open Dropbox file.';
die();
} else if ( file_put_contents( $zipped, $dropboxfile ) === FALSE ) {
echo 'FATAL ERROR: could not copy Dropbox file.';
die();
}
echo "Dialogues downloaded as zip OK. (See {$zipped})<br>";
/** Unzip the dialogues **/
print 'Unzipping...<br>';
$zip = new ZipArchive;
$res = $zip->open( $zipped );
if ( $res === TRUE ) {
// Does not work
// $zip->extractTo( ABSPATH . 'tmp/updates/testing' );
// Works
for( $i = 0 ; $i < $zip->numFiles ; $i++ ) {
if ( $zip->getNameIndex( $i ) != '/' && $zip->getNameIndex( $i ) != '__MACOSX/_' ) {
print $zip->getNameIndex( $i ) . '<br>';
$zip->extractTo( $outputdirectory, array($zip->getNameIndex($i)) );
}
}
$zip->close();
print 'Done unzipping.<br>';
} else {
print 'FATAL ERROR: unzipping failed.';
}
As it turned out, I had a / "folder" inside the ZIP archive.
This is confirmed by browsing the ZIP archive through the command-line. e.g., on OS X, using unzip -vl dialogues.zip gave me this:
Archive: dialogues.zip
Length Method Size Ratio Date Time CRC-32 Name
-------- ------ ------- ----- ---- ---- ------ ----
0 Defl:N 2 0% 08-22-15 12:07 00000000 /
2154 Defl:N 1064 51% 06-08-15 15:18 602c6793 dialogue001-en.txt
...
4379 Defl:N 1793 59% 08-21-15 13:56 75e1ef52 dialogue106-en.txt
70 Defl:N 39 44% 08-22-15 12:07 985af458 __MACOSX/_
-------- ------- --- -------
775512 343864 56% 312 files
The file is downloaded from Dropbox and I'd rather be able to work with it as it is.
So I just ended up filtering the list of files contained inside the ZIP archive, before deciding to unzip any given file:
print 'Unzipping...<br>';
$zip = new ZipArchive;
$res = $zip->open( $zipped );
if ( $res === TRUE ) {
//
for( $i = 0 ; $i < $zip->numFiles ; $i++ ) {
if ( $zip->getNameIndex( $i ) != '/' && $zip->getNameIndex( $i ) != '__MACOSX/_' ) {
print $zip->getNameIndex( $i ) . '<br>';
$zip->extractTo( $tempdirectory, array($zip->getNameIndex($i)) );
}
}
$zip->close();
print 'Done unzipping.<br>';
} else {
print 'FATAL ERROR: unzipping failed.';
}
Did not see this documented anywhere and wasted close to an hour on this. I hope this will help someone.
I'm still not clear as to whether the / reference inside of the ZIP file is correct. (Comments welcome.)

file_write failing in codeigniter

I have a piece of code written in codeigniter that reads a csv file and is supposed to write to a JSON file which i can read from later. The problem is that if I set a path for the file, the code fails but it works if i don't save a filepath.
Here is my code
$csvfile = array('csvfile' => $this->upload->data($upload_field_name));
$csvdata = $this->csvreader->parse_file($csvfile['csvfile']['full_path']);
$data['jsondata'] = json_encode($csvdata);
$path = '../uploads/'.$current_user_name.'.json';
if ( ! write_file( $path, $data['jsondata'],'w+' ) )
{
echo "File writing failed";
echo $path;
}
else
{
$this->load->view('dashboard');
}
I have looked for possible solutions but couldn't find any.

PHP on WAMP: problems uploading / creating a file

I get this error and I am not sure how to clear it. Not sure if its on my WAMP and if so I have two ini file, development and production, where should I look?
( ! ) Warning: move_uploaded_file(uploadedFiles/gal2.jpg): failed to open stream: No such file or directory in C:\wamp\www\fileupload.php on line 20
Call Stack
# Time Memory Function Location
1 0.0007 257960 {main}( ) ..\fileupload.php:0
2 0.0015 303448 move_uploaded_file ( ) ..\fileupload.php:20
( ! ) Warning: move_uploaded_file(): Unable to move 'C:\wamp\tmp\php71A.tmp' to 'uploadedFiles/gal2.jpg' in C:\wamp\www\fileupload.php on line 20
Call Stack
# Time Memory Function Location
1 0.0007 257960 {main}( ) ..\fileupload.php:0
2 0.0015 303448 move_uploaded_file ( ) ..\fileupload.php:20
The code is below:
$desiredPath = 'uploadedFiles/';
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
print "Picture Info"."<br>";
print_r($_FILES['picture']);
if (move_uploaded_file($_FILES['picture']['tmp_name'], $desiredPath.$_FILES['picture']['name']))
{
print 'File Upload Successful';
print '<div>';
print '<img width="300px" src="'.$desiredPath.$_FILES['picture']['name'].'">';
print '</div>';
}
else
{
print 'File Upload Failed with error code: '.$_FILES['picture']['error'];
}
}
Your code:
$desiredPath = 'uploadedFiles/';
Have you tested that the directory exists, before moving the file to it?
Code below:
if(!file_exists($desiredPath)) {
mkdir($desiredPath, 0755, true);
}
It's just a suggestion. I was trying to create an upload script myself and that little block of code solved all my problems

Weird Undefined offset: 0 error

I've the following PHP code that receives a file from an iOS app.
The information is received and for my debuggin $file is setted and has content in all its forms. The original value passed is btn-7.png and $file[0] = btn-7.
The function is processed and all images are copied to the system as I see them in the folder.... thus I dont know why i am getting this error.
The error appear in the first line available to the function that shows $_FILES[$file]
Does anyone have an idea why this is happening?
EDIT: As I said. No need to do var_dump because I can echo $file. Also I am debbugin from iOS console can't see non-JSON results, I only rely on PHP logs to know the actual error message.
EDIT2: as requested `var_dump(); (I am working from XCode, iOS dev console, not web browser)
ob_start();
var_dump($file);
$e = ob_get_contents();
ob_end_clean();
error_log($e, 0);
the result
[06-Jun-2013 17:58:26 UTC] string(9) "btn-7.png"`
the error
[06-Jun-2013 17:24:45 UTC] PHP Notice: Undefined offset: 0 in C:\xampp\htdocs\igym\classes\shareexercise.php on line 146
PHP
private function storeFile( $file )
{
$file = explode('.',$file);
$file = $file[0];
$msg['asd'] = $file;
echo json_encode($msg);
if( $_FILES[$file]["type"] !== "image/png" && $_FILES[$file]["size"] < 2048600 )
{
$error['error'] = 'There was a problem uploading your picture';
echo json_encode($error);
return 0;
}
if( move_uploaded_file( $_FILES[$file]['tmp_name'], IMGUPLOADDIR . '/' . $this->userID . '/' . $_FILES[$file]['name'] ) ) {
return true;
} else{
//$error['error'] = 'There was a problem uploading your picture';
//echo json_encode($error);
return false;
}
}
$_FILES is an associative array, not a numerical array:
From: php.net
$_FILES
An associative array of items uploaded to the current script via the HTTP POST method.
You should var_dump($_FILES) and see what the structure looks like. 0 doesn't exist because the index is the field name or some other string.
Aso: A tutorial on $_FILES

Categories