Multiple input file in one form - php

I have form :
<form method="post" enctype="multipart/form-data" action="edit_kategori.php">
<input type="file" name="icon-main" id="icon-main">
<input type="file" name="icon-hover" id="icon-hover">
<form>
I want to upload two images from two input files, but only the last one file I have choosen that uploaded. and here is my php:
$dirMain = $_FILES['icon-main']['tmp_name'];
$dirHover = $_FILES['icon-hover']['tmp_name'];
//main icon
$tempMain = explode(".", $_FILES['icon-main']['name']);
$newMain = round(microtime(true)) . '.' . end($tempMain);
$iconMain = $folder . basename($newMain);
//hover icon
$tempHover = explode(".", $_FILES['icon-hover']['name']);
$newHover = round(microtime(true)) . '.' . end($tempHover);
$iconHover = $folder . basename($newHover);
if (!empty($dirMain)&&!empty($dirHover)) {
$dir[] = $dirMain;
$dir[] = $dirHover;
$icon[] = $iconMain;
$icon[] = $iconHover;
for ($i=0; $i <= 1; $i++) {
move_uploaded_file($dir[$i] , $icon[$i]);
}
}
Is that because "tmp_name" can only store one file ? Thanks for helping :)

Just small mistake, loop through <= 1
for ($i=0; $i <= 1; $i++) {
move_uploaded_file($dir[$i] , $icon[$i]);
}
I guess storing $_FILES['yourvar']['tmp_name'] is causing issue. I have tried this both ways and it might useful to you the difference:
Method 1: (working)
move_uploaded_file($_FILES['icon-main']['tmp_name'], $_FILES['icon-main']['name']);
move_uploaded_file($_FILES['icon-hover']['tmp_name'], $_FILES['icon-hover']['name']);
Method 2: (not working)
$d = $_FILES['icon-main']['tmp_name'];
$k = $_FILES['icon-hover']['tmp_name'];
move_uploaded_file($d, $_FILES['icon-main']['name']);
move_uploaded_file($k, $_FILES['icon-hover']['name']);

I just find the way, I move file manualy using if, not looping...
$target = "../category/";
$dir = $target . basename( $_FILES['icon-main']['name']);
if(move_uploaded_file($_FILES['icon-main']['tmp_name'], $dir)) {
echo "<br>";
echo $dir;
} else {
echo "Fail";
};
$dir = $target . basename( $_FILES['icon-hover']['name']);
if(move_uploaded_file($_FILES['icon-hover']['tmp_name'], $dir)) {
echo "<br>";
echo $dir;
} else {
echo "Fail";
};

Related

Multiple image upload, change name if image already exists

I have a code that changes image names like in the windows systems. If there is a image like cup.jpg, the code changes the name into cup0.jpg.
The problem however, is when I'm uploading many images from array and only some of the images already exist and need to get the name changed.
What changes need to be made for this to work with multiple files?
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
$target_file = $target_dir . basename($_FILES["upload"]["name"][$i]);
$images[] = basename($_FILES['upload']['name'][$i]);
}
if (file_exists($target_file)) {
$i = 0;
echo " Image exists, changing name.";
while (file_exists($target_file)) {
$extension = pathinfo($target_file, PATHINFO_EXTENSION);
$filename = pathinfo($target_file, PATHINFO_FILENAME);
$new_filename = $filename . $i . $iterator . '.' . $extension;
$target_file = $target_dir . $new_filename;
$i++;
$images[] = $new_filename;
}
}
I tried adding a loop but the code doesn't work if the array consists of new images and already existing images so only some of the images would need their names changed.
Here are you go:
$images = array();
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
getUniqueName(basename($_FILES["upload"]["name"][$i]),$images);
}
function getUniqueName ($name, &$images) {
$i = 0;
$extension = pathinfo($name, PATHINFO_EXTENSION);
$filename = pathinfo($name, PATHINFO_FILENAME);
while (in_array($name, $images)) {
$name = $filename . $i . '.' . $extension;
$i++;
}
/* Need to define $target_dir here */
$i=0;
while (file_exists($target_dir.$name)) {
$name = $filename . $i . '.' . $extension;
$i++;
}
$images[]= $target_dir.$name;
}

