Accessing array values created in foreach loops - php

I am trying to display an error if a file does not upload. The crux of my problem is that my $status() array doesn't return the values I append in an if statement within a foreach loop.
Can someone enlighten me as to what is going on and what I am doing wrong? I'd like the status values in the foreach loop to append and return outside the loop.
Code below.
$status = array();
// Check that file within size restrictions, then upload.
foreach($request->getFiles() as $file)
{
$file_dir = sfConfig::get("sf_data_dir") . '/retail/order/' . $order_id . '/';
if (!is_dir($file_dir))
{
mkdir($file_dir, 0777, true);
}
$maxsize = 332027;
if(($file['size'] >= $maxsize) || ($file['size'] == 0))
{
$status[] = 0;
}
else
{
move_uploaded_file($file['tmp_name'], $file_dir . $file['name']);
$attachment = new Attachment();
$attachment->setName($file['name']);
$attachment->setPath($file_dir);
$attachment->setSize($file['size']);
$attachment->setCreatedTs('now');
$attachment->save();
$app_attachment = new ApendedAttachment();
$app_attachment->setAttachmentId($attachment->getAttachmentId());
$app_attachment->setWebOrderId($order_id);
$app_attachment->setCreatedTs('now');
$app_attachment->save();
$status[] = 1;
}
}
if (in_array(1, $status))
{
$this->getUser()->setFlash('success', 'Thank you. Your cart has been saved.');
}
else
{
$this->getUser()->setFlash('error', 'Please upload files less than 20MB.');
}
$this->redirect('order/detail?id=' . $order->getWebOrderId());

You are not assigning values to the status array correctly. You probably want to increment an index as you go through the array of files:
$i = 0;
for each(){
...
$status[$i] = 1;
...
$i++;
}
Sorry for the bad code format. Doing this on my mobile device.

Related

PHP Is there a way to display my list from the foreach separately?

I want to display the links separately. One list would include all the .html links and the other all the .jpg links.
right now it displays this and I understand why it is doing it, but when i do another foreach outside or even right before the echo, its like nothing is passing into it.
.jpg
.html
.jpg
.html
I need it to display like this
HTML-Backup HTML
.jpg .html
.jpg .html
php Code
$array = array();
$html= "";
$htmlBackup= "";
if(file_exists("uploads/" . $_POST["prefix"] .'/'))
{
$dir = 'uploads/' . $_POST["prefix"] . '/';
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir));
$prefixDir = scandir($dir);
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.' </br>';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.' </br>';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
}
}
}
Don't put <br> at the end of each echo. Do it after the inner loop so all links from the same directory will be on the same line.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.'';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.'';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
echo "<br>";
}
}
I found a solution by including arrays.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.html") !== false || strpos($lastDir, "H5.html") !== false)
{
//variable to store the list of dir
array_push($html_array, $lastDir);
array_push($html_dir,$secondDir.'/'.$lastDir);
}
else if(strpos($lastDir, "HTML5.jpg") !== false || strpos($lastDir, "H5.jpg")!== false )
{
//variable to store list of dir
array_push($html_backup_array, $lastDir);
array_push($html_backup_dir,$secondDir.'/'.$lastDir);
}
}
}
}
and then display them under in another foreach as I want
if(!empty($html_array))
{
echo "<p>";
echo ("<p><span class='heading'>HTML5 Units</span></p>");
foreach (array_combine($html_dir, $html_array) as $html_dirr => $html_arrays)
{
echo (''.$html_arrays.'');
echo "<br>";
}
echo "</p>";
}

Get the position number of a file in the $_FILES array

