php rename uploaded file before upload and overwrite if already exists - php

Currently using this code for the upload (but happy to use any if suggested)..
<form style="margin-bottom:2px;" method="post" enctype="multipart/form-data" name="formUploadFile">
<label>Select CSV file to upload:</label>
<input type="file" name="files[]" multiple="multiple" /> <input type="submit" value="Upload CSV" name="btnSubmit"/>
</form>
<?php
if(isset($_POST["btnSubmit"]))
{
$errors = array();
$uploadedFiles = array();
$extension = array("csv");
$bytes = 1024;
$KB = 1024;
$totalBytes = $bytes * $KB;
$UploadFolder = "tmp_csv_store";
$counter = 0;
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name){
$temp = $_FILES["files"]["tmp_name"][$key];
$name = $_FILES["files"]["name"][$key];
if(empty($temp))
{
break;
}
$counter++;
$UploadOk = true;
if($_FILES["files"]["size"][$key] > $totalBytes)
{
$UploadOk = false;
array_push($errors, $name." file size is larger than the 1 MB.");
}
$ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array($ext, $extension) == false){
$UploadOk = false;
array_push($errors, $name." invalid file type.");
}
if(file_exists($UploadFolder."/".$name) == true){
$UploadOk = false;
array_push($errors, $name." file already exists.");
}
if($UploadOk == true){
move_uploaded_file($temp,$UploadFolder."/".$name);
array_push($uploadedFiles, $name);
}
}
if($counter>0){
if(count($errors)>0)
{
echo "<b>Errors:</b>";
foreach($errors as $error)
{
echo " ".$error.",";
}
echo "<br/>";
}
if(count($uploadedFiles)>0){
echo "<b>Uploaded:</b>";
echo "=";
foreach($uploadedFiles as $fileName)
{
echo " ".$fileName.",";
}
echo "<br/>";
echo "<big><big>".count($uploadedFiles)." file has been successfully uploaded.</big></big>";
}
}
else{
echo "ERROR: Please press the browse button and select a CSV file to upload.";
}
}
?>
And would like to modify it so that it renames the uploaded file from "any-file-name.csv" to "foobar.csv" before it uploads the file and it should also overwrite the file if it already exists.
As a bonus the code currently allows for multi-file upload but I really only need it for a single file each time so it could also possibly be shortened a bit if changed to only allow a single file.
Thanks in advance :-)

To add your custom name:
if($UploadOk == true){
$name = "foobar.csv";
move_uploaded_file($temp,$UploadFolder."/".$name);
array_push($uploadedFiles, $name);
}
For single file, remove multiple="multiple":
<input type="file" name="files[]" />

Related

php keep only the first 4 lines of a text file when uploading

I'm using the following code to upload a txt file to my server..
<form style="margin-bottom:2px;" method="post" enctype="multipart/form-data" name="formUploadFile">
<label>Select txt file to upload:</label>
<br>
<input type="file" name="files[]" /> <input type="submit" value="Upload" name="Submit"/>
<br>
</form>
<?php
if(isset($_POST["Submit"]))
{
$errors = array();
$uploadedFiles = array();
$extension = array("txt");
$bytes = 1024;
$KB = 1024;
$totalBytes = $bytes * $KB;
$UploadFolder = "tmp_txt_store";
$counter = 0;
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name){
$temp = $_FILES["files"]["tmp_name"][$key];
$name = $_FILES["files"]["name"][$key];
if(empty($temp))
{
break;
}
$counter++;
$UploadOk = true;
if($_FILES["files"]["size"][$key] > $totalBytes)
{
$UploadOk = false;
array_push($errors, $name." file size is larger than the 1 MB.");
}
$ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array($ext, $extension) == false){
$UploadOk = false;
array_push($errors, $name." invalid file type.");
}
if(file_exists($UploadFolder."/".$name) == true){
$UploadOk = false;
array_push($errors, $name." file already exists.");
}
if($UploadOk == true){
$name = "my.txt";
move_uploaded_file($temp,$UploadFolder."/".$name);
array_push($uploadedFiles, $name);
}
}
if($counter>0){
if(count($errors)>0)
{
echo "<b>Errors:</b>";
foreach($errors as $error)
{
echo " ".$error.",";
}
echo "<br/>";
}
if(count($uploadedFiles)>0){
echo "<b>Uploaded:</b>";
echo "=";
foreach($uploadedFiles as $fileName)
{
echo " ".$fileName.",";
}
echo "<br/>";
echo "DONE!";
}
}
else{
echo "ERROR: Please press the browse button and select a txt file to upload.";
}
}
?>
And I would like to keep only the first 4 lines of text, so trim off (delete) all lines of text (after the 4th line) before it gets uploaded.
So
line 1 text
line 2 text
line 3 text
line 4 text
line 5 text
line 6 text
line 7 text
<!--And so on-->
Becomes
line 1 text
line 2 text
line 3 text
line 4 text
How do I go about doing this?
I have tried a few suggstions looking at answers to other (similar) questions but being a so novice at php I'm really not getting anywhere with this.
You can just read the first four line, then overwrite the file.
$fp = fopen($file_path);
$num = 4;
while($num-- > 0 && $line = fgets($fp)){
$lines [] = $line;
}
fclose($file_path);
file_put_contents($file_path,join("",$lines));

