I have an multiple input sending files and I need guard this images with another name inside my folder called 'home';
So the pictures filing with the name home1.jpg, home2.jpg, etc
So, here is my code:
$file = $_FILES['Filedata'];
$filename_home = "";
$img_array = array($filename);
foreach($img_array as $key=>$value){
$filename_home.="home".$key.".jpg";
}
But this doesn't producing the result.
Any help, will be appreciate
Where does $filename come from? It looks like you want to use $file instead.
Related
I have created a form that submits the data to a filename on the server. The form submit is working fine, it generates the requested file called "we_input_.sts".
I am trying to use the following code to grab two variables from the form "bfstnme" and "gfstnme"and attach them to the filename eg "wed_import-Jane_Bill.sts
This is the amended code: However I am still unable to get it to work.
I am trying different ideas to get this to work correctly. I have tried moving the code around but I'm still obviously missing something. The last line before the $savestring== is "$fp=fopen("wed-import-.sts", "a+");
The last lines after the $savestring are : fwrite($fp,$savestring); fclose($fp);
<?php
$bfirstname = $_POST['bfstnme'];
$gfirstname = $_POST['gfstnme'];
$file = 'wed_import_.sts';
$current = file_get_contents($file);
$new_file = 'wed_input_'.$bfirstname.'&'.$gfirstname.'.sts';
file_put_contents($new_file, $current);
?>
Here is the way I have solved it using the valuable assistance of all concerned.
$names .= ("$bfstnme" . "$gfstnme");
$fp = fopen("wed_import_($names).sts", "a+");
The results of the above give me a filename called:
"wed_Import_[JaneBill].sts. I only need to work out how to put an amperstand (&) betwen the names.
Thank you to all.
If you want put the info inside the file you must change the + by a . like this:
$current .= ("gfirstname" . "bfirstname");
If you want change the name, you must do something like #Jay_P says
Why you don't name the file before writing to it?
<?php
$gfirstname = $_POST['gname'];
$bfirstname = $_POST['bname'];
$file = 'wed_input_Bride_Groom.sts';
// Opens the file to get existing content hopefully
$current = file_get_contents($file);
// Appends bride and groom first names to the file hopefully
$current .= ("gfirstname" . "bfirstname");
$new_file = 'wed_input_'.$gfirstname.'_'.$bfirstname.'.sts';
// Write the contents back to the file
file_put_contents($new_file, $current);
?>
Let's assume you have the names in a variable called $names. You can easily append the text with the FILE_APPEND flag like this:
file_put_contents('wed_input_Bride_Groom.sts', $names, FILE_APPEND);
so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.
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;
So right now I am trying to upload a .txt file and send it to mysql. That part works fine. But I have my code looking for a set file name, like text.txt. The txt file is being ftp'd into a directory, then a button in a php file is pressed and it looks for that file, reads it and sends it to the db. However, the file is going to be ftp'd with different names everday, like date. It will be uploaded like this: test20130802.txt
How do I get my code to look for that date variable? It won't always be today's date either.
Here is part of my current code:
$handle = #fopen("test.txt", "r");
$values='';
while (!feof($handle))
{
$buffer = fgets($handle, 4096);
//MYSQL QUERY......
}
Any help is greatly appreciated. Thank you.
It is fairly straightforward I think.
First you take the name of the file "test20130802.txt" into a variable. e.g.
$readTestFile = "test20130802.txt"; //Or however you are taking the file name as input
Hopefully, you are getting a standard file name. (By standard I mean that the first few letters are consistently the same always.)
In case of standard file name:
$dateYearChar = array();
$dateMonthChar = array();
$dateDateChar = array();
for($i=0;$i<4;$i++)
$dateYearChar[$i] = $readTestFile[$i+4];
for($i=0;$i<2;$i++)
$dateMonthChar[$i] = $readTestFile[$i+8];
for($i=0;$i<2;$i++)
$dateDateChar[$i] = $readTestFile[$i+10];
$dateYear = intval($dateYearChar);
$dateMonth = intval($dateMonthChar);
$dateDate = intval($dateDateChar);
Edit: And you can do the reverse thing if you want to look for a filename with the specified format.
e.g.
$fileName = "test" . $dateYear . $dateMonth . $dateDate . ".txt"
I have a project that needs to create files using the fwrite in php. What I want to do is to make it generic, I want to make each file unique and dont overwrite on the others.
I am creating a project that will record the text from a php form and save it as html, so I want to output to have generated-file1.html and generated-file2.html, etc.. Thank you.
This will give you a count of the number of html files in a given directory
$filecount = count(glob("/Path/to/your/files/*.html"));
and then your new filename will be something like:
$generated_file_name = "generated-file".($filecount+1).".html";
and then fwrite using $generated_file_name
Although I've had to do a similar thing recently and used uniq instead. Like this:
$generated_file_name = md5(uniqid(mt_rand(), true)).".html";
I would suggest using the time as the first part of the filename (as that should then result in files being listed in chronological/alphabetic order, and then borrow from #TomcatExodus to improve the chances of the filename being unique (incase of two submissions being simultaneous).
<?php
$data = $_POST;
$md5 = md5( $data );
$time = time();
$filename_prefix = 'generated_file';
$filename_extn = 'htm';
$filename = $filename_prefix.'-'.$time.'-'.$md5.'.'.$filename_extn;
if( file_exists( $filename ) ){
# EXTREMELY UNLIKELY, unless two forms with the same content and at the same time are submitted
$filename = $filename_prefix.'-'.$time.'-'.$md5.'-'.uniqid().'.'.$filename_extn;
# IMPROBABLE that this will clash now...
}
if( file_exists( $filename ) ){
# Handle the Error Condition
}else{
file_put_contents( $filename , 'Whatever the File Content Should Be...' );
}
This would produce filenames like:
generated_file-1300080525-46ea0d5b246d2841744c26f72a86fc29.htm
generated_file-1300092315-5d350416626ab6bd2868aa84fe10f70c.htm
generated_file-1300109456-77eae508ae79df1ba5e2b2ada645e2ee.htm
If you want to make absolutely sure that you will not overwrite an existing file you could append a uniqid() to the filename. If you want it to be sequential you'll have to read existing files from your filesystem and calculate the next increment which can result in an IO overhead.
I'd go with the uniqid() method :)
If your implementation should result in unique form results every time (therefore unique files) you could hash form data into a filename, giving you unique paths, as well as the opportunity to quickly sort out duplicates;
// capture all posted form data into an array
// validate and sanitize as necessary
$data = $_POST;
// hash data for filename
$fname = md5(serialize($data));
$fpath = 'path/to/dir/' . $fname . '.html';
if(!file_exists($fpath)){
//write data to $fpath
}
Do something like this:
$i = 0;
while (file_exists("file-".$i.".html")) {
$i++;
}
$file = fopen("file-".$i.".html");