I have an image manager with preview and I need to know the position number of the image in the $_FILES array so I can know which one I have to delete and upload the new one. The images names are just numbers (i.e. 1.jpg, 2.jpg, etc).
For example, I have 6 images in preview (6 inputs) and I need to replace some of them so I click the remove buttom for those to replace and then I drag and drop the new ones. When I click upload I need to know how many inputs are filled with an image and the position of them in the $_FILES array so I don't delete the wrong ones.
If one of the previews are removed and are not replaced I have to delete the file from server, I'm thinking on using hidden inputs with a value of 0/1 to know if the user wants to remove the image, these values are set by the remove image button (each input have it's own). I'm having some trouble thinking how to get this done.
This is what I already have:
$file_count = count($_FILES['file']['tmp_name']);
$id = isset($_GET['id']) && $_GET['id'] != '' ? (int) $_GET['id'] : 0;
if ($id !== 0) {
$path = realpath('/home/aet/websites/images/property/' . $id . '/');
if ( FALSE !== $path && is_dir($path) ) {
$url = [];
for($i = 0; $i < $file_count; $i++) {
if ($_FILES['file']['name'][$i] != '') {
$path = $path . (++$i) . '.jpg';
if (file_exists($path)) unlink($path);
if (move_uploaded_file($file_count[$i], $path)) {
$url[] = 'http://static.website.com/images/property/' . $id . '/' . (++$i) . '.jpg';
} else die('Error uploading image (' . (++$i) . ')' );
} else {
// first we have to check if the user requested the file deletion
// (no image preview in the html)
//unlink($path);
}
}
if ( !empty($url) ) {
$mysqli = $staff->aet->getAetSql();
$mysqli->set_charset('utf8');
$mysqli->autocommit(FALSE);
$value = NULL;
if ($stmt = $mysqli->prepare('INSERT INTO img (path, property) VALUES (?, ?)')) {
$stmt->bind_param('si', $value, $id);
foreach ($url as $key => $value) {
$stmt->execute();
}
if ( $mysqli->commit() ) {
header('Location: /property');
} else die('DB Error.');
}
}
} else die('Error (path does not exist)');
}

Multiple files upload with array name in CodeIgniter

i've problem with my code here.
The case is, i have multiple input file form, i need to get name of current array (which contain database id) and upload the file from it.
Here's in my views
foreach($result2 as $result3)
{
print "
<tr>
<td><input type=file name=baddismantling[".$result3['iddeployment']."] size=20></td>
</tr>
";
}
so, there'll be various of upload form and name too, but it always unique.
and after user click submit button, that form will call function in my controller, and here's
the function that handled it
private function _ready_to_start($sessiondata)
{
if($post['doSubmitDismantlingAction'] == 'uploadbad')
{
while ($fruit_name = current($_FILES['baddismantling']['name']))
{
if($fruit_name != false)
{
//GET ID FROM DEPLOYMENT DB
$deploymentid = key($_FILES['baddismantling']['name']);
$file = "baddismantling[$deploymentid]";
if(!$this->upload->do_upload($file))
{
$check3[] = $this->upload->display_errors()." target: ".$file;
}
$check2 = $this->upload->data();
}
next($_FILES['baddismantling']['name']);
}
//SHOW RESULT WHILE UPLOADING
print implode($check3);
}
}
as you see,i've successful with getting the
$deploymentid = 1
as i wish...but, browser give me :
You did not select a file to upload. target: baddismantling[1]
anyone can give me suggestion about that problem?or there's something wrong with my code?
as note :
there's no problem with configuration $this->upload-> because i've
successfull with a single upload form only
thanks for your time with my question, and i've "luckily" got my own solving from question above with this code :
$check3 = array();
$count = 0;
$check = ($_FILES == true ? count($_FILES['baddismantling']['name']) : (0));
while ($fruit_name = ($check == true && $check > 0 ? current($_FILES['baddismantling']['name']) : (false)) || $count <= $check){
$count++;
if($fruit_name == true && key($_FILES['baddismantling']['name']) == true)
{
$iddeployment = key($_FILES['baddismantling']['name']);
/*THIS PART WAS HELPING ME*/if($_FILES['baddismantling']['name'][$iddeployment] == true)
{
$_FILES['userfile']['name'] = $_FILES['baddismantling']['name'][$iddeployment];
$_FILES['userfile']['type'] = $_FILES['baddismantling']['type'][$iddeployment];
$_FILES['userfile']['tmp_name'] = $_FILES['baddismantling']['tmp_name'][$iddeployment];
$_FILES['userfile']['error'] = $_FILES['baddismantling']['error'][$iddeployment];
$_FILES['userfile']['size'] = $_FILES['baddismantling']['size'][$iddeployment];
if (!$this->upload->do_upload())
{
$check3[] = $this->upload->display_errors();
}
else
{
$uploaddata = $this->upload->data();
$result['badfilename'] = $uploaddata['full_path'];
$result['id'] = $iddeployment;
$sql = $this->sql->updatedismantlingBAD($result);
}
}
}
next($_FILES['baddismantling']['name']);}

How to retrieve files on a directory in list using PHP

