Weird Undefined offset: 0 error - php

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

Related

Fatal error when trying to Parse a XML file to CSV in PHP

I am stuck on a bit of code for my program, where I am attempting to convert a XML document to CSV using a function in PHP. The code for the function is:
function createCsv($xml, $f)
{
foreach ($xml->children() as $item)
{
$hasChild = (count($item->children()) > 0) ? true : false;
if (!$hasChild)
{
$put_arr = array($item->getName(), $item);
fputcsv($f, $put_arr, ',', '"');
}
else
{
createCsv($item, $f);
}
}
}
And I am calling it in the main script here:
if (file_exists($FilePath))
{
echo "Converting, please stand by /n";
$xml = $_FILES;
$f = fopen('.csv', 'w');
createCsv($xml, $f);
fclose($f);
//calling function to convert the xml file to csv
$UploadDirectory = $UploadDirectory . basename($_FILES["fileToUpload"]["tmp_name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $UploadDirectory))
{
echo "The file has been uploaded and converted. Please click the link below to download it";
echo ''.$File.'';
//giving link to click and download converted CSV file
}
else
{
echo "There was a problem uploading and converting the file. Please refresh the page and try again.";
}
}
the error message I get when running the script through XAMPP is:
Fatal error: Uncaught Error: Call to a member function children() on array in C:\xampp\htdocs\XMLtoCSV\convert.php:4 Stack trace: #0 C:\xampp\htdocs\XMLtoCSV\convert.php(73): createCsv(Array, Resource id #3) #1 {main} thrown in C:\xampp\htdocs\XMLtoCSV\convert.php on line 4
Line 4 that it is referencing is the foreach statement in the createCSV function. I am really at a loss, and very new to PHP. I have had to teach myself PHP with mixed results, and any assistance would be highly appreciated.
You are considering $_FILES as the xml file, which is incorrect.
$_FILES is an associative array of uploaded files. You need to open the file and read the data. To do so you can use simplexml_load_file:
$xml = simplexml_load_file($_FILES["fileToUpload"]["tmp_name"]);
createCsv($xml, $f);

Strict Standards: Only variables should be passed by reference in /home/indiamaz/public_html/musicwala.cf/get-zip.php on line 31 [duplicate]

This question already has answers here:
Only variables should be passed by reference
(12 answers)
Closed 2 years ago.
I created a php project a few days ago, when this error was not coming, but since 2 days this error is coming, I do not know what the problem is, please help someone.
Strict Standards: Only variables should be passed by reference in /home/indiamaz/public_html/musicwala.cf/get-zip.php on line 31
Warning: filesize(): stat failed for /home/indiamaz/public_html/musicwala.cf/siteuploads/Gulabo Sitabo (2020) Mp3 Songs-musicwala.zip in /home/indiamaz/public_html/musicwala.cf/get-zip.php on line 51
##get-zip.php##
<?php
require_once('config/functions.php');
if(isset($_GET["code"]))
{
if(!empty($_GET["code"]) == true)
{
$zipname = __dir__.'/siteuploads/'.$_GET["name"].'-musicwala.zip';
if(file_exists($zipname))
{
$rp = str_replace(array("_","%20","+")," ",$_GET["name"]);
$size = filesize($zipname);
echo '
<div id="dlzip"> <a class="dwnLink2" rel="nofollow" href="/siteuploads/'.$_GET["name"].'-musicwala.zip">download Zip Of '.$rp.' - '.vars::bytes($size).'</a>
<center> <b style="color:red">Note*Only 10 Files Compressed Due To Server Bandwidth Limition!</b></center></div>
';
exit;
}
$url = vars::$siteUrl.$_GET["code"];
$data = vars::cURL($url);
$match = preg_match_all("|<!-- WapkaHost.Com Web Solution :: File List -->(.*?)<!-- WapkaHost.Com Web Solution :: File List Complete -->|mis",$data,$cats);
$rp = str_replace("/download/",vars::$siteUrl."download/",$cats[1][0]);
preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $rp,$urls);
$count = count($urls[1]);
if($count < 12){
// $zipname = __dir__.'/siteuploads/'.$_GET["name"].'-musicwala.zip';
$files="";
foreach($urls[0] as $url)
{
$name = end(explode("/",$url));
// echo $name;
$rm = preg_replace("|https://(.*?)/(.*?)/(.*?)/{$name}|mis","http://musicwala.cf/files/download/id/$3",$url);
$headers = get_headers($rm);
$location = str_replace("Location: /","",$headers[3]);
$files[] = $location;
}
$zip = new ZipArchive; $zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file)
{
// echo $file;
$zip->addFile($file);
}
$zip->close();
$rp = str_replace(array("_","%20","+")," ",$_GET["name"]);
$size = filesize($zipname);
echo '
<div class="download">
<div id="dlzip"> <a class="dwnLink2" rel="nofollow" href="/siteuploads/'.$_GET["name"].'-musicwala.zip">download Zip Of '.$rp.' - '.vars::bytes($size).'</a> </div>
<center> <b style="color:red">Note*Only 10 Files Compressed Due To Server Bandwidth Limition!</b></center>
</div>
';
}
else
{
echo "Sorry Max File Size Allow 10";
}
}
else
{
echo "Faild To Compress!";
}
}
?>
Regarding the Strict Standards error on the end function, from the documentation:
Parameters (1)
array. The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.
explode is a function that returns an array - not a real variable, Since end modifies real variables, you must set the return value of explode to a separate real variable and send that variable to end.
// $url = __dir__.'/siteuploads/'.$_GET["name"].'-musicwala.zip';
foreach($urls[0] as $url)
{
$exploded_array = explode("/", $url);
$name = end( $exploded_array );
// ...
As a guess, the OP's code should actually be foreach ( $urls as $url ){ (not $urls[0]) but that isn't specifically related to the error code.
The second message: Warning: filesize(): stat failed for.. is a bit harder to diagnose here. Possibly the file wasn't created, maybe it's too large (filesize can get weird over 2GB files), or some other issue. Try using the following to determine more of an error message (docs here).
var_dump( $zip->getStatusString() ); // Returns a string with the status message on success or false on failure.
var_dump( $zip->close() ); // Returns true on success or false on failure.

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.

Trying to validate a folder being dynamically created using PHP

I am trying validate: whether or not the folder I am attempting to create exists. Sure, I get a message... an error message :/ telling me it does! (if it doesn't exist, no error message, and everything goes as planned).
It outputs this error message
Directory exists
Warning: mkdir() [function.mkdir]: File exists in /home/***/public_html/***/formulaires/processForm-test.php on line 75
UPLOADS folder has NOT been created
The current code I use is this one:
$dirPath = $_POST['company'];
if(is_dir($dirPath))
echo 'Directory exists';
else
echo 'directory not exist';
function ftp_directory_exists($ftp, $dirPath)
{
// Get the current working directory
$origin = ftp_pwd($ftp);
// Attempt to change directory, suppress errors
if (#ftp_chdir($ftp, $dirPath))
{
// If the directory exists, set back to origin
ftp_chdir($ftp, $origin);
return true;
}
// Directory does not exist
return false;
}
$result = mkdir($dirPath, 0755);
if ($result == 1) {
echo '<br/>'.$dirPath . " has been created".'<br/>';
} else {
echo '<br/>'.$dirPath . " has NOT been created".'<br/>';
}
I added the middle part recently (I don't know if that would even have an impact). The one that starts off with "function ftp_directory_exists($ftp, $dirPath)"
Use file_exists() to check if a file / directory exists:
if(!file_exists('/path/to/your/directory')){
//yay, the directory doesn't exist, continue
}
The function ftp_directory_exists you added won't have any impact on your code as it is never called...
You might tried something like this (not tested...) :
$dirPath = $_POST['company'];
$dirExists = is_dir($dirPath);
if(!dirExists)
$dirExists = mkdir($dirPath, 0755);
echo '<br/>'.$dirPath . (($dirExists)? "" : "DO NOT") . " exists".'<br/>';

Can't move/fine APC Uploaded file

As a bit of a follow up to Javascript form won't submit (to view the code I am using visit that link) I am now encountering a problem that I cannot find the file that has been uploaded.
I have added $files = apc_fetch('files_'.$_POST['APC_UPLOAD_PROGRESS']); to the top of my page and this is the output of print_r($files);
Array
(
[theFile] => Array
(
[name] => tt1.mp4
[type] => video/mp4
[tmp_name] => /tmp/php2BEvy7
[error] => 0
[size] => 1050290
)
)
However when I try to run the following code:
if (file_exists($files['theFile']['tmp_name'])) {
$webinarType = strcmp($files['theFile']['type'], 'video/mp4');
if($webinarType == 0) {
$webinarFile = $fileTitle;
$webinarTempName = $files['theFile']['tmp_name'];
} else {
echo 'Webinar must be .mp4';
}
} else {
echo "No File";
}
I get the No File output.
I have ssh'd into the server and the file is not in /tmp/, /path/to/public_html/tmp/ or path/to/file/tmp/ all of which exist.
I have tried to use move_uploaded_file() but as this is executed on all file inputs I can't get the tmp_name dynamically due to my limited knowledge of javascript.
tl;dr version; Where is my file gone and how can I find it?
NOTE; This form did work before the APC intevention and I am running wordpress in case that affects anything.
Fixed this one on my own as well.
In the progress.php file (found on the other question) I modified the elseif statement with this:
elseif(($s_progressId = $_POST['APC_UPLOAD_PROGRESS']) || ($s_progressId = $_GET['APC_UPLOAD_PROGRESS']))
{
// If the file has finished uploading add content to APC cache
$realpath = realpath($PHP_SELF);
$uploaddir = $realpath . '/tmp/';
foreach ($_FILES as $file) {
if(!empty($file['name'])) {
$uploaded_file = $file['name'];
$moveme = $uploaddir.$uploaded_file;
move_uploaded_file($file['tmp_name'], $moveme);
}
}
apc_store('files_'.$s_progressId, $_FILES);
die();
}
That way I could iterate through the $_FILES array without knowing the name of the input. I noticed that it loops through a couple of times hence the if(!empty()) however in hindsight it's probably best practice anyway.

Categories