Good Day. I have a php script that move multiple file in my directory..
$filepath = 'uploads/';
if (isset($_FILES['file'])) {
$file_id = $_POST['file_id'];
$count = 0;
foreach($_FILES['file']['tmp_name'] as $k => $tmp_name){
$name = $_FILES['file']['name'][$k];
$size = $_FILES['file']['size'][$k];
if (strlen($name)) {
$extension = substr($name, strrpos($name, '.')+1);
if (in_array(strtolower($extension), $file_formats)) { // check it if it's a valid format or not
if ($size < (2048 * 1024)) { // check it if it's bigger than 2 mb or no
$filename = uniqid()."-00000-". $name;=
$tmp = $_FILES['file']['tmp_name'][$k];
if (move_uploaded_file($tmp_name, $filepath . $filename)) {
$id = $file_id;
$file_path_array = array();
$files_path = $filepath . $filename;
$file_extension = $extension;
foreach($file_name as $k_file_path => $v_file_path){
$file_path_array[] = $v_file_path;
}
foreach($file_extension as $k_file_extension){
$file_extension_array[] = $v_file_extension;
}
$file_path = json_encode($files_path);
$file_name = str_replace("\/", "/",$file_path);
var_dump($file_name);
$update = $mysqli->query("UPDATE detail SET file_path='$file_name' WHERE id='$id'");
} else {
echo "Could not move the file.";
}
} else {
echo "Your file is more than 2MB.";
}
} else {
echo "Invalid file format PLEASE CHECK YOU FILE EXTENSION.";
}
} else {
echo "Please select FILE";
}
}
exit();
}
this is my php script that move file to 'uploads/' directory and i want to save the path to my database. i try to dump the $file_name and this is my example path how to save that to my database.. ? any suggestions ?
NOTE: i already move the file to uploads/ directory and i only want to save the path to my database
string(46) "uploads/5638067602b48-00000-samplePDF.pdf"
string(46) "uploads/5638067602dee-00000-samplePDF1.pdf"
string(46) "uploads/5638067602f8d-00000-samplePDF2.pdf"
if you must store them in one field..
inside the loop
$file_name_for_db[]=$file_name;
outside the loop:
$update = $mysqli->query("UPDATE detail SET file_path='".json_encode($file_name_for_db)."' WHERE id='$id'");
there is serialize() instead of json_encode() if you prefer
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.
<?php
require_once("database.php");
if(#$_POST['upload']) {
$file_name = $_FILES['cvs']['name'];
$file_type = $_FILES['cvs']['type'];
$file_temp_loc = $_FILES['cvs']['tmp_name'];
$file_error_msg = $_FILES['cvs']['error'];
$file_size = $_FILES['cvs']['size'];
/* 1. file upload handling */
if(!$file_temp_loc) { // if not file selected
echo "Error: please browse for a file before clicking the upload button.";
exit();
}
if(!preg_match("/\.(csv)$/i", $file_name)) { // check file extension
echo 'Error: your file is not CSV.';
#unlink($file_temp_loc); // remove to the temp folder
exit();
}
if($file_size > 5242880) { // file check size
echo "Error: you file was larger than 5 Megabytes in size.";
exit();
}
if($file_error_msg == 1) { //
echo "Error: an error occured while processing the file, try agian.";
exit();
}
$move_file = move_uploaded_file($file_temp_loc, "\\Reformist003-pc/c/xampp/htdocs/FARMAPP/Farmer/{$file_name}"); // temp loc, file name
if($move_file != true) { // if not move to the temp location
echo 'Error: File not uploaded, try again.';
#unlink($file_temp_loc); // remove to the temp folder
exit();
}
$csvFile = '\\Reformist003-pc/c/xampp/htdocs/FARMAPP/Farmer/'.$file_name;
$csvFileLength = filesize($csvFile);
$csvSeparator = ",";
$handle = fopen($csvFile, 'r');
$count = '';
while($data = fgetcsv($handle, $csvFileLength, $csvSeparator)) { // while for each row
$count += count($data[0]); // count imported
mysql_query("INSERT INTO `csv_data` (`product_title`, `product_price`) VALUES ( '$data[0]', '$data[1]' )");
}
fclose($handle);
unlink($csvFile); // delete cvs after imported
header('Location: index.php?success=1&count='.$count);
exit();
}
?>
please check the spelling of file field's name .. it must be csv in html and you called it cvs
$file_name = $_FILES['csv']['name'];
$file_type = $_FILES['csv']['type'];
$file_temp_loc = $_FILES['csv']['tmp_name'];
$file_error_msg = $_FILES['csv']['error'];
$file_size = $_FILES['csv']['size'];
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 want to upload files sequentially. When I do so, the files I uploaded the last will get to the file system whereas my php code will not see the files I uploaded earlier. Anyone had a similar problem?
function inputImages()
{
print_r($_FILES);
$images_number = count($_FILES['images']['name']);
$uploadDir = 'tmp_name/';
$images = array();
for ($i=0; $i<$images_number; $i++) {
$fileName = $_FILES['images']['name'][$i];
$tmpName = $_FILES['images']['tmp_name'][$i];
$permanentname = sha1($tmpName.$fileName.rand()).substr($fileName,-4);
$filePath = $uploadDir . $permanentname;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
$ErrorMessage.= "Error uploading <strong>file</strong>";
} else {
array_push($images, $permanentname);
}
}
return $images;
}
i'd like to change the name of uploaded file to md5(file_name).ext, where ext is extension of uploaded file. Is there any function which can help me to do it?
$filename = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = md5($filename).'.'.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'], "/path/{$new}"))
{
// other code
}
Use this function to change the file name to md5 with the same extension
function convert_filename_to_md5($filename) {
$filename_parts = explode('.',$filename);
$count = count($filename_parts);
if($count> 1) {
$ext = $filename_parts[$count-1];
unset($filename_parts[$count-1]);
$filename_to_md5 = implode('.',$filename_parts);
$newName = md5($filename_to_md5). '.' . $ext ;
} else {
$newName = md5($filename);
}
return $newName;
}
<?php
$filename = $_FILES['file']['name'];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = rand(0000,9999);
$newfilename=$new.$filename.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'],$newfilename))
{
//advanced code
}
?>
Find below php code to get file extension and change file name
<?php
if(isset($_FILES['upload_Image']['name']) && $_FILES['upload_Image']['name']!=='') {
$ext = substr($_FILES['upload_Image']['name'], strpos($_FILES['upload_Image']['name'],'.'), strlen($_FILES['upload_Image']['name'])-1);
$imageName = time().$ext;
$normalDestination = "Photos/Orignal/" . $imageName;
move_uploaded_file($_FILES['upload_Image']['tmp_name'], $normalDestination);
}
?>
This one work
<?php
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
// random 4 digit to add to our file name
// some people use date and time in stead of random digit
$random_digit=rand(0000,9999);
//combine random digit to you file name to create new file name
//use dot (.) to combile these two variables
$new_file_name=$random_digit.$file_name;
//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "upload/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
?>