How may i able to retrieve different file extensions in a certain directory. Let say i have a folder named "downloads/", where inside that folder are different types of files like PDFs, JPEGs, DOC files etc. So in my PHP code i wanted those files be retrieved and listed with there file names and file extensions. Example: Inside "downloads/" folder are different files
downloads/
- My Poem.doc
- My Photographs.jpg
- My Research.pdf
So i wanted to view those files where i can get there file names, file extensions, and file directories. So in view will be something like this
Title: My Poem
Type: Document
Link: [url here]
Title: My Photographs
Type: Image
Link: [url here]
Title: My Research
Type: PDF
Link: [url here]
Anyone knows how to do it in php? Thanks a lot!
It's pretty simple. To be honest i don't know why didn't you searched on a php.net. They got whole lots of examples for this. Check it in here: click
Example:
<?php
function process_dir($dir,$recursive = FALSE) {
if (is_dir($dir)) {
for ($list = array(),$handle = opendir($dir); (FALSE !== ($file = readdir($handle)));) {
if (($file != '.' && $file != '..') && (file_exists($path = $dir.'/'.$file))) {
if (is_dir($path) && ($recursive)) {
$list = array_merge($list, process_dir($path, TRUE));
} else {
$entry = array('filename' => $file, 'dirpath' => $dir);
//---------------------------------------------------------//
// - SECTION 1 - //
// Actions to be performed on ALL ITEMS //
//----------------- Begin Editable ------------------//
$entry['modtime'] = filemtime($path);
//----------------- End Editable ------------------//
do if (!is_dir($path)) {
//---------------------------------------------------------//
// - SECTION 2 - //
// Actions to be performed on FILES ONLY //
//----------------- Begin Editable ------------------//
$entry['size'] = filesize($path);
if (strstr(pathinfo($path,PATHINFO_BASENAME),'log')) {
if (!$entry['handle'] = fopen($path,r)) $entry['handle'] = "FAIL";
}
//----------------- End Editable ------------------//
break;
} else {
//---------------------------------------------------------//
// - SECTION 3 - //
// Actions to be performed on DIRECTORIES ONLY //
//----------------- Begin Editable ------------------//
//----------------- End Editable ------------------//
break;
} while (FALSE);
$list[] = $entry;
}
}
}
closedir($handle);
return $list;
} else return FALSE;
}
$result = process_dir('C:/webserver/Apache2/httpdocs/processdir',TRUE);
// Output each opened file and then close
foreach ($result as $file) {
if (is_resource($file['handle'])) {
echo "\n\nFILE (" . $file['dirpath'].'/'.$file['filename'] . "):\n\n" . fread($file['handle'], filesize($file['dirpath'].'/'.$file['filename']));
fclose($file['handle']);
}
}
?>
You could use glob & pathinfo:
<?php
foreach (glob(__DIR__.'/*') as $filename) {
print_r(pathinfo($filename));
}
?>
You will try this code :
$Name = array();
$ext = array();
$downloadlink = array();
$dir = 'downloads'
while ($file= readdir($dir))
{
if ($file!= "." && $file!= "..")
{
$temp = explode(".",$file);
if (count($temp) > 1)
{
$Name[count($Name)] = $temp[0];
swich($ext)
{
case "doc" :
{
$ext[count($ext)] = "Document";
break;
}
[...]
default :
{
$ext[count($ext)] = "Error";
break;
}
}
$downloadlink[count($downloadlink)] = "http://yourdomain.com/".$dir."/".$file;
}
}
}
closedir($dir);
for($aux = 0; $aux < count($Name); $aux++)
{
echo "Name = " . $Name[$aux]."<br />
Type = " . $ext[$aux]."<br/>
Link = " . $downloadlink[$aux]."<br/>
";
}

PHP auto increment file names