PHP - multiple file upload, If not upload some field, it will get error

Hello I do the PHP Upload multiple files, but my form does not require to upload all field (require just at least one field upload) so user may not upload the second input field.
The problem is if user upload only 1 file, user will get the error "Invalid file" (final else statement).
But if user upload all 2 fields, it does not have error, I guess the error come from null upload field. So I use if not empty first, but it's not work. How should I do?
<form action="upload.php" method="post" enctype="multipart/form-data">
Image 1 :
<input type="file" name="images[]" />
<br>
image 2 :
<input type="file" name="images[]" /> <br>
<input type="submit" value="Upload" />
</form>
in upload.php page
if(!empty($_FILES))
{
$count = count($_FILES["images"]["name"]);
for($i=1; $i <= $count; $i++)
{
if ((($_FILES["images"]["type"][$i-1] == "image/gif")
|| ($_FILES["images"]["type"][$i-1] == "image/jpeg")
|| ($_FILES["images"]["type"][$i-1] == "image/png"))
&& ($_FILES["images"]["size"][$i-1] < 2000000)) //2 MB
{
if ($_FILES["images"]["error"][$i-1] > 0)
{
echo "File Error : " . $_FILES["images"]["error"][$i] . "<br />";
}
else
{
if (file_exists("path/to/".$_FILES["images"]["name"][$i-1] ))
{
echo "<b>".$_FILES["images"]["name"][$i-1] . " already exists. </b>";
}
else
{
$newname = date('Y-m-d')."_".$i.".jpg";
move_uploaded_file($_FILES["images"]["tmp_name"][$i-1] , "path/to/".$newname);
}
}
}
else
{
echo "Invalid file" ;
exit();
}
}
}
You can change your first line to:
if(isset($_FILES["images"]["name"][0])) {
With one or multiple files this can work
on line with:
echo "Invalid file" ;
exit();
this can be a problem, because if the first file have a problem you exit aplication and not process the second or others.
i suggest to you this code, too:
<?php
if (isset($_FILES["images"]["name"][0])) {
$path_upload = 'path/upload/';
$count = count($_FILES["images"]["name"]);
$allowed_types = array("image/gif", "image/jpeg", "image/png");
$nl = PHP_EOL.'<br>'; // Linux: \n<br> Window: \r\n<br>
for($i=0; $i < $count; $i++)
{
$file_type = $_FILES["images"]['type'][$i];
$file_name = $_FILES["images"]['name'][$i];
$file_size = $_FILES["images"]['size'][$i];
$file_error = $_FILES["images"]['error'][$i];
$file_tmp = $_FILES["images"]['tmp_name'][$i];
if (in_array($file_type, $allowed_types) && $file_size < 2000000) {
if ($file_error > 0) {
echo 'Upload file:'.$file_name.' error: '.$file_error.$nl;
} else {
$path_new_upload = $path_upload.$file_name;
// verify while filename exists
while (file_exists($path_new_upload)) {
$ext = explode('.', $file_name); // explode dots on filename
$ext = end($ext); // get last item of array
$newname = date('Y-m-d_').$i.'.'.$ext;
$path_new_upload = $path_upload.$newname;
}
move_uploaded_file($file_tmp, $path_new_upload);
}
} else {
echo 'Invalid file type to: '.$file_name.$nl;
// continue the code
}
}
}
Can be better, this verify filename to new creation.

need php code to post below 5 images into one field of db separated by br

Please help me
My html code is as follows:
here image_name is getting through echo from another upload query
My upload script code
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name)){
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$time = time();
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO uploads(image_name,poster_user,created,cat,status,ip) VALUES('$actual_image_name','$u_id','$time', 'Photos', '1', '$ip')");
echo "<img src='uploads/".$actual_image_name."' class='previewOfimgss'> ";
$allimages_name = "$actual_image_name";
echo "$allimages_name";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
It is working quite good and giving result like
and i want images names in on textbox like
$items=$_POST["post_items"];
$final = "";
foreach($items as $item){
$final .= $item."<br>";
}
echo $final
And you can then pass the $final variable to the column.
There is another way to do it.
$items= $_POST["post_items"];
$final = implode("<br>",$items);
It will work only if $items is array.
Ok I've done a working solution for you. This is a kind of prototype of your system. Hope it helps you in what you are building.
fileForm.php (Where you select file to upload.)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="uploadFile.php" method="post" enctype="multipart/form-data">
<input type="file" name="photoimg[]" multiple="yes">
<input type="submit" name="fileUploader">
</form>
</body>
</html>
uploadFile.php (Where you upload your files as in your question)
<?php
if ($_SERVER["REQUEST_METHOD"]=="POST") {
$path = "uploads/"; // Upload directory
// Return's files extension
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP"); // Valid formats to upload
$fileCount=count($_FILES["photoimg"]["name"]); // Number of files uploaded
$files=array(); // Initilize an empty array to save names
// Loop through all files and upload them
for ($i=0; $i < $fileCount; $i++) {
$name=$_FILES["photoimg"]["name"][$i];
$tmp=$_FILES["photoimg"]["tmp_name"][$i];
$size=$_FILES["photoimg"]["size"][$i];
// If name is not empty
if(!empty($name)){
$ext = getExtension($name); // Get file extension
// If file is valid to upload
if(in_array($ext,$valid_formats)){
If file is less than 1 MB.
if($size<(1024*1024)){
$actual_image_name = time().substr(str_replace(" ", "_", $name), 5); // Final name of image
// If file uploads successfully
if(move_uploaded_file($tmp, $path.$actual_image_name)){
$time=time();
$ip=$_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO uploads(image_name,poster_user,created,cat,status,ip) VALUES('$actual_image_name','$u_id','$time', 'Photos', '1', '$ip')"); // Insert into your table
echo "<img src='uploads/$actual_image_name' class='previewOfimgss'> "; // Show the image
$files[$i] = $actual_image_name; // Save file names
}else{
echo "Fail upload folder with read access.";
}
}else{
echo "Image file size max 1 MB";
}
}else{
echo "Invalid file format..";
}
}else{
echo "Please select image..!";
}
}
}
?>
<form action="toSaveFileName.php" method="post">
<?php
for ($i=0; $i < $fileCount; $i++) {
// Generate input fields
echo "<input type='text' name='post_items[]' value='{$files[$i]}'>";
}
?>
<input type="submit">
</form>
toSaveFileName.php (This is what you originally asked for.)
$items=$_POST["post_items"]; // from input fields
$todb=""; // to send to database
if(is_array($items)){
$todb=implode("<br>",$items);
}else{
$todb=$items;
}
echo $todb; // for output
//save to database
Now implementing it to your system is your job. And I hope you should be able to do it on your own.
Don't forget to mark this as answer and vote up.

hide input field if upload succeed

I would like to hide the input field if upload succeed. I tried to hide it by putting $sub =1; and if($sub==0) as below but it hides the input whenever submit is pressed not when the upload succeed. any ideas?
<?php
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'productpic/'; //with trailing slash
//Set max file size in bytes
$max_size = 2097152;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "We are sorry, the image must be less than 2MB";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "The file you trying to upload is not an Image, we only accept images";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "The image you trying to upload already exists, please upload only once";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "Please select a photo";
return $out;
}
}
?>
<?php
if (isset($_POST['submit'])) {
$sub=1;
$file = uploadFile('file', true, false);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
}
echo $message;
}
?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<?php
ini_set( "display_errors", 0);
if($sub==0)
{
?>
<input name="file" type="file" size="20" />
<input name="submit" type="submit" value="Upload" />
<?php
}
?>
</form>
Try this
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
$sub=1; // keep here sub=1
}
The $sub=1 is executing when the submit is pressed since it is given in if (isset($_POST['submit'])) this means if submit is set.It should be given when upload completes.

