Php files attached and not attached statment - php

I have a code
if(count($_FILES) > 0) {
foreach($_FILES['fileAttach']['error'] as $status){
if($status === UPLOAD_ERR_OK) {
$fname[] = $_FILES['fileAttach']['name'][$Ccount];
$tmp_path[] = $_FILES['fileAttach']['tmp_name'][$Ccount];
$ftype[] = $_FILES['fileAttach']['type'][$Ccount];
}
$Ccount++;
}
} else { $fname[] = "0"; $tmp_path[] = "0"; $ftype[] = "0"; } // this not working
Then i want to use variables in function
SendEmails($ReCEmail,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftype,$tmp_path);
It works until files is attached, but if no i got error Notice: Undefined variable: fname in ... on line ..
function SendEmails($vasia,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftypes,$tmp_path) {
if(count($fname) == 0)
{ code without variables $fname,$ftypes,$tmp_path }
else {code with variables $fname,$ftypes,$tmp_path}
}
How to fix that?

if(count(array_filter($_FILES['fileAttach']['name'])) > 0) {
foreach($_FILES['fileAttach']['error'] as $key => $status){
if($status === 0) {
$fname[] = $_FILES['fileAttach']['name'][$key];
$tmp_path[] = $_FILES['fileAttach']['tmp_name'][$key];
$ftype[] = $_FILES['fileAttach']['type'][$key];
}
}
} else { $fname[] = "0"; $tmp_path[] = "0"; $ftype[] = "0"; }
and in your function change
if(count(array_filter($fname)) == 0)

If all $_FILES are error, then files array will be zero. So this error is printed
$fname[] = array();
$tmp_path[] = array();
$ftype[] = array();
foreach($_FILES['fileAttach']['error'] as $key => $status){
if($status === 0) {
$fname[] = $_FILES['fileAttach']['name'][$key];
$tmp_path[] = $_FILES['fileAttach']['tmp_name'][$key];
$ftype[] = $_FILES['fileAttach']['type'][$key];
}
}
if(count($fname)==0)
{ $fname[] = "0";$tmp_path[] = "0"; $ftype[] = "0"; }

Initialize your $fname array before the if:
$fname = array();
if($status === UPLOAD_ERR_OK) {
Confirm that your upload process is working by putting and echo after the if:
if($status === UPLOAD_ERR_OK) {
echo "Upload Status: " . $status . "<br>";
$fname[] = $_FILES['fileAttach']['name'][$Ccount];
If the echo output shows that $status != UPLOAD_ERR_OK, then $fname was not getting initialized, hence the Undefined variable error.
If the upload is failing, create another question containing the corresponding code snippets for that issue.

Related

PHP uploads the first TWO images only

I'm trying to upload images to my database, but it's acting really weird, because it uploads the first two images only. I have no idea why the first 2 and not the first only. The code is a little bit long because I'm executing another insert and then inserting the images. It's requested by an AJAX call, don't know if it's important or not. This is how it looks like:
if ($ok) {
//IMAGE UPLOAD
$filesize_error = 0;
$filesTempName = $_FILES['images']['tmp_name'];
$counted = count($filesTempName);
$allowed_types = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
if ($counted > $maxImage) {
$errorMsg[] = "Maximum 5 képet lehet feltölteni!";
} else {
for ($i = 0; $i < $counted; $i++) {
if (empty($filesTempName[$i])) {
$errorMsg[] = "Legalább egy képet ki kell választani!";
} else {
$detectedType = exif_imagetype($filesTempName[$i]);
if ($_FILES["images"]["size"][$i] > $maxSize) {
$filesize_error = 1;
$errorMsg[] = "Minden képnek 2 Mb-nál kisebbnek kell lennie!";
} elseif (!in_array($detectedType, $allowed_types)) {
$errorMsg[] = "A képek csak PNG/JPG/JPEG/GIF formátumban elfogadottak!";
} elseif ($filesize_error == 0) {
if (isset($_POST['mainimage']) && $_POST['mainimage'] != '') {
$placeholder = $_POST['mainimage'];
$mainimage = 'uploads/' . time() . $placeholder;
$stmt->execute();
$stmt->close();
$productid = $link->insert_id;
$statement = $link->prepare("INSERT INTO images(thumbnailimage, productid) VALUES(?, ?)");
for ($i = 0; $i < $counted; $i++) {
$file = $filesTempName[$i];
if (is_uploaded_file($file) && !empty($file)) {
$data = "uploads/" . time() . $_FILES["images"]["name"][$i];
move_uploaded_file($file, $data);
$statement->bind_param("si", $data, $productid);
$statement->execute();
}
}
$statement->close();
$link->close();
$success = true;
$_SESSION['successad'] = true;
} else {
$errorMsg[] = "Kérjük válassza ki a fő képet!";
$ok = false;
}
}
}
}
}
}
count($_FILES["images"]);
try count before temp name, try one var_dump on $_FILES
var_dump($_FILES);

Saving data in the database in yii2 during file upload action

I have a upload controller where by am also performing saving other data to the database. The file uploading to the folder is okay but saving the other details in the table doesn't happen
controller code
$images = $_FILES['evidence'];
$success = null;
$paths= ['uploads'];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
echo $success;
}
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$evidence->save();
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
After doing var_dump($evidence->save()) I get an error of Boolean false
You could have validation errors. Check $errors property
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$retSave = $evidence->save();
if($retSave == false)
{
var_dump($evidence->errors);
}
$output = [];
}
....

