I added multiple file upload on my website, but I noticed, that uploaded files eat much RAM on the server and it does not decrease for 1-2 days. I think the reason is incorrect PHP code... I tried to unset all variables but it didn't help. That's my code:
<?php
if(isset($_POST['upload'])){
if(count($_FILES['files']['name']) > 0){
for($i=0; $i<count($_FILES['files']['name']); $i++) {
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
if($tmpFilePath != ""){
$max_filesize = 10000288;
if(filesize($_FILES['files']['tmp_name'][$i]) > $max_filesize)
die('File is too large.');
if($_FILES['files']['type'][$i] != "image/jpeg" AND $_FILES['files']['type'][$i] != "image/png")
die('This is not available format.');
$shortname = $_FILES['files']['name'][$i];
$filePath = "img/uploaded_images/full/" .date('d-m-Y-H-i-s').'-'.$_FILES['files']['name'][$i];
if(move_uploaded_file($tmpFilePath, $filePath)) {
$files[] = $shortname;
$tmpFilePath = NULL;
$allowed_filetypes = NULL;
$max_filesize = NULL;
$filePath = NULL;
$_FILES['files']['name'][$i] = NULL;
$shortname = NULL;
$_FILES['files']['tmp_name'][$i] = NULL;
unset( $tmpFilePath);
unset($allowed_filetypes);
unset($max_filesize);
unset($filePath);
unlink($_FILES['files']['name'][$i]);
unset($_FILES['files']['name'][$i]);
unset($shortname);
unset($_FILES['files']['tmp_name'][$i]);
}
}
}
$_FILES = NULL;
unset($_FILES);
}
} ?>
Related
I want to insert multiple file names into $NewFileNames array and then pass the complete array only once and with all filenames assigned to it, so I tried at first looping in this way using an increment variable
<?php
require "prepare.php";
$allowUpload = true;
$allowtypes = array('jpg', 'png', 'jpeg', 'gif');
$maxfilesize = 80000000;
if (isset($_FILES['uploadedFile'])) {
$myFile = $_FILES['uploadedFile'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
$tmpFilePath = $_FILES['uploadedFile']['tmp_name'][$i];
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "uploads/" . $_FILES['uploadedFile']['name'][$i];
$NewFileNames = array();
array_push($NewFileNames,$newFilePath);
$imageFileType = pathinfo($newFilePath,PATHINFO_EXTENSION);
if (file_exists($newFilePath))
{
require "other\\fileExsist.php";
$allowUpload = false;
}
if ($_FILES["uploadedFile"]["size"][$i] > $maxfilesize)
{
require "other\\fileSize.php";
$allowUpload = false;
}
if (!in_array($imageFileType,$allowtypes ))
{
require "other\\fileExtenstion.php";
$allowUpload = false;
}
if ($allowUpload){
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
if (!empty($NewFileNames)){
$Files = json_encode($NewFileNames);
echo '<script>start('.$Files.');</script>';
}
}
}
}
}
}
?>
so, this code is not working in the right way because it inserts each file name to the array $NewFileNames and then calls the js script function start in line 39 several times
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
if (!empty($NewFileNames)){
$Files = json_encode($NewFileNames);
echo '<script>start('.$Files.');</script>';
}
}
but this is not what I'm trying to accomplish in this project I want the array to carry all the file names and call the javascript function start($Files) only once so, obviously the problem is with the first for loop so I thought using foreach will be easier and match what i want to do
so this is what i tried :
<?php
require "prepare.php";
$allowUpload = true;
$allowtypes = array('jpg', 'png', 'jpeg', 'gif');
$maxfilesize = 80000000;
if (isset($_FILES['uploadedFile'])) {
$myFile = $_FILES['uploadedFile'];
$fileCount = count($myFile["name"]);
// for ($i = 0; $i < $fileCount; $i++) {
foreach($_FILES['uploadedFile'] as $file) {
$tmpFilePath = $file['tmp_name'];
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "uploads/" . $file['name'];
$NewFileNames = array();
array_push($NewFileNames,$newFilePath);
$imageFileType = pathinfo($newFilePath,PATHINFO_EXTENSION);
if (file_exists($newFilePath))
{
require "other\\fileExsist.php";
$allowUpload = false;
}
if ($file["size"] > $maxfilesize)
{
require "other\\fileSize.php";
$allowUpload = false;
}
if (!in_array($imageFileType,$allowtypes ))
{
require "other\\fileExtenstion.php";
$allowUpload = false;
}
if ($allowUpload){
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
if (!empty($NewFileNames)){
$Files = json_encode($NewFileNames);
echo '<script>start('.$Files.');</script>';
}
}
}
}
}
}
?>
and this code is given this error
Warning: Undefined array key "tmp_name"
I have written a line of codes to upload an image in the database, however, trying to upload image gives me this error
File name too long
Following is my code to upload an image to database:
if($_SERVER['REQUEST_METHOD']=="POST")
{
$pid = rand(1000,9000);
$title = $_POST['title'];
$descpt = $_POST['description'];
$push = isset($_POST['send_push']) ? $_POST['send_push'] : "";
$feature_image = array();
$fy = $_POST['fy'];
if(empty($title) || empty($descpt) || empty($fy))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['feature_image']['name'][0]))
{
$image = $_FILES['feature_image'];
$allowed_ext = array('jpeg','jpg','png','pdf','docx');
$allowed_size = 20000000;
foreach($image['name'] as $pos=>$image_name)
{
$dir = "./cdn/uploads/notice/".$title;
$tmp = $image['tmp_name'][$pos];
$img_size = $image['size'][$pos];
$img_error = $image['error'][$pos];
$img_ext = explode('.', $image_name);
$img_name = $img_ext[0];
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed_ext))
{
if($img_size <= $allowed_size)
{
if(!file_exists($dir))
{
mkdir($dir);
}
$image_new_name = $img_name.'$$'.uniqid('', true).'.'.$img_ext;
$upload_destination = $dir.'/'.$image_new_name;
if(move_uploaded_file($tmp, $upload_destination))
{
array_push($feature_image, $image_new_name);
}
else
{
array_push($this->errors, $img_error);
return;
}
}
}
else
{
array_push($this->errors, $img_ext.' is not an allowed file extension.');
return;
}
}
}
$s_feature_image = json_encode($feature_image, JSON_UNESCAPED_UNICODE);
$statement = $this->db->prepare("INSERT INTO `notice` (`pid`,`title`,`descpt`,`date`,`photo`,`fy`)
VALUES (?,?,?,?,?,?)");
if($statement->execute([$pid,$title,$descpt,DAT, $s_feature_image, $fy]))
{
if($push == "checked")
{
$descpt = strip_tags($descpt);
$tek = array("message"=>$descpt,"title"=>$title);
$tokens = $this->getTokens();
$this->push_notification($tokens,$tek);
}
ExitThis::send_to(URL.'notice?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
Is it because of permission issue or something else? If so, what is causing me this problem and how do I fix this?
this is how I upload the file into the server and save the file name + extension into the database.
<?php
include 'connection.php';
$id = $_POST['id'];
$imgFile = $_FILES['photo']['name'];
$tmp_dir = $_FILES['photo']['tmp_name'];
$imgSize = $_FILES['photo']['size'];
$folder = 'images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$img = rand(1000, 1000000) . "." . $imgExt;
// allow valid image file formats
if (in_array($imgExt, $valid_extensions)) {
// Check file size '5MB'
if ($imgSize < 5000000) {
move_uploaded_file($tmp_dir, $folder . $img);
} else {
$errMSG = "Sorry, your file is too large.";
}
} else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
$query = mysqli_query($con, "UPDATE `profile` SET `photo` = '$img' WHERE `id` = '$id'");
if ($query) {
echo "<script>alert('Profile Updated'); window.location ='index.php?data=profile' </script>";
} else {
echo "<script>alert('Failed'); window.location ='index.php?data=profile' </script>";
}
?>
Hope this helps.
Cheers.
This is my code:
function secure_img_upload($file, $path, $options = array()){
// HANDLE OPTIONS
$validExtensions = isset($options['validExtensions']) ? $options['validExtensions'] : array('jpg', 'jpeg', 'png');
$surfix = isset($options['surfix']) ? $options['surfix'] : '';
// HANDLES FILES
$tempFile = $file['tmp_name'];
$fileName = $file['name'];
$extension = explode(".", $fileName);
$extension = strtolower(end($extension));
$imageName = sha1($fileName.uniqid());
$destination = rtrim($path, '/').'/'.$imageName.$surfix.'.'.$extension;
if(in_array($extension, $validExtensions)) {
$validExtension = true;
} else {
$validExtension = false;
}
// Run getImageSize function to check that we're really getting an image
if(getimagesize($tempFile) == false) {
$validImage = false;
} else {
$validImage = true;
}
if($validExtension == true && $validImage == true) {
if(move_uploaded_file($tempFile, $destination)) {
return $destination;
}else{
return array('s'=>'ko', 'm'=>T("Invalid path."));
}
}else{
return array('s'=>'ko', 'm'=>T("Invalid extension."));
}
}
My problem is that in this way, Images are uploaded in a random way.
But I need that images are uploaded in the order I select them. Any tips? Thank you
If I submit a form with multiple files in it, how can I upload each of them after some kind of execution one by one?
Add something like this to your PHP page
//upload image 1
if ($filename1<>"") {
$filename = $filename1;
$file = 'file1';
$temp = explode(".", $_FILES["file1"]["name"]);
include "upload_file.php";
$updateimageurl = mysql_query("update yacht set image1 = '$newfilename' where yachtid = '$yachtid'");
}
//upload image 2
if ($filename2<>"") {
$filename = $filename2;
$file = 'file2';
$temp = explode(".", $_FILES["file2"]["name"]);
include "upload_file.php";
$updateimageurl = mysql_query("update yacht set image2 = '$newfilename' where yachtid = '$yachtid'");
}
And then the file called "upload_file.php should look something like this (change the validation sections if you want it to validate on different file names). Also, this renames the file to a random name before saving it to your location);
<?php
$length = 30;
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
$code = "";
for ($p = 0; $p < $length; $p++) {
$pos = mt_rand(0, strlen($characters)-1);
$code .= $characters{$pos};
}
$parts = explode('.',$filename);
$extension= end($parts);
$newfilename=$code .".".$extension;
$success = 0;
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end($temp);
if ((($_FILES[$file]["type"] == "image/gif") || ($_FILES[$file]["type"] == "image/jpeg") || ($_FILES[$file]["type"] == "image/jpg")
|| ($_FILES[$file]["type"] == "image/pjpeg") || ($_FILES[$file]["type"] == "image/x-png") || ($_FILES[$file]["type"] == "image/png"))
&& ($_FILES[$file]["size"] < 1000000) && in_array($extension, $allowedExts)) {
$filenamepng = "./images/yacht/".$code.".png";
$filenamegif = "./images/yacht/".$code.".gif";
$filenamejpeg = "./images/yacht/".$code.".jpeg";
$filenamejpg = "./images/yacht/".$code.".jpg";
$filenamepjpeg = "./images/yacht/".$code.".pjpeg";
$filenamexpng = "./images/yacht/".$code.".x-png";
if (file_exists($filenamepng)||file_exists($filenamegif)||file_exists($filenamejpeg)||file_exists($filenamejpg)||file_exists($filenamepjpeg)||file_exists($filenamexpng)) {
if (file_exists($filenamepng)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.png';
unlink($filename);
}
if (file_exists($filenamegif)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.gif';
unlink($filename);
}
if (file_exists($filenamejpeg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.jpeg';
unlink($filename);
}
if (file_exists($filenamejpg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.jpg';
unlink($filename);
}
if (file_exists($filenamepjpeg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.pjpeg';
unlink($filename);
}
if (file_exists($filenamexpng)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.x-png';
unlink($filename);
}
}
move_uploaded_file($_FILES[$file]["tmp_name"],
"images/yacht/" . $newfilename);
//echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
unset($code);
$success = 1;
}
else
{
$error = "Your image is over 1mb OR is not in an accepted format; gif, jpeg, jpg, pjpeg, x-png, or png. Please try again.";
}
?>
www.clubtray.com
www.clubtray-clubmembershipsoftware.com
hopefully someone can help me here. been up all night browsing and nothing I try seems to work, but im new to php so im slow. I need to upload 6 images, and this works great. but then I realized you can upload not only images but all other file types. Im trying to be able to limit it to just images under 100kb each. heeeeelllllllpppppp!!!! please!
function findexts ($filename) { $filename = strtolower('$filename') ;
$exts = preg_split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['images']['name']) ;
$ran = rand ();
$ran2 = $ran.".";
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
See the answer to both your questions here:
https://stackoverflow.com/a/9153419/723855
Add this function to your script (modified from link):
function acceptFileUpload($thefile){
if(isset($_FILES[$thefile])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES[$thefile]['size'] >= $maxsize) || ($_FILES[$thefile]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES[$thefile]['type'], $acceptable)) && (!empty($_FILES[$thefile]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) !== 0) {
return true;
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
return false;
}
die(); //Ensure no more processing is done
}
}
}
Then in your script change your while loop to use this function to check for a valid file:
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
if(acceptFileUpload('images'))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
}
I might not have that parameter right that is getting passed to acceptFileUpload().
Four functions to run on the processing script on each file, if all tests pass then the file meets your conditions and can be safely stored (png / jpg / gif + non-zero + 10Kb limit + is uploaded file)
//Example Call: checkFileExtension($_FILES['fieldname']['name']);
function checkFileExtension($filename) {
$filename = strtolower($filename) ;
$filenamePartsArray = preg_split("[/\\.]", $filename) ;
$extension = $filenamePartsArray[count($filenamePartsArray) - 1];
if (($extension == 'gif') || ($extension == 'jpeg') || ($extension == 'jpg') || ($extension == 'png')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileMIME($_FILES['fieldname']['type']);
function checkFileMIME($filetype) {
if (($filetype == 'image/png') || ($filetype == 'image/jpeg') || ($filetype == 'image/gif')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileSize($_FILES['fieldname']['size'], 10);
function checkFileSize($filesize, $limitKb = 0) {
if ($filesize == 0) {
return false;
}
if ($limitKb != 0) {
if ($filesize > ($limitKb * 1024)) {
return false;
}
}
return true;
}
//Native Call: is_uploaded_file($_FILES['fieldname']['tmp_name']);
Edit: pseudo example use
foreach ($_FILES as $fieldname => $file) {
if ((checkFileExtension($file['name'])) && (checkFileMIME($file['type'])) && (checkFileSize($file['size'], 10)) && (is_uploaded_file($file['tmp_name']))) {
//Move the image with move_uploaded_file
//Save the file location with DB insert
}
}
you can check the file type with
$_FILES['image']['type']
or if you want to check the extension too
$extension = explode('.',(string)$_FILES['image']['name']);
//then check if its "jpg", "gif" or "png"
the file size can be checked with
$_FILES['image']['size']
so your script should be like this for each of your image updates:
$extension = explode('.',$_FILES['image']['name']);
$imgextensions = array();
$size = $_FILES['image']['size'];
if(($extension == 'jpg' || $extension == 'gif' || $extension == 'png') &&
$size < 100000 ){
// upload your file to your filesystem
}else{
//inform the user
}