Upload Multiple Files with FuelPHP - php

I currently have a script that allows me to upload 1 file to my server. It works great.
Here is a portion of the code I am using to do this:
// Custom configuration for this upload
$config = array(
'path' => DOCROOT.DS.'foldername/tomove/your/images',
'randomize' => true,
'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png'),
);
Upload::process($config);
// if a valid file is passed than the function will save, or if its not empty
if (Upload::is_valid())
{
// save them according to the config
Upload::save();
//if you want to save to tha database lets grab the file name
$value = Upload::get_files();
$article->filename = $value[0]['saved_as'];
}
I was now wondering, how do I loop through multiple files and upload these to my server?
I'm guessing using a foreach loop but I'm a little out of my depth with this I'm afraid.
Ultimately, I plan to store these filenames in a separate table on my database.
Many thanks for any help with this.

You already have the result in your code.
You already store it
$value = Upload::get_files();
so
$value = Upload::get_files();
foreach($value as $files) {
print_r($files);
}
And you will get everything what you need

Related

php rename files when downloading

Having trouble and keep getting error with my efforts , currently have an array in this format ....
$espn_ar["pid_6254"] = "2977742";
$espn_ar["pid_8269"] = "9614";
I'm using it to create url paths to download some images and name them
foreach ($espn_ar as $value){
$imageUrl = "https://a.espncdn.com/combiner/i?img=/i/headshots/nfl/players/full/$value.png&h=107&w=80&scale=crop";
$imageName = "images/mfl_.$value.png";
$imageFile = file_get_contents($imageUrl);
file_put_contents($imageName, $imageFile);
}
using the array example above the files are being named
mfl_2977742.png
mfl_9614.png
But i want the files to be named for the value that follows the "pid_" in each array item , so the file names i want are
mfl_6254.png
mfl_8269.png
Using my example , can anyone show me how to change the value when naming each image to the numbers following "pid_"
Include the keys in your foreach loop and extract the number for your filename
foreach ($espn_ar as $key => $value) {
$imageName = sprintf('images/mfl_%s.png', str_replace('pid_', '', $key));
// etc
}
Demo ~ https://3v4l.org/FgMi2

Upload multiple files at the same time without a duplicate in Laravel

I use this code to upload multiple files together in Laravel. However, all name files get duplicated. Please guide me.
if (is_array($files) || is_object($files)) {
foreach ($files as $file) {
$name = time().'.'.$file->getClientOriginalExtension();
$file->move(public_path('uploadmusic'), $name);
PostPhoto::create([
'post_id' => $post->id,
'filename' => $name
]);
}
}
1568314601.png
1568314601.png
1568314601.png
The precision of time() is only a second - not enough time to make time() report a different value when assigning $name in your loop for each file.
Append something else, like a call to \Illuminate\Support\Str::random() to get each name to be unique.
Depending on requirements, you might consider omitting the timestamp from the filename altogether and use something like md_file() instead.
$name = implode('.', [
md5_file($file->getPathname()),
$file->getClientOriginalExtension()
]);
This can also help keep duplicate files off of your storage device.

Rename uploaded image in numeric sequence (i + 1)