Glitches in code for deleting a folder after the zip is made

I have the code below.
It first create a dynamic folder with name like v3_12-02-2012-12873547839. Then it creates a subfolder called "image" and saves some jpeg images in the subfolder. Then it create a csv file and put it in "v3_12-02-2012-12873547839"
Then it creates a zip folder in the project folder with name "v3_12-02-2012-12873547839.zip"
function create_csv($version,$ctg,$cnt,$nt,$api)
{
$folder = $version."-".date('d-m-Y')."-".time();
if(!file_exists('./'.$folder))
{
mkdir('./'.$folder);
mkdir('./'.$folder.'/image/');
}
$cnt_table = "aw_countries_".$version;
$ctg_table = "aw_categories_".$version;
$off_table = "aw_offers_".$version;
$sizeof_ctg = count($ctg);
$cond_ctg = " ( ";
for($c = 0; $c < $sizeof_ctg ; $c++)
{
$cond_ctg = $cond_ctg." $ctg_table.category = '".$ctg[$c]."' ";
if($c < intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." OR ";
else if($c == intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." ) ";
}
$sizeof_cnt = count($cnt);
$cond_cnt = " ( ";
for($cn = 0; $cn < $sizeof_cnt ; $cn++)
{
$cond_cnt = $cond_cnt." $cnt_table.country = '".$cnt[$cn]."' ";
if($cn < intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." OR ";
else if($cn == intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." ) ";
}
$sizeof_nt = count($nt);
$cond_nt = " ( ";
for($n = 0; $n < $sizeof_nt ; $n++)
{
$cond_nt = $cond_nt." $off_table.network_id = '".$nt[$n]."' ";
if($n < intval($sizeof_nt-1))
$cond_nt = $cond_nt." OR ";
else if($n == intval($sizeof_nt-1))
$cond_nt = $cond_nt." ) ";
}
$sizeof_api = count($api);
$cond_api = " ( ";
for($a = 0; $a < $sizeof_api ; $a++)
{
$cond_api = $cond_api." $off_table.api_key = '".$api[$a]."' ";
if($a < intval($sizeof_api-1))
$cond_api = $cond_api." OR ";
else if($a == intval($sizeof_api-1))
$cond_api = $cond_api." ) ";
}
$output = "";
$sql = "SELECT DISTINCT $off_table.id,$off_table.name
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg;
$result = mysql_query($sql);
$columns_total = mysql_num_fields($result);
for ($i = 0; $i < $columns_total; $i++)
{
$heading = mysql_field_name($result, $i);
$output .= '"'.$heading.'",';
}
$output .= '"icon"';
$output .="\n";
while ($row = mysql_fetch_array($result))
{
for ($i = 0; $i < $columns_total; $i++)
{
$output .='"'.$row["$i"].'",';
}
$sql_icon = "SELECT $off_table.icon FROM $off_table WHERE id = '".$row['id']."'";
$result_icon = mysql_query($sql_icon);
while($row_icon = mysql_fetch_array($result_icon))
{
$image = $row_icon["icon"];
$id = $row["id"];
$icon = "./$folder/image/{$id}.jpg";
$icon_link = "$folder/image/{$id}.jpg";
file_put_contents($icon, $image);
}
$output .= '"'.$icon_link.'"';
$output .="\n";
}
$filename = "myFile.csv";
$fd = fopen ( "./$folder/$filename", "w");
fputs($fd, $output);
fclose($fd);
$source = $folder;
$destination = $folder.'.zip';
$flag = '';
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', $source);
if($flag)
{
$flag = basename($source) . '/';
}
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
if (strpos($flag.$file,$source) !== false) { // this will add only the folder we want to add in zip
if (is_dir($file) === true)
{
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $flag.$file), file_get_contents($file));
}
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString($flag.basename($source), file_get_contents($source));
}
$zip->close();
if (is_dir($folder))
{
$objects = scandir($folder);
foreach ($objects as $object)
{
if ($object != "." && $object != "..")
{
if (filetype($folder."/".$object) == "dir")
{
$object_inner = scandir($folder."/".$object);
foreach ($object_inner as $object_inner)
{
if ($object_inner != "." && $object_inner != "..")
{
unlink($folder."/".$object."/".$object_inner);
}
}
rmdir($folder."/".$object);
}
else
unlink($folder."/".$object);
}
}
reset($objects);
}
rmdir("./".$folder);
}
Now the problem is, when I am trying to delete the folder, the folder somehow doesn't seem to delete, though I can recursively delete all its contents. Even though the folder becomes empty at the end, it doesn't get deleted.
Error I am getting:
Warning: rmdir(./v3-02-12-2014-1417512727): Permission denied in C:\xampp\htdocs\projecthas2offer\appwall_dev\frontend\ajax.php on line 265
Instances of ZipArchive and/or RecursiveIteratorIterator still live and might still have their hands on your directory, so free them using unset( $zip, $files );

Why base64_encode() return null

I have a 22M docx file and want to encode it using base64_encode() function in php. But It always returns NULL value after running this function. Is there any limit file size or condition for this function. My code:
$handle = fopen($fullpathfile, "rb");
$imagestr = base64_encode(fread($handle, filesize($fullpathfile)));
fclose($handle);
Try this code
$fh = fopen($fullpathfile, 'rb');
$cache = '';
$eof = false;
while (1) {
if (!$eof) {
if (!feof($fh)) {
$row = fgets($fh, 4096);
} else {
$row = '';
$eof = true;
}
}
if ($cache !== '')
$row = $cache.$row;
elseif ($eof)
break;
$b64 = base64_encode($row);
$put = '';
if (strlen($b64) < 76) {
if ($eof) {
$put = $b64."\n";
$cache = '';
} else {
$cache = $row;
}
} elseif (strlen($b64) > 76) {
do {
$put .= substr($b64, 0, 76)."\n";
$b64 = substr($b64, 76);
} while (strlen($b64) > 76);
$cache = base64_decode($b64);
} else {
if (!$eof && $b64{75} == '=') {
$cache = $row;
} else {
$put = $b64."\n";
$cache = '';
}
}
if ($put !== '') {
echo $put;
}
}
fclose($fh);

giving error msg at wrong condition

<?php
$dir = 'dir';
$exclude = array('.','..','.htaccess');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
$res = opendir($dir);
if (strlen($q) < 3) {
echo "Search must be longer than 3 characters.<br><br>";
} else {
if (!( ($q == "mp3") || ($q == "wav") || ($q == ""))){
while(false!== ($file = readdir($res))) {
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) {
$nicefile = str_replace(".mp3", "", "$file");
$info = pathinfo($file);
if (($info["extension"] == "mp3") || ($info["extension"] == "wav")) {
echo "<a href='http://domainname/filename.php?name=$file'>$nicefile</a>";
echo "<br>";
}elseif(!isset($errorMsg)){
$errorMsg = "ERROR: File not found.<br><br>";
}else{}
}elseif(!isset($errorMsge)){
$errorMsge = "ERROR: File not found.<br><br>";
}else{}
}
if (isset($errorMsge)){echo $errorMsge;}
else{}
if (isset($errorMsg)){echo $errorMsg;}
else{}
}else{echo"ERROR: File not found.<br><br>";}
}
closedir($res);
?>
this is like a search script and the problem is #
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude))
{
it shows the error msg whether there is results or file named like search query or not.
any idea how to fix that?

Categories