PHP: How to create foreach loop (simple code) - php

I am new to PHP and have created a little code for a file upload on a form.
The code works fine but I was wondering if I could achieve the same using a foreach loop so that it could also handle more files and I dont have to write a separate line for each of them.
Can someone here help me with this and tell me how to write it properly.
My Code (working):
session_start();
$varUID = $_POST['UID'];
$varSender = $_SESSION['email'];
$varFile1 = $_FILES["file1"]["name"];
$varExt1 = pathinfo($varFile1, PATHINFO_EXTENSION);
$varFile2 = $_FILES["file2"]["name"];
$varExt2 = pathinfo($varFile2, PATHINFO_EXTENSION);
$varFile3 = $_FILES["file3"]["name"];
$varExt3 = pathinfo($varFile3, PATHINFO_EXTENSION);
move_uploaded_file($_FILES["file1"]["tmp_name"], "uploads/" . $varUID . "_1" . "." . $varExt1);
move_uploaded_file($_FILES["file2"]["tmp_name"], "uploads/" . $varUID . "_2" . "." . $varExt2);
move_uploaded_file($_FILES["file3"]["tmp_name"], "uploads/" . $varUID . "_3" . "." . $varExt3);
echo $varUID;
Thanks for any help with this,
Tim

foreach ($_FILES as $key => $file) {
$name = $file["name"];
$ext = pathinfo($name, PATHINFO_EXTENSION);
preg_match('/(\d+)$/', $key, $match); // get 2 out of "file2"
$nr = $match[1];
move_uploaded_file($file["tmp_name"], "uploads/" . $varUID . "_" . $nr . "." . $ext);
}

$varUID = $_POST['UID'];
$varSender = $_SESSION['email'];
$i = 1;
foreach ($_FILES as $key => $file) {
$varFile = $file[$key]["name"];
$varExt = pathinfo($varFile, PATHINFO_EXTENSION);
move_uploaded_file($file[$key]["tmp_name"], "uploads/" . $varUID . "_" . $i . "." . $varExt);
$i++;
}
echo $varUID;

Related

php truncate file path to display file name

Trying to display filename but code is resulting in full file url displaying
if (trim($s) == "") continue;
$arrfilename = explode("\/", $s);
$shortfilename = $arrfilename[count($arrfilename)-1];
$path_parts = pathinfo($s);
$dir = $path_parts['dirname'];
$basename = $path_parts['basename'];
$ext = $path_parts['extension'];
$fn = $path_parts['filename'];
$sliderimage = $dir . '/' . $fn . '.' . $ext;
if (!file_exists($sliderimage) && !file_exists('../' . $sliderimage)) $sliderimage = $s;
$output .= '[setslideshowlinkattributes ssrs="' . $s . '"]<img src="/' . $sliderimage . '" alt="' .$shortfilename . '" /></a>';
}
$output .= '</div>';
$output .= ' <div id="htmlcaption" style="display: inline;">' . $this->options->slideshowcaption . '</div>';
$output .= '</div>';

Search for pdf files

I have one little question, this is my code to list all files from a folder and subfolders;
if ($handle = opendir($dir)) {
$allFiles = array();
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($dir . "/" . $entry)){
$allFiles[] = "D: " . $dir . "/" . $entry;
}else{
$extension = strtoupper(pathinfo($entry, PATHINFO_EXTENSION));
$fileNoExten = pathinfo($entry, PATHINFO_FILENAME);
$directory = substr(str_replace('/', ' > ', $dir), $rootLenOnce + 3);
$listagem .= '<tr>';
$listagem .= "<td><a href='../" . $dir . "/" . $entry . "' ' target='_blank'>" . $entry . "</a></td>";
//$listagem .= "<td><small>" . $directory . "</small></td>";
$listagem .= "<td>" . $extension . "</td>";
$listagem .= "<td><a class='download-cell' href='../".$dir ."/". $entry."' ' download> <i class='fa fa-download' ></i></a></td>";
$listagem .= "<td class='display-none'>" . $fileNoExten . "</td>";
$allFiles[] = "F: " . $dir . "/" . $entry;
$listagem .= '</tr>';
echo "<pre>"; print_r(glob("*.pdf")); echo "</pre>";
}
}
}
closedir($handle);
foreach($allFiles as $value){
$displayName = substr($value, $rootLen + 4);
$fileName = substr($value, 3);
$linkName = str_replace(" ", "%20", substr($value, $pathLen + 3));
if (is_dir($fileName)) {
myScanDirPdf($fileName, $level + 1, strlen($fileName),$rootLenOnce);
}
}
}
return $listagem;
}
what i need is to filtrate the search, to search only .pdf files.
Someone can help me plz!
Thks!
i try with the glob function, but not with great results.
Thks!
When you are looping through each file, you can use
if(stripos($fileName, ".pdf"))
Hope this will help
I have one more suggestion in listing all the files and subfolders.
You can use Recursive Iterator
$folderName = $_POST['folderName'];
$dir = new RecursiveDirectoryIterator($folderName);
$it = new RecursiveIteratorIterator($dir);
foreach ($it as $fileinfo) {
if ($fileinfo->isDir()) {
}elseif ($fileinfo->isFile()) {
$fileName = $fileinfo->getFileName();
if(stripos($fileName, ".pdf")) {
//do what you need to do
}
}
}