Multiple File upload with dynamic fields

Can you please advise/help me with this code? I want to upload multiple files to the server and save the information in database. But this code is uploading only one file, from the first input field.
I have dynamic "upload file" fields, like this:
<form action="uploader.php" method="POST" enctype="multipart/form-data">
<label>Upload</label>
<input type="file" name="file[]">
<label>Description</label>
<input type="text" id="filedesc" name="filedesc[]">
<a href="#" onClick="addUpload('dynamicInputUpload');" >
<img src="../../img/add.png" ></a>
<div id="dynamicInputUpload"></div>
<input type="submit" float= "right" name="add" id="add" value="UPLOAD" >
<input type="hidden" name="pid" id="pid" value="<?php echo $pid; ?>">
<input type="hidden" name="intnumber" id="intnumber" value="<?php echo $int; ?>">
</form>
Bellow is the Javascript that creates dynamic fields:
var counterUpload = 1;
var limit = 10;
function addUpload(divName){
if (counterUpload == limit) {
alert("You have reached the limit of adding " + counterUpload + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <label>File " + (counterUpload + 1) + "</label><input type=\"file\" name=\"file["+counterUpload+"]\" id=\"file["+counterUpload+"]\"> <label>Description " + (counterUpload + 1) + "</label><input type=\"text\" id=\"filedesc["+counterUpload+"]\" name=\"filedesc["+counterUpload+"]\" >"
document.getElementById(divName).appendChild(newdiv);
counterUpload++;
}
}
And the problem is bellow in the uploader.php. I suceed to uplaod only one (the first) file.
<?php
include '../../c/config.php';
include '../../c/opendb.php';
// Settings
$allowedExtensions = array('jpg','gif','bmp','png', 'docx', 'doc','pdf');
$maxSize = 2097152;
$storageDir = '../uploads/';
// Result arrays
$errors = $output = array();
if (!empty($_FILES['file'])){
// Validation loop
foreach($_FILES['file']['name'] as $i=> $value){
$fileName = $_FILES['file']['name'][$i];
$fileSize = $_FILES['file']['size'][$i];
$fileErr = $_FILES['file']['error'][$i];
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
// Validate extension
if (!in_array($fileExt, $allowedExtensions)) {
$errors[$fileName][] = "Format $fileExt in file $fileName is not accepted";
}
// Validate size
if ($fileSize > $maxSize) {
$errors[$fileName][] = "$fileName excedes the maximum file size of $maxSize bytes";
}
// Check errors
if ($fileErr) {
$errors[$fileName][] = "$fileName uploaded with error code $fileErr";
}
}
// Handle validation errors here
if (count($errors) > 0) {
die("Errors validating uploads: ".print_r($errors, TRUE));
}
// Create the storage directory if it doesn't exist
if (!is_dir($storageDir)) {
if (!mkdir($storageDir, 0755, TRUE)) {
die("Unable to create storage directory $storageDir");
}
}
// File move loop
foreach($_FILES['file']['name'] as $i=> $array_value){
// Get base info
$fileBase = basename($_FILES['file']['name'][$i]);
$fileName = pathinfo($fileBase, PATHINFO_FILENAME);
$fileExt = pathinfo($fileBase, PATHINFO_EXTENSION);
$fileTmp = $_FILES['file']['tmp_name'][$i];
// Construct destination path
$fileDst = $storageDir.'/'.basename($_FILES['file']['name'][$i]);
for ($j = 0; file_exists($fileDst); $j++) {
$fileDst = "$storageDir/$fileName-$j.$fileExt";
}
// Move the file
if (move_uploaded_file($fileTmp, $fileDst)) {
$output[$fileBase] = "Stored $fileBase OK";
$sql=mysql_query("INSERT INTO uploaded_files (pid, file_path,file_type)
Values ('$_POST[pid]','$fileDst','$fileExt')")
or die ("Unable to issue query sql: ".mysql_error());
} else {
$output[$fileBase] = "Failure while uploading $fileBase!";
$errors[$fileBase][] = "Failure: Can't move uploaded file $fileBase!";
}
}
// Handle file move errors here
if (count($errors) > 0) {
die("Errors moving uploaded files: ".print_r($errors, TRUE));
} }
This string has an error:
$sql=mysql_query("INSERT INTO uploaded_files (pid, file_path,file_type)
Values ('$_POST[pid]','$fileDst','$fileExt')")
or die ("Unable to issue query sql: ".mysql_error());
Try to comment this string, your script will save all files.
Maybe you did not connected to the database.

Categories