In Propriete entity I have 5 field called image1 image2 image3 image4 image5
I wan't to add these fields in a for loop
I tried this but it doesn't work:
for($i=0;$i<count($this->request->data['files'])&&$i<5;$i++){
//... some code
$propriete->{'image'.$i+1} = $file['name'];
}
}
Can someone help me?
EDIT
This is the code of my loop:
for($i=0; $i<count($this->request->data['files']) && $i<5; $i++){
$file=$this->request->data['files'][$i];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . '/img/' . $file['name']);
debug($file['name']);
//prepare the filename for database entry
$propriete->{'image'.$i+1} = $file['name'];
}
}
Your code should work fine, you're just missing parenthesis which makes your concatenation go haywire
$propriete->{'image'.($i+1)}="test";
This can also be demonstrated by this simple test
$i=2;
echo 'image'.$i+1; // 1 :)
VS
echo 'image'.($i+1); //image3
Put the value of every method in a variable to store the value and then use it.For eg
$values = $this->request->data['files'];
You cannot for loop the data without putting them in a variable first.
If you cannot find the filename the problem should be that you are naming the object property in the wrong manner.You should enclose $i+1 with quotes.
Related
I have a function to upload multiple files. I use two foreach to upload the files. In the first foreach, I loop the uploaded file,
$j_upl = count($my_upload["name"]);
$isUploaded = 0;
$files = $_FILES;
for($i=0;$i<$j_upl;$i++){
$random_name = substr($my_upload["name"][$i],0,-4)."_".date("ymdhis").$i.substr($my_upload["name"][$i],-4);
$this->load->library('upload', $config);
$_FILES['upload_act']['name'] = $files['upload_act']['name'][$i];
$_FILES['upload_act']['type'] = $files['upload_act']['type'][$i];
$_FILES['upload_act']['tmp_name'] = $files['upload_act']['tmp_name'][$i];
$_FILES['upload_act']['error'] = $files['upload_act']['error'][$i];
$_FILES['upload_act']['size'] = $files['upload_act']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload('upload_act');
}
In the $random_name, I use .date("ymdhis") to be added to the file_name. So, the file will be renamed to the file name."_".datetime uploded.
In the second foreach, I use this to insert the $random_name into the database.
foreach($details as $rows){
$file_name = substr($rows['val_upl'],0,-4)."_".date("ymdhis").$ii.substr($rows['val_upl'],-4);
$dt_act['UPL_FILENAME'] = ($rows['val_upl'] == "") ? NULL : $file_name.$ii;
$this->MProject->ins_activity_m($dt_act);
$ii += 1;
}
I use the same method to get the $file_name. If I upload around 2-3 files, the $file_name is matching the $random_name. But, if there are more files to upload, it begins to not match the $random_name because the second in ('Ymdhis') is different.
What is the best method to get the $random_name match the $random_name so the inserted file_name is matching the uploaded file_name?
Note:
I may added something to the file_name, but I prefer not to remove anything (the datetime format should exist)
The easiest way to solve this is to create an associate array in the first for loop with the required information passed in as key-value pairs. You don't need to loop through this object as you can use keys that you already know the values of within your loop like an existing filename to access the values like below...
$file_uploads = array();
for($i=0;$i<$j_upl;$i++){
$random_name = substr($my_upload["name"][$i],0,-4)."_".date("ymdhis").$i.substr($my_upload["name"][$i],-4);
$file_uploads[$my_upload["name"][$i]] = array(
'new_name' => $random_name,
'some_other_value' => $some_other_var
);
$this->load->library('upload', $config);
$_FILES['upload_act']['name'] = $files['upload_act']['name'][$i];
$_FILES['upload_act']['type'] = $files['upload_act']['type'][$i];
$_FILES['upload_act']['tmp_name'] = $files['upload_act']['tmp_name'][$i];
$_FILES['upload_act']['error'] = $files['upload_act']['error'][$i];
$_FILES['upload_act']['size'] = $files['upload_act']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload('upload_act');
}
foreach($details as $rows){
$file_name = $file_uploads[substr($rows['val_upl']]['new_name'];
$dt_act['UPL_FILENAME'] = ($rows['val_upl'] == "") ? NULL : $file_name.$ii;
$this->MProject->ins_activity_m($dt_act);
$ii += 1;
}
please note i've not tested this and i'm coding blind here but that should be enough to get you there.
If you need to capture the exact file names from the first loop, why not build an array within the first loop that just stores the file names? Then you can reference the array by the value of $rows rather than attempt to rebuild the names. (It also depends on what's between these two loops.)
I need to upload two files with different ext example :
file_1.txt and file_image.png
when the user sent the two files using upload an form :
file_1.txt and file_image.png
before move_uploaded_file I need to rename the image name to be like the txt. name file :
file_1.txt
file_1.jpeg
I just want to rename the image filename, not the extension
Code is something like this :
switch($_REQUEST['action']) {
case "upload":
$Imagefile_temp = $_FILES['file']['tmp_name'];
$Textfile_temp = $_FILES['file']['tmp_name'];
$Imagefile_name = $_FILES['file']['name'];
$Textfile_name = $_FILES['file']['name'];
$ImageFileType = array('png' ,'jpg');
$TextFileType = array('txt');
$Image_extension = pathinfo($Imagefile_name, PATHINFO_EXTENSION); // holds the file extension of the file
$Text_extension = pathinfo($Textfile_name, PATHINFO_EXTENSION); //holds the file extension of the file
// //Declaring Path for uploaded images
$file_path = "uploads";
//checks for duplicate files
if((!file_exists($file_path."/".$Imagefile_name)) || (!file_exists($file_path."/".$Textfile_name))) {
$j = 0; //Variable for indexing uploaded image
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
if(in_array($Image_extension,$ImageFileType) ) {
$Image_extension = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($Image_extension); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $Image_extension[count($Image_extension) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
$Imagefilestatus = move_uploaded_file($Imagefile_temp,$file_path."/"."image_".$Imagefile_name) ;//if file moved to uploads folder
}
if(in_array($Text_extension,$TextFileType) ) {
$Text_extension = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($Text_extension); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $Text_extension[count($Text_extension) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
$Textfilestatus = move_uploaded_file($Textfile_temp,$file_path."/".$Textfile_name) ;//if file moved to uploads folder
}
}
}
}
$name = 'Whatevernameyouwant.'.pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
pathinfo with parameter PATHINFO_EXTENSION returns the file extension.
You can just explode the text file from the extension and use it as the image file name when moving it :
$text_file_name = $_FILES["text"]["name"]; // give you the text file name
$image_file_name = $_FILES["image"]["name"]; // give you the image file name
$file_expensions = strtolower(end(explode(".", $image_file_name))); // give you the image extension and so you can use it later for saving the file
$n = explode(".", $text_file_name, 1);
$name = $n[0]; // get text file name
$name = $name.".".$file_expensions; // this is new name of the image
move_uploaded_file($file_tmp, "path/$name")
I assume you are aware that the code you've presented here allows anyone with upload privileges to upload and execute PHP code.
(the reason I mention this is that there is scope for a lot of improvement elsewhere - and if the security vulnerability is exploitable then you should really think about start again from scratch with this).
Will your extension always be .jpg or .png ? (what about .jpeg ?)
I need to rename the image name to be like the txt. name file
I presume you mean that you want the filename on the retained image file to match that of the txt file - you can specify the destination name in move_uploaded_file(). Breaking down a process into steps is a good idea for managing complexity but file operations are expensive and here redundant.
So really you want to know how to get the a filename without an extension then add the file extension from a different file.
You already have the extension you want to apply in $Image_extension
While you could just do....
$destination_name=$destination_path
. str_replace('.txt', '.' . $image_extension, $Textfile_name);
However this will not work as expected if $imageFile_name contains more than one instance of '.txt'.
You could use PCREs to specify that you should only apply the change to the end of the string:
$destination_name=preg_replace("/txt$/i", $image_extension, $Textfile_name);
Or take the last 4 characters off $Textfile_name then append the image extension.
$destination_name=substr($Textfile_name, 0, -3) . $image_extension;
Or strrev the text file name, replace 'txt' with strrev($image_extension) with a limit of 1, then strrev the result to ensure only the end of the string is replaced.
If I spent more time thinking about this, there are probably other solutions too - but they will become increasingly esoteric.
In general, allowing users to pick their own names (or even part thereof) for content uploaded inside the document root is a bad idea.
I am a newbie at PHP and I'm learning.
I've made a basic script where you can upload an image to a director on the server. I want the image names to get a number at the end so that the name won't be duplicated.
This is my script to add 1 to the name (I'm really bad at "for loops"):
for(x=0; $imageName => 50000; x++){
$imageFolderName = $imageName.$x;
}
Please tell me if I'm doing this totally wrong.
Adding to Niet's answer, you can do a foreach loop on all the files in your folder and prepend a number to the file name like so:
<?
$directory = 'directory_name';
$files = array_diff(scandir($directory), array('.', '..'));
$count = 0;
foreach($files as $file)
{
$count++;
rename($file, $count.'-'.$file);
}
?>
Alternatively you could rename the file to the timestamp of when it was uploaded and prepend some random characters to the file with the rand() function:
<?
$uploaded_name = 'generic-image.jpeg';
$new_name = time().rand(0, 999).$uploaded_name;
?>
You'll need to handle and move the uploaded files before and after the rename, but you get the general gist of how this would work.
Here's a potential trick to avoid looping:
$existingfiles = count(glob("files/*"));
// this assumes you are saving in a directory called files!
$finalName = $imageName.$existingfiles;
Im stuck on a problem,
I have created a multiply uploader, it works fine until i want the file I upload to register the name inside a database,
The error message I get is
Warning: mysql_real_escape_string() expects parameter 1 to be string,
array given in C:\wamp\www\bookstyled\profile.php on line 16
My line 16 is the variable file_name
$file_name = mysql_real_escape_string($_FILES['file_name']['name']);
If I remove the mysql_real_escape_string, It actually save to the database but not as the file name, but its says " Array "
This is some of the code
if(isset($_FILES['file_name'])) {
foreach ($_FILES['file_name'] ['tmp_name'] as $key => $tmp_name){
$file_name = mysql_real_escape_string($_FILES['file_name']['name']);
$dt1=date('y-m-d H:m:s');
$ip=$_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `files` (`file_name`, `user_name`,`file_time`,`file_ip`) VALUES ('$file_name', '{$_SESSION['username']}','$dt1','$ip')") ;
move_uploaded_file($tmp_name, "core/files/{$_FILES['file_name']['name'][$key]}");
}
}
And If I didn't mention it
The files are being upload.
Thanks
You have enabled multiple uploads. So I'm guessing your html names for the fields are arrays. eg:
<input type="file" name="file_name[]" multiple="multiple">
Now $_FILES['file_name']['name'] doesn't hold one file but multiple files in an array.
Each file is individually accessed through
$_FILES['file_name']['name'][$i] //where $i is a 0,1,2.....
Since you are using
$file_name = mysql_real_escape_string($_FILES['file_name']['name'])
the function mysql_real_escape_string isn't being given a string as the parameter but the complete array which hold each and every file uploaded to 'file_name'.
The solutions is simple, you need to use
file_name = mysql_real_escape_string($_FILES['file_name']['name'][$key])
$key because I see that you are already using that in move_upload_file function
If you change this
$file_name = mysql_real_escape_string($_FILES['file_name']['name']);
to this
$file_name = mysql_real_escape_string($_FILES['file_name']['name'][$key]);
As you use this [$key] in this sentence move_uploaded_file($tmp_name, "core/files/{$_FILES['file_name']['name'][$key]}"); I think you should use on the line 16 too.
Looks like $_FILES['file_name']['name'] is an array as opposed to a string, so try $_FILES['file_name']['name']['key']
Untested, but could work.
if(isset($_FILES['file_name'])) {
foreach ($_FILES['file_name'] as $file){
$file_name = mysql_real_escape_string($file['tmp_name']);
$dt1=date('y-m-d H:m:s');
$ip=$_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `files` (`file_name`, `user_name`,`file_time`,`file_ip`) VALUES ('$file_name', '{$_SESSION['username']}','$dt1','$ip')") ;
move_uploaded_file($tmp_name, "core/files/{$file['name']}");
}
}
I want make a loop of my fold, get all the files and make a judge, print all the files name witch size are less than 10kb. But I get nothing from this code (no php error hint, just 0 result, and I am sure there has 10 files at lest < 10kb), where is the problem? Thanks.
$folder = dirname('__FILE__')."/../images/*";
foreach(glob($folder) as files){
$size = filesize(files);
if($size<10240){
echo files.'<br />';
}
}
I think there's a typo, because
dirname('__FILE__')
should be (without quotes)
dirname(__FILE__)
and also, your variable files doesn't have a dollar sign
$size = filesize($files);
and also here echo $files
That's it, it should fix your problem
__FILE__ is a magic constant, therefore you cannot wrap it in quotes:
$folder = dirname(__FILE__)."/../images/*";
You missed a $ in files:
$size = filesize($files);
// and
echo $files.'<br />';
Are you sure
$folder = dirname('__FILE__')."/../images/*";
is valid? do you mean
dirname(__FILE__)