PHP rename deletes some of the files?

I have the following photos:
product-1.jpg
product-2.jpg
product-3.jpg
product-4.jpg
I have the following request (came from jQuery's sortable):
action=save&photos=photo[]=4&photo[]=2&photo[]=3&photo[]=1
I've tried this:
<?php
if($_POST) {
if($_POST['action'] == 'save') {
parse_str($_POST['photos'], $photos);
$id_new = 1;
foreach($photos['photo'] as $id) {
rename(dirname(__FILE__) . '/product-' . $id . '.jpg', dirname(__FILE__) . '/product-' . $id_new . '.jpg');
$id_new++;
}
}
}
?>
But rename deletes some of the photos.
You have photos ids 4, 3, 2, 1 and you are renaming the files in the reverse order so:
if you rename 4 to 1 then 1 is overwritten and 4 disappear
if you rename 3 to 2 then 2 is overwritten and 3 disappear
That's why you remain with less files.
As #MVG1984 suggested in a comment you can rename those files into another folder like:
$path = dirname(__FILE__);
$tmpPath = $path . '/tmp';
mkdir($tmpPath);
$id_new = 1;
foreach($photos['photo'] as $id) {
rename($path . '/product-' . $id . '.jpg', $tmpPath . '/product-' . $id_new . '.jpg');
$id_new++;
}
for ($i = 1; $i < $id_new; $i++) {
rename($tmpPath . '/product-' . $i . '.jpg', $path . '/product-' . $i . '.jpg');
}
rmdir($tmpPath);

No error when creating zip, but it doesn't get created inside directory

I wrote this code to create a ZIP file of my uploaded attachment, wp application has an option to uploads pdf , those upload pdf will stored under upload directory , i got the result success with no error's but still zip is not get created inside the directory server . Here's the code:
// Code for Getting links (Path)of Attachements
$list = array();
// $count = 1;
foreach($applicants as $key=>$val) {
$cat_id =explode("-", $key);
foreach($val as $appkey=>$appval) {
// if(($appval['name'])=='Navn') {
// $names = $count . '_' . $cat_id[1] . '_' . stripslashes($appval['value']) ;
// }
if(($appval['name']) == ' (PDF)') {
$attach = stripslashes($appval['value']) ;
$list[] = $cat_id[0].'-'. $cat_id[1].'/' . $attach; // Attaching ID and Category to attachement file name
}
}
// $count++;
}
$paths = array();
foreach ($list as $list) {
$data = explode('/',$list);
$pdfpath='../../' . $data[7] . '/' . $data[8] . '/' . $data[9] . '/' . $data[10];
$name=(string)$data[0] . '_' . $data[10];
$paths[] = $pdfpath."*".$name;
}
$zip = new ZipArchive;
$rand = rand(0,5000);
// Generating random file name for zipcode
if ($zip->open($rand . 'appl_attachments.zip', ZipArchive::CREATE)) {
// add files to zip from the path i.e uplaods(Folder) if file exists
foreach ($paths as $value ) {
$path=explode("*", $value);
if(file_exists($path[0])) {
$zip->addFile($path[0],$path[1]);
}
}
$zip->close();
Finally got a fix on the issue , update the changes on the pdf path .
Here is the changes on the code :
$paths = array();
foreach ($list as $list) {
$data = explode('/',$list);
$pdfpath='../../' . $data[6] . '/'. $data[7] . '/' . $data[8] . '/' . $data[9] ;
$name=$data[9];

Strange PHP issue

My function looks like that
protected function make_js_link($list, $folder, $parentdir = "js") {
$links = array();
$list = explode(',', $list);
foreach ($list as $name) {
$dir = $parentdir . "/";
if (is_string($folder))
echo $folder . "/";
$links[] = '<script src="' . $dir . trim($name) . '.js"></script>' . "\n";
}
echo implode(" ", $links);
}
So when js file located in $parentdir I'm calling like that
$this->make_js_link('ckeditor', 0, 'incl/editor');
If file located in parentdir/another_dir, then calling like that
$this->make_js_link('jquery', 'adapters', 'incl/editor');
The problem is, PHP escapes this part in both cases: even if I have folder variable with exact string value:
if (is_string($folder))
echo $folder . "/";
Where I did wrong?
You did echo instead of
$dir = $parentdir . "/";
if (is_string($folder))
$dir.= $folder . "/";

Categories