How to explode a file extension from a filename that is in an array?

function addFlyer($db) {
if (isset($_FILES['file_array'])) {
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for ($i = 0; $i < count($tmp_name_array); $i++) {
if (file_exists($name_array[$i])) {
echo "Sorry file already exists. ";
$uploadOk = 0;
}
else {
if (move_uploaded_file($tmp_name_array[$i], "images/" . $name_array[$i])) {
echo $name_array[$i] . " upload is complete<br>";
} else {
echo "move_uploaded_file function failed for " . $name_array[$i] . "<br>";
}
}
}
}
At the moment I got this code for upload multiple files to a folder and insert it into the database (I excluded the code for inserting.)
But if I want to use the file_exists function correctly I need to seperate the extension and the name from the file. But I have no idea how I can explode an array.
Is there someone that can help me with this?
You don't need to explode or something else. You could get image extension by path_info() PHP Function. PLease have a look on below.
$path = $_FILES['file_array']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
If you want to explode a file name. You can use below trick
$file = $_FILES['file_array']['name'];
$image_info = explode(".", $file);
$image_type = end($image_info)
foreach ($name_array as $value) {
if (file_exists($value)) {
echo "Sorry file already exists. ";
$uploadOk = 0;
} else {
if (move_uploaded_file($value, "images/" . $value)) {
echo $value . " upload is complete<br>";
} else {
echo "move_uploaded_file function failed for " . $value . "<br>";
}
}
}
This may work. Use foreach() loop instead of for() loop.

echo 15 random lines of html files

I have to do a php assignment for college.
How would I echo 15 random lines of a html file if there is a movie script text and a image with the same in the same folder?
What I have tried so far:
$folder = 'Filmnoir/';
$hitchcock ='Hitchcock/';
$shakespear ='Shakespear/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$file2 = glob ($hitchcock.$filetype);
$file3 = glob ($shakespear.$filetype);
$count = count($files);
$count1 = count($file2);
$count2 = count($file3);
$scripttype ='*.html';
$Scripts = glob($ScriptFilmNoir.$scripttype);
$Scripts=file_get_contents("DoubleIndemnity.html");
if($_POST['radio1']=="0"){
if(($i %1)==0){
for ($i = 0; $i < $count; $i++)
{
echo '<div class="image2">';
echo '<img src="'.$files[$i].'" />';
echo '</div>';
if (condition) {
include 'DoubleIndemnity.html'; }
echo '</td></tr>';
}
echo '<div class="Passwordtext">';
echo 'Type in password to view full Script';
echo '</div>';
echo "<label><div class=\"password\"><input type='password' name='code' value='code'/></div></label>";
echo "<form method='POST' action='ca1_result.php'>";
echo "<div class=\"SubmitIt\"><input type='submit' name='submitScript' value='Submit Password'/></div>";
echo '</form>';
}
}
if($_POST['radio1']=="1"){
echo '<div class="Sorrytext">';
echo 'We apologize. No script available for this movie.';
echo '</div>';
}
if($_POST['radio1']=="2"){
echo '<div class="Sorrytext">';
echo 'We apologize. No script available for this movie.';
echo '</div>';
}
I want to achieve that when there is an image (e.g DoubleIndemnity.png) and movie script (e.g DoubleIndemnity.html) in the same folder that I get 15 random lines of the movie script text plus the image. Could I use the glob function and when yes how would I achieve that?
Can I ask another thing? When I submit the password how to I get then the full movie script?
I tried:
foreach($files as $file2) {
if($_POST['submitPassword']){
if($file2 === '.' OR $file2 === '..' OR $file2 === 'thumbs.db' OR !is_dir($folder.'/'.$file2)) {continue;}
if(file_exists($folder.'/'.$file2.'/doubleindemnity.gif') AND file_exists($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm')) {
echo '<div class="Container">';
echo "<div class='image2'><img src='$folder/$file/doubleindemnity.gif'>";
$lines4 = file($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm');
$count = count($lines4);
for($a = 0;$a < $count;$a++) {
echo substr($lines4[$a],strlen($folder),strpos($lines4[$a], '.')-strlen($folder));
}
echo "</div>";
}
echo "</div>";
}
}
?>
With that code I just get a couple of lines from the html file. I don't want that. I want the full text. And how can I use the string replace function to get rid of the code and just receive the text from the paragraphs?
Cheers:)
This piece of code will loop trough folders in a pre-defined folder (eg: /movies). It will look if whatever is inside is a folder, and if that folder has 2 files: image.png and lines.html. If it has those two files, it'll first place the image, then it'll read the HTML file, and writing down 15 random lines from that file.
<?php
$folder = "movies";
$files = scandir($folder);
foreach($files as $file) {
if($file === '.' OR $file === '..' OR $file === 'thumbs.db' OR !is_dir($folder.'/'.$file)) {continue;}
if(file_exists($folder.'/'.$file.'/image.png') AND file_exists($folder.'/'.$file.'/lines.html')) {
echo "<div class='image2'><img src='$folder/$file/image.png'>";
$lines = file($folder.'/'.$file.'/lines.html');
for($x = 1;$x<=15;$x++) {
echo $lines[rand(0, count($lines)-1)]."<br>";
}
echo "</div>";
}
}
Loops through files in $directory and then outputs 15 random lines into a html variable and if the image exists it adds it to the image html variable. If they are both added it returns the result. (untested but should work)
<?php
//I dont know where you have got some of these variables from
$directory = "Filmnoir";
$ScriptFilmNoir = "DoubleIndemnity";
$scripttype ='html';
$supportedImages = Array("png", "jpg", "jpeg");
$html = "";
$imagehtml = "";
$allFiles = scandir($folder);
$imageFound = 0;
$htmlFound = 0;
foreach($files as $file) {
if($file === '.' || $file === '..' || $file === 'thumbs.db' || is_dir($file)) {
continue;
}
$nameWithoutExtension = substr($file, 0 , (strrpos($file, ".")));
$fileExtension = $id = substr($file, strrpos($file, '.') + 1);
if($nameWithoutExtension == $ScriptFilmNoir){
if($fileExtension == $scripttype){
$htmlFound = 1;
$lines = file($directory . "/" . $ScriptFilmNoir . "." . $scripttype);//file in to an array
$range = range(1, count($lines));
$range = array_flip($range);
$range = array_rand($range, 15);
foreach($range as $line){
$html .= $lines[$value] . PHP_EOL;
}
}elseif(in_array ( $fileExtension , $supportedImages)){
$imageFound = 1;
$imagehtml = "<img src='{$directory}/{$ScriptFilmNoir}.{$fileExtension}' /><br />";
}
}
}
if($imageFound == 1 && $htmlFound == 1){
echo $imagehtml . $html;
}
I think what owen is looking for is a random extract of 15 lines rather than 15 random lines.
Using #ThijmenDF's example, just change
for($x = 1;$x<=15;$x++) {
echo $lines[rand(0, count($lines)-1)]."<br>";
}
to
$random = rand(0, count($lines)-1);
for($x = 1;$x<=15;$x++) {
echo $lines[$random + $x]."<br/>";
}

PHP Rename File name if Exists Append Number to End

I'm trying to rename the file name of an image when it's uploaded if it exists, say if my file name is test.jpg and it already exists I want to rename it as test1.jpg and then test2.jpg and so on. With the code I've written its changing my file name like so test1.jpg and then test12.jpg any advice on fixing this would be great thank!
PHP
$name = $_FILES['picture']['name'];
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$actual_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Here's a minor modification that I think should do what you want:
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$original_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Inspired from #Jason answer, i created a function which i deemed shorter and more readable filename format.
function newName($path, $filename) {
$res = "$path/$filename";
if (!file_exists($res)) return $res;
$fnameNoExt = pathinfo($filename,PATHINFO_FILENAME);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Example:
$name = "foo.bar";
$path = 'C:/Users/hp/Desktop/ikreports';
for ($i=1; $i<=10; $i++) {
$newName = newName($path, $name);
file_put_contents($newName, 'asdf');
}
New version (2022):
function newName2($fullpath) {
$path = dirname($fullpath);
if (!file_exists($fullpath)) return $fullpath;
$fnameNoExt = pathinfo($fullpath,PATHINFO_FILENAME);
$ext = pathinfo($fullpath, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Usage:
for ($i=1; $i<=10; $i++) {
$newName = newName2($fullpath);
file_put_contents($newName, 'asdf');
}
There are several ways for renaming image in PHP before uploading to the server.
appending timestamp, unique id, image dimensions plus random number etc.You can see them all here
First, Check if the image filename exists in the hosted image folder otherwise upload it. The while loop checks if the image file name exists and appends a unique id as shown below ...
function rename_appending_unique_id($source, $tempfile){
$target_path ='uploads-unique-id/'.$source;
while(file_exists($target_path)){
$fileName = uniqid().'-'.$source;
$target_path = ('uploads-unique-id/'.$fileName);
}
move_uploaded_file($tempfile, $target_path);
}
if(isset($_FILES['upload']['name'])){
$sourcefile= $_FILES['upload']['name'];
tempfile= $_FILES['upload']['tmp_name'];
rename_appending_unique_id($sourcefile, $tempfile);
}
Check more image renaming tactics
I checked SO and found a nice C# answer here, so I ported it for PHP:
['extension' => $extension] = pathinfo($filePath);
$count = 0;
while (file_exists($filePath) === true) {
if ($count === 0) {
$filePath = str_replace($extension, '[' . ++$count . ']' . ".$extension", $filePath);
} else {
$filePath = str_replace("[$count].$extension", '[' . ++$count . ']' . ".$extension", $filePath);
}
}

Php uploaded file unique name issue

Well, I've a html Upload form which process by .php file (uploader.php). It's a multiple file uploaded code.
So when it's upload, all files are go to upload directory with their individual file name. Like: abc.jpg, abc2.jpg etc.
But If someone upload a file with same name then it's ovrwrite the existing file. So that I need a unique name for the uploaded file. Is there any way to rename the file with unique random name. Like: 12545454.jpge, 234324324.jpge, 323453253.jpg etc..
Php Code:
<?php
if (isset($_POST['Submit'])) {
$number_of_file_fields = 0;
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/uploaded/'; //set upload directory
/**
* we get a $_FILES['images'] array ,
* we procee this array while iterating with simple for loop
* you can check this array by print_r($_FILES['images']);
*/
for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
$number_of_file_fields++;
if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['images']['name'][$i];
if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory .
$_FILES['images']['name'][$i])) {
$number_of_moved_files++;
}
}
}
echo "Number of File fields created $number_of_file_fields.<br/> ";
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode(',', $uploaded_files);
}
?>
Use uniqid() . It is made for this.
You can concat time(); and session_id() or uniqid() as suggested by wormhit is also very good idea against name of each file.
Use The below code:
<?php
$target_path = "images/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
//$upload_directory = ''.uniqid().'_'.dirname(__file__) . '/uploaded/'; //set upload directory
$uploaded_file="".$upload_directory ."/".uniqid()."_".$_FILES['images']['name'][$i]."";
if (move_uploaded_file($_FILES['images']['tmp_name'][$i],$uploaded_file)) {
$number_of_moved_files++;
}
?>
<?php
if (isset($_POST['Submit'])) {
$number_of_file_fields = 0;
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/uploaded/'; //set upload directory
/**
* we get a $_FILES['images'] array ,
* we procee this array while iterating with simple for loop
* you can check this array by print_r($_FILES['images']);
*/
for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
$number_of_file_fields++;
if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not
$uploaded_file="".$upload_directory ."".uniqid()."_".$_FILES['images']['name'][$i]."";
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['images']['name'][$i];
if (move_uploaded_file($_FILES['images']['tmp_name'][$i],$uploaded_file)) {
$number_of_moved_files++;
}
}
}
echo "Number of File fields created $number_of_file_fields.<br/> ";
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode(',', $uploaded_files);
}
?>
You can use this
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$newfilename = substr( sha1(uniqid (rand())), 0, 10). '.'.$ext;

Categories