I have a form, upon submission, it will create a new directory, all images submitted along with the form will be upload in the said directory.
this is the shortened code.
mkdir('uploads/'.$name, 0777, true); //create directory
$count = count($_FILES['images']['tmp_name']); //count all uploaded files
for ($i=0; $i<$count; $i++)
{
//formatting
$file = $_FILES['images']['name'][$i];
$filename = strtolower($file);
$random = rand(0, 999); //Random number to be added to name.
$newfile = $random.$filename; //new file name
//upload
if (move_uploaded_file($newfile, "uploads/".$name."/".$newfile))
{
echo "uploaded";
} else {
echo " failed";
}
}
if i echo the directory echo "upload to =" . $teamdir."/".$newfile;
it shows the correct path /uploads/john/567banner_0.jpg
but the image aren't being uploaded.
bool move_uploaded_file ( string $filename , string $destination )
Your first parameter has to be the source so you have to give it the temp name assigned
by php.
In your case : $_FILES['images']['tmp_name'][$i]
I feel you should add
$_SERVER['DOCUMENT_ROOT'].'/path/to/uploads/
in image destination path
Related
I am uploading file into folder using PHP but my issue is its at a time writing file into 2 different path. My code is below.
if(array_key_exists('pimage',$_FILES)){
$tempFile = $_FILES['pimage']['tmp_name'];
$fileName = $_FILES['pimage']['name'];
$fileName = str_replace(" ", "-", $_FILES['pimage']['name']);
$fig = rand(1, 999999);
$saveFile = $fig . '_' . $fileName;
$uploadOk = 1;
if (exif_imagetype($_FILES['pimage']['tmp_name']) == IMAGETYPE_GIF) {
$ext=pathinfo($saveFile, PATHINFO_FILENAME);
$saveFile=$ext.'.png';
$png = imagepng(imagecreatefromgif($_FILES['pimage']['tmp_name']), $saveFile);
}
if (exif_imagetype($_FILES['pimage']['tmp_name']) == IMAGETYPE_JPEG) {
$ext=pathinfo($saveFile, PATHINFO_FILENAME);
$saveFile=$ext.'.png';
$png = imagepng(imagecreatefromjpeg($_FILES['pimage']['tmp_name']), $saveFile);
}
if (strpos($fileName,'php') !== false) {
# code...
}else{
$targetPath = PT_USERS_IMAGES_UPLOAD;
$targetFile = $targetPath . $saveFile;
if (file_exists($targetFile)) {
$data=array("msg"=>'profile image already exists');
$uploadOk = 0;
}
if ($_FILES["pimage"]["size"] > 2000000 || $_FILES["pimage"]["size"] == 0) {
$uploadOk = 0;
$data=array("msg" => "profile image should not greater than 2 MB.");
}
//echo $uploadOk;exit;
if ($uploadOk==0) {
$flag=0;
$data[]=array("msg" => $data['msg']);
}else{
$moved =move_uploaded_file($tempFile, $targetFile);
if ($moved) {
$filename = $saveFile;
$data = array('ai_image' => $filename);
$this->db->where('accounts_id', $dataArr['user_id']);
$this->db->update('pt_operator_accounts', $data);
}else{
$flag=0;
$data[]=array("msg" => "Not uploaded because of error #".$_FILES["pimage"]["error"]);
}
// print_r($data);exit;
}
}
}
Here I need to write file into PT_USERS_IMAGES_UPLOAD path but before uploading into this path also the file is uploading into project's root path. Here I need to upload only in PT_USERS_IMAGES_UPLOAD path not in project's root path.
It is likely because of these lines:
imagepng(imagecreatefromgif($_FILES['pimage']['tmp_name']), $saveFile);
If you look at the documentation regarding this imagepng(), it will either output an image to the browser (with a proper header) or save the file to disk when you fill out the second parameter, in your case you have used the to parameter ($saveFile). So, once you save it there, you then save it again using the move_uploaded_file($tempFile, $targetFile); which is the one saving it to the proper location.
If you are trying to convert something to PNG, then just do the imagepng() line and remove the move_uploaded_file() line. Change $saveFile to T_USERS_IMAGES_UPLOAD and then you should only get one saved file. Either way, remove one of those methods for saving the file to disk.
I have some code running on my site which works well to upload single files from file input form elements - but I now need a multiple file input form element to accept more than 1 file and upload them all to the server and store the details of the filenames uploaded in a comma separated string... Any ideas on how to make this work with the code I am using below:
form field:
<input name="logoexamples[]" id="blogoexamples" type="file" class="textInput" value="notrelevant" multiple>
PHP code (that works to accept 1 file uploaded, but not more than 1....?):
<?php
// initialize output;
$output = true;
// valid extensions
$ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf', 'jpg', 'jpeg', 'png', 'eps', 'svg', 'gif', 'ai');
// create unique path for this form submission
//$uploadpath = 'assets/uploads/';
// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.
// UPLOAD TO FOLDER IN /ASSETS/UPLOADS/ WITH ID OF THE PARENT PROJECT FOLDER RESOURCE
// Get page ID
// $pageid = $modx->resource->get('id');
// $uploadpath = 'assets/uploads/'.$pageid.'/';
// Get parent page title
$parentObj = $modx->resource->getOne('Parent');
$parentpageid = $parentObj->get('pagetitle');
$uploadpath = 'assets/uploads/'.$parentpageid.'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );
// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive
// is the file name empty (no file uploaded)
if($filename != '') {
// is this the right type of file?
if(in_array($ext, $ext_array)) {
// clean up file name and make unique
$filename = mb_strtolower($filename); // to lowercase
$filename = str_replace(' ', '_', $filename); // spaces to underscores
$filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
// full path to new file
$myTarget = $target_path . $filename;
// JWD - save uploaded filenames as a session var to get it on the redirect hook
$_SESSION['briefing_submittedfiles_' . $sf] = 'http://www.example.com/assets/uploads/'.$parentpageid.'/'.$filename;
// create directory to move file into if it doesn't exist
mkdir($target_path, 0755, true);
// is the file moved to the proper folder successfully?
if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
// set a new placeholder with the new full path (if you need it in subsequent hooks)
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
// set the permissions on the file
if (!chmod($myTarget, 0644)) { /*some debug function*/ }
} else {
// File not uploaded
$errorMsg = 'There was a problem uploading the file.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
} else {
// File type not allowed
$errorMsg = 'Type of file not allowed.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
// if no file, don't error, but return blank
} else {
$hook->setValue($sf, '');
}
}
return $output;
I had something similar coded for my website, this code is super old so don't judge or use it directly. Just an example.
if(isset($_POST['upload'])){
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "../FOLDER NAME/" . $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
copy($newFilePath, $newFilePath1);
$filename = basename($_FILES['upload']['name'][$i]);
// add $filename to list or database here
$result = "The files were uploaded succesfully.";
}else{
$result = "There was an error adding the files, please try again!";
}
}
}
I'm creating an upload form that when uploading files will check to see if a file with the same name already exists in the directory. If a file with the same name is found, the script should increment the file by appending the file name with a number such as test1.txt test2.txt and so on until a match is not found. This is what I have come up with so far but wanted to see if there is a different approach I should take.
Also note, my filenames are already cleaned before they enter this part of the script so my filename and extension functions are simplified.
function filename($file){
return substr($file,0,strrpos($file,'.'));
}
function extension($file){
return strtolower(substr(strrchr($file,'.'),1));
}
$new_file = 'test.txt';
$dir = 'files';
$files = scandir($dir);
$exclude = array('.','..');
foreach($files as $file){
if(!in_array($file,$exclude)){
$file_array[] = $file;
}
}
$i = 1;
while(in_array($new_file,$file_array)){
$filename = filename($new_file);
$extension = extension($new_file);
if($i>1){
$num = strlen($filename);
$filename = substr($filename,0,-1);
$new_file = $filename.$i.'.'.$extension;
} else {
$new_file = $filename.$i.'.'.$extension;
}
echo $new_file.'<br>';
echo $i.'<br>';
$i++;
}
echo $new_file;
the following piece of code recognizes the image through getimagesize() but then when i try to move the file to an uploaded folder it moves the file there but says it's an array? im confused because im not setting any variables as an array?
<?php
//simple image check using getimagesize() instead of extensions
if($_FILES){
$empty_check = getimagesize($_FILES['file']['tmp_name']);
if(empty($empty_check)){
echo 'this is not an image';
}
else{
echo 'you have uploaded ' . explode('.',$_FILES['file']['name'])[0].'
and it is a ' . explode('.',$_FILES['file']['name'])[1].'.';
//an example of how i would extract the extension
$target = "C:\\xampp\\htdocs";
move_uploaded_file($_FILES['file']['tmp_name'], $target.'\\'.$_FILES['file']);
}
}
?>
$_FILES['file']
is an array, you're trying to use it as the target filename;
comment of deceze.
Echo the file you want to move/save, then you should see what he mentioned..
When using move_uploaded_file you get to pick the filename, so you can pick anything you want.
When you upload the file, its put into a temporary directory with a temporary name, move_uploaded_file() allows you to move that file and in that you need to set the name of the file as well.
Use this coding for multiple file uploading....
//For Multiple file uploading
if (isset($_FILES['photo']) != "") {
$errors = array();
foreach($_FILES['photo']['tmp_name'] as $key = > $tmp_name) {
$file_name = $_FILES['photo']['name'][$key];
$file_size = $_FILES['photo']['size'][$key];
$file_tmp = $_FILES['photo']['tmp_name'][$key];
$file_type = $_FILES['photo']['type'][$key];
//change the image extension as png
$fileExt = "png";
$photorename[$key] = strtolower($property_code.
'_'.$key.
'.'.$fileExt);
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
//Path of Uploading file
$target = "images_property";
if (empty($errors) == true) {
if (is_dir($target) == false) {
mkdir("$target", 0700); // Create directory if it does not exist
}
if (file_exists("$target/".$photorename[$key])) {
unlink("$target/".$photorename[$key]);
}
move_uploaded_file($file_tmp, "$target/".$photorename[$key]);
} else {
print_r($errors);
}
}
if (empty($errors)) {
echo "Success";
}
}
I have a problem here im trying to upload a file
first time it is moving the filename from temp it its respective directory,
but again i try ot upload the aa different file with the same name it should rename the
first time uploaded file
with date_somefilename.csv and give the filename to its original state
for example a file test.csv ,im uploading it for first time it will upload to
corresponding directory as
test.csv,when i upload a different csv file with same name test.csv
I need to get the
test.csv (latest uploaded file)
06222012130209_test.csv(First time uploaded file)
The code is below
$place_file = "$path/$upload_to/$file_name";
if (!file_exists('uploads/'.$upload_to.'/'.$file_name))
{
move_uploaded_file($tmp, $place_file);
}else{
move_uploaded_file($tmp, $place_file);
$arr1 = explode('.csv',$file_name);
$todays_date = date("mdYHis");
$new_filename = $todays_date.'_'.$arr1[0].'.csv';
echo $str_cmd = "mv " . 'uploads/'.$upload_to.'/'.$file_name . " uploads/$upload_to/$new_filename";
system($str_cmd, $retval);
}
See comments in code.
$place_file = "$path/$upload_to/$file_name";
if (!file_exists($place_file)) {
move_uploaded_file($tmp, $place_file);
} else {
// first rename
$pathinfo = pathinfo($place_file);
$todays_date = date("mdYHis");
$new_filename = $pathinfo['dirname'].DIRECTORY_SEPARATOR.$todays_date.'_'.$pathinfo['basename'];
rename($place_file, $new_filename)
// and then move, not vice versa
move_uploaded_file($tmp, $place_file);
}
DIRECTORY_SEPARATOR is php constant. Value is '/' or '\', depending of operation system.
pathinfo() is php function, that return information about path: dirname, basename, extension, filename.
What about...
$place_file = "$path/$upload_to/$file_name";
if (file_exists($place_file)) {
$place_file = date("mdYHis")."_".$file_name;
}
if (!move_uploaded_file($tmp, $place_file)) {
echo "Could not move file";
exit;
}
I would not add a date to the file if it already exists. Instead I would just add a number to the end of it. Keep it simple.
$counter = 0;
do {
// destination path path
$destination = $path.'/'.$upload_to.'/';
// get extension
$file_ext = end(explode('.', $file_name));
// add file_name without extension
if (strlen($file_ext))
$destination .= substr($file_name, 0, strlen($file_name)-strlen($file_ext)-1);
// add counter
if ($counter)
$destination .= '_'.$counter;
// add extension
if (strlen($file_ext))
$destination .= $file_ext;
$counter++;
while (file_exists($destination));
// move file
move_uploaded_file($tmp, $destination);
$target = "uploads/$upload_to/$file_name";
if (file_exists($target)) {
$pathinfo = pathinfo($target);
$newName = "$pathinfo[dirname]/" . date('mdYHis') . "_$pathinfo[filename].$pathinfo[extension]";
rename($target, $newName);
}
move_uploaded_file($tmp, $target);
Beware though: Security threats with uploads.
how about something like this?
<?php
$tmp = '/tmp/foo'; // whatever you got out of $_FILES
$desitnation = '/tmp/bar.xyz'; // wherever you want that file to be saved
if (file_exists($desitnation)) {
$file = basename($destination)
$dot = strrpos($file, '.');
// rename existing file to contain its creation time
// "/temp/bar.xyz" -> "/temp/bar.2012-12-12-12-12-12.xyz"
$_destination = dirname($destination) . '/'
. substr($file, 0, $dot + 1)
. date('Y-m-d-H-i-s', filectime($destination))
. substr($file, $dot);
rename($destination, $_destination);
}
move_uploaded_file($tmp, $destination);