I have a file uploader and I want the filenames to auto increment number. I don't feel the need to use a database to do this and I want to keep the code relatively clean, I'm pretty new in file upload and management in PHP so I'm not exactly sure what to do. Could anyone direct me in the right path?
Here is my current code, it just uses an md5 of a bunch of seeds.
<?php
if(isset($_FILES['imagedata']['tmp_name']))
{
// Directory related to the location of your gyazo script
$newName = 'images/' . substr(md5(rand() . time()), 0, 20) . '.png';
$tf = fopen($newName, 'w');
fclose($tf);
move_uploaded_file($_FILES['imagedata']['tmp_name'], $newName);
// Website
echo 'http://davidknag.com/' . $newName;
}
?>
<?php
if(isset($_FILES['imagedata']['tmp_name'])) {
// Directory related to the location of your gyazo script
$fileCount = count (glob ('images/*.png'));
$newName = 'images/' . ( $fileCount + 1) . '.png';
$tf = fopen($newName, 'w');
fclose($tf);
move_uploaded_file($_FILES['imagedata']['tmp_name'], $newName);
// Website
echo 'http://davidknag.com/' . $newName;
}
It just counts all .png files in the directory, increments that number by 1 and uses that as its filename.
Note that if you're storing a very large amount of files (say 10.000s), it's faster to use Joseph Lusts' method, but otherwise this will work jus tfine.
You can just have a basic text file in the given folder. Store the number in there. Read it out and increment it as needed.
It would be easiest to make a function like getNextNumber() that did the above and then you could use it as needed. You could also do this in a $_SERVER[] variable, but it would need to be reloaded from the file on server restart.
<?PHP
// a basic example
function getNextNumber() {
$count = (int)file_get_contents('yourFile.txt');
$count+=1;
file_put_contents('yourFile.txt',$count);
return $count;
}
?>
Note that if you are using this a great deal, you'll need a more advanced sequence generator since this will perform 2 file IO's on each call.
You can try the code below. It creates a file with .png extension and unique name in outdir/
$filename = uniqFile('outdir', '.png');
move_uploaded_file($_FILES['imagedata']['tmp_name'], $filename);
function uniqFile($dir, $ext)
{
if (substr($dir, -1, 1) != '/')
{
$dir .= '/';
}
for ($i=1; $i<999999; $i++)
{
if (!is_file($dir . $i . $ext))
{
return $i . $ext;
}
}
return false;
}
A little late in the game but this pair of functions does the trick and follows the familiar format of the filename followed by "(n)" and then the file extension:
incrementFileName() returns the updated filename incremented by 1 with input filename and destination directory. splitLast() is a modification of explode to only split on the last occurrence of some substring.
function incrementFileName($name,$path){
if (!array_search($name,scandir($path))) {
return $name;
} else {
$ext=splitLast($name,".")[1];
$baseFileName=splitLast(splitLast($name,".")[0],"(")[0];
$num=intval(splitLast(splitLast($name,"(")[1],")")[0])+1;
return incrementFileName($baseFileName."(".$num.").".$ext,$path);
}
}
function splitLast($string,$delim) {
$parts = explode($delim, $string);
if (!$parts || count($parts) === 1) {
$before=$string;
$after="";
} else {
$after = array_pop($parts);
$before=implode($delim, $parts);
}
return array($before,$after);
}
When handling upload, set your filename with it:
$fileName = incrementFileName($_FILES['file']['name'], $path);
This will return someFileName(1).jpg or someFileName(2).jpg etc.
function enc($length = "string") {
if(!is_numeric($length) || $length > 255 || $length < 1){
$length = rand("3","6");
}
// $randomID = substr(uniqid(sha1(crypt(md5("".time("ysia", true)."".rand())))), 0, $length);
$randomID = genUnique($length);
$count = 0;
while(glob("$randomID.*") || fetch("select * from `short` where `short` = '$randomID'") || fetch("select * from `images` where `name` = '$randomID'") || glob("img/$randomID.*") || is_numeric($randomID)){
if($count > 20){
$length++;
}
$randomID = genUnique($length);
$count++;
}
return $randomID;
}
this code is pretty old (not even using mysqli), but i figured i'd include it first
<?php
include_once "functions.php";
if(!isset($_REQUEST['api'])){
notfound("");
}
$con = connect();
$key = $_REQUEST['api'];
$ver = $_REQUEST['version'];
if($ver != "10-26-2016" || $key == "zoidberg")
{
die("Please upgrade your in4.us.exe by logging in and clicking download.");
}
if($key == "nokey"){
die("You need to keep the exe with the ini file to pair your api key. Copy ini file to same directory or redownload.");
}
$key = mysql_real_escape_string($key);
$findkey = fetch(" SELECT * from `users` where `key` = '$key' ");
if(!is_array($findkey)){
die("No user with that API Key found. Configure the INI File using your api key on in4.us");
}
$user = $findkey['username'];
if(isset($_FILES['imagedata']['tmp_name'])){
$newName = enc();
$tf = fopen("img/".$newName.".png", 'w');
fclose($tf);
move_uploaded_file($_FILES['imagedata']['tmp_name'], "img/".$newName.".png");
$domain = $_SERVER['HTTP_HOST'];
date_default_timezone_set('America/New_York');
$mysqldate = date("Y-m-d H:i:s");
$qry = mysql_query("INSERT INTO `images` (`name`, `added`, `dateadded`) VALUES ('$newName', '$user', '$mysqldate');");
if(!qry){
die('Invalid query: ' . mysql_error());
}
echo "http://$domain/$newName.png";
disconnect($con);
}else{
notfound("");
}
?>

Categories