I have a json post that uploads photos. It works just fine. I want to change the name of the uploaded file as it is uploaded. I know how to do that. I want to add a number to the end of the file name before the image type extension. I know how to do that. I want the number to increment by one for each new file when I upload multiple images at once. I cant do that :-( Here is what Im working with:
if (!file_exists($vendimagepath) ) {
mkdir($vendimagepath,0777,TRUE);
}
$valid_extensions = array('gif', 'png', 'jpeg', 'jpg');
$uploader = new FileUpload('uploadfile');
// Handle the upload
$result = $uploader->handleUpload($vendimagepath);
if (!$result) {
exit(json_encode(array('success' => false, 'msg' => $uploader->getErrorMsg())));
} else {
echo json_encode(array('success' => true));
$_SESSION['success']=true;
$path = $uploader->getFileName();
$vendimagepath= $vendimagepath.$path;
$result = $db -> query("INSERT into vendimages (vendregid, vendimagepath) VALUES ('$vendredig', '$path')");
$result = $db -> update("UPDATE registervendors SET images='1' WHERE regid = '$vendredig' AND username='$vendusername' ");
}
I inserted a variable under the if statement at the top $x=1; and then under the $uploader=new fileupload I added a while loop with $x++; and put that closing brace at the end of the script. It didnt work. It uploaded files but they all end up with the same number (1) . I know why. The script is called for each new file uploaded so $x=1 restarts each time and therefore $x++ is 1 each time.
Since you want to count across page loads, you should use your $_SESSION. Before the uploads start set:
$_SESSION['upload_index'] = 1;
Then do $_SESSION['upload_index']++ each time you get a new uploaded file.

update existing move_uploaded_file code to handle an array instead of a single image upload

I have extended functionality of banner manager to allow for it to be multi language. This gives the user the opportunity to have language specific title, html banner, or image banner.
All the data is correctly being saved to the database now, but I can only ever get the first image of the three to be uploaded to the specified directory.
The original two code lines that uploaded the images are
if (move_uploaded_file($this->file['tmp_name'], $this->destination . $this->filename)) {
chmod($this->destination . $this->filename, $this->permissions);
I thought that changing it to the following word work, but it still only sends a single image.
$languages = zen_get_languages();
for ($i=0, $n = sizeof($languages); $i<$n; $i++) {
$language_id = $languages[$i]['id'];
if (move_uploaded_file($this->file['tmp_name'][$language_id] , $this->destination . $this->filename[$language_id])) {
chmod($this->destination . $this->filename[$language_id], $this->permissions);
}
I can see that the correct data is available for the uploads from the following print_r commands
print_r($this->file['tmp_name']);
results in
Array ( [2] => /Applications/MAMP/tmp/php/phpVr9JSd [1] => /Applications/MAMP/tmp/php/phpGpYRG9 [4] => /Applications/MAMP/tmp/php/phpfbOoQ4 )
and
print_r($this->destination);
results in
/Applications/MAMP/htdocs/confetti/images/banners/
and
print_r($this->filename);
results in
Array ( [2] => stislide1.jpg [1] => stislide2.jpg [4] => stislide3.jpg )
You may be wondering why I made the assumption that putting [$language_id] into the move_uploaded_file command would work. That thought was based on the fact that the code I used to upload the correct path/name information to the database was
for ($i=0, $n = sizeof($languages); $i<$n; $i++) {
$language_id = $languages[$i]['id'];
$db_image_location = (zen_not_null($banners_image_local_array[$language_id])) ? $banners_image_local_array[$language_id] : $banners_image_target . $banners_image->filename[$language_id];
Obviously what works as part of the mysqli upload doesn't work in the class file where this upload function is added.
Any pointers on where I've gone wrong here would be appreciated.
The answer was to rewrite the code so that the array contents were handled by a foreach
foreach($this->file['tmp_name'] as $key => $tmp_name){
$file_name = $this->filename[$key];
$file_tmp =$this->file['tmp_name'][$key];
move_uploaded_file($file_tmp, $this->destination. $file_name);
chmod($this->destination . $file_name, $this->permissions);
}
This is now uploading however many images are in the array

How to write a ini file in PHP codeigniter?

Hi I want to write a ini file into php.
first i upload a ini file to my server then i edit it,
i want to make some changes in parameters then want save that file back to uploads.
I used put_file_contents and fwrite but didn't get required result.
this is my code:
$data = array('upload_data' => $this->upload->data());
foreach ($data as $info)
{
$filepath = $info['file_path'];
$filename= $info['file_name'];
}
$this->data['parameters'] = parse_ini_file($filepath.$filename);
$insert = array(
'OTAID' => $this->input->post('OTAID'),
'SipUserName' => $this->input->post('SipUserName') ,
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'ServerMode' => $this->input->post('ServerMode')
);
$this->load->helper('file');
$file =fopen($filepath.$filename,'w');
fwrite($file,implode('', $insert));
$this->data['subview'] = 'customer/upload/upload_success';
$this->load->view('customer/_layout_main', $this->data);
As I told you in the last question you will need to use a helper function to turn the array into the right format for an ini-file. You can find such a helper-function here.
Also you are loading the file-helper from codeigniter but using the php built-in methods. Please have a look to the docs here.
Something akin the following might work:
//Replace the fwrite($file,implode('', $insert)); with
$iniContent = "";
foreach ($insert as $key => $value) {
$initContent .= $key."=".$value.PHP_EOL;
}
fwrite($file,$iniContent);
Note: This is probably the simplest thing one can do. I doesn't deal with sections or comments or escape characters or basically any sort of error checking. If you expect this sort of thing to be done a lot in your code I suggest you look into existing INI reading/writing libraries.
Update
Try http://pear.php.net/package/Config_Lite or http://pear.php.net/package/Config as suggested at create ini file, write values in PHP (which also has a lot more information to look at for this particular issue).

Categories