How to validate multiple uploaded file using php? - php

I am using PHP to upload multiple file to the database. So when I check file extension its always showing me my given error message even if file extension is correct:
File type is not allowed, We accept only .jpg, .png and .gif extension
file
Here is the validation :
$total = count($_FILES['client_doc']['name']);
for($i=0; $i<$total; $i++) {
$file_name = htmlspecialchars($_FILES['client_doc']['name'][$i]);
$file_tmp = htmlspecialchars($_FILES['client_doc']['tmp_name'][$i]);
$file_size = htmlspecialchars($_FILES['client_doc']['size'][$i]);
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed_type = array('jpg', 'jpeg', 'gif', 'png');
}
if(!empty($file_name)) {
if(!in_array($file_ext, $allowed_type)) {
$msg[] = 'File type is not allowed, We accept only .jpg, .png and .gif extension file';
$msg['error'] = true;
}elseif($file_size > 2097152) { // only 2 mb size is allowed
$msg[] = 'Uploaded file name must be less than 2MB';
$msg['error'] = true;
}
}

I've tested your code by giving the $file_name variable test.png value and it works fine. Are you sure your file form works correctly? Try to echo $file_name's at the end of for loop and check if there's any output.
Another tips:
Do you want to validate all the files? As far as I'm concerned your current code validates only the last file - you iterate through all the files, but you overwrite variables storing file's data. In order to validate all the elements you have to put your condition inside the for loop.
Because your $allowed_type is a constant, you don't have to overwrite it inside the loop.

Related

Retrieve uploaded filepath of latest added file in php

Lets start from the begining. I am a student and have recently had a course in webdevelopement with databases (Im sure the course has different name in english) and I am creating a dynamic website.
You can add, edit and remove sites/articles.
I wanted to be able to upload you own logo on your navbar neside your "tabs" but I have come to a dead end. I followed a guy on youtube that explained how to upload files to my server into a specific folder and limiting it to be only certain file types and a specific filesize.
But now i need to retrieve the filepath of that image so i can display it as a logo on my navbar on the website.
The way i started thinking was that i need to somehow get the latest modified file and then somehow get its location/filepath and then save it to a variable.
The current code i have for uploading an image is this:
its in the root folder and called "upload.php"
<?php
if (isset($_POST['upload'])) {
$file = $_FILES['file'];
/* $_FILES gives you an array of info of an file */
/* below i give each variable some info from my file */
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
/* Ext = extension.*/
/* i only want .jpg and. png files on my site */
/* Here i check if it has .jpg or png at the end of the file name */
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
/* Creating an array with accepted file endings */
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 1000000) {
/* newimages get uniq names inside database */
/* in this case it uses milliseconds */
$fileNameNew = uniqid('', true).".".$fileActualExt;
/* set file destination */
$fileDestination = 'images/'.$fileName;
move_uploaded_file($fileTmpName, $fileDestination);
header('Location: index.php?uploadsuccess');
}else {
echo "Your file was to big! Make sure it's less than 1MB!";
}
}else {
echo "There was an error uploading your file! Please try again!";
}
}else {
echo "You cannot Upload files of this type!";
}
}
And then i need to put the filepath into a variable and then add it to:
<img src="images/file_name.jpg>" class="navbar-logo" alt="">
Then replace the file_name.jpg with my variable.
I dont understand how i can achieve this. I dont have the knowledge for it and i hope that turning to stackoverflow i can get some help and learn something new on the way.
I have searched and tried out this code:
(written inside of the "upload.php" file at the bottom, outside of the "if" statement.
/* get latest image name */
$path = "images";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
Maybe i can't access the variable from the file im trying to get it from?
As mentioned, this file ("upload.php") is inside the root folder. Im trying to use the variable $latest_filename in the following place: root/views/master.php
I dont know what more to add, i tried making this as transparent as possible.

PHP upload file not working right

I have this script that is uploading file to directory and form data to database. But some how the file is not uploading and says the
variable '$filedestination' is undefined.
if(!isset($error)){
try{
if(isset($_FILES['cv'])){
$file = $_FILES['cv'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('pdf', 'doc');
$cl_name = e($_POST['cl_name']);
if(in_array($file_ext, $allowed)){
if($file_error === 0){
$new_file_name = 'cv-'.$cl_name.'-'.$file_ext;
$file_destination = 'cv/' . $new_file_name;
if(move_uploaded_file($file_tmp, $file_destination)){
} else{
$error[] = 'No se podido subir el c.v.';
}
}else{
$error[] = 'Problema';
}
}
}
$handler = $db->prepare('INSERT INTO work_with_us (work_area, cl_name, cl_last_name, cl_dir, cl_city, cl_provincia, cl_tel, cl_email, work_comentario, is_cv, cv_url) VALUES (:work_area, :cl_name, :cl_last_name, :cl_dir, :cl_city, :cl_provincia, :cl_tel, :cl_email, :work_com, :is_cv, :cv_url)');
$handler->execute(array(
':work_area' => e($_POST['work_area']),
':cl_name' => e($_POST['cl_name']),
':cl_last_name' => e($_POST['cl_last_name']),
':cl_dir' => e($_POST['cl_dir']),
':cl_city' => e($_POST['cl_city']),
':cl_provincia' => e($_POST['cl_provincia']),
':cl_tel' => (int)$_POST['cl_tel'],
':cl_email' => e($_POST['cl_email']),
':work_com' => e($_POST['work_comentario']),
':is_cv' => 'Si',
':cv_url' => $file_destination
));
}catch(PDOException $e){
$error[] = $e->getMessage();
}
}
Thing is i have the same script used, in other file and for uploading pictures and it works fine but this one for .pdf and .doc its somehow not working.
You are only allowing pdf and doc :
$allowed = array('pdf', 'doc');
So png is not allowed. As for the word file, make sure you are uploading a .doc file and not a .docx since it will not be allowed. You can add a list of allowed extensions that covers all Microsoft word extensions.
As for Microsoft extensions, check this link.
just define your $filedestination variable globally means out of if block. Your Code is OK.
Give R/W permission to the folder in which you want to move/upload your file.
Actually due to R/W permission your file is not moving try Chmod command for giving R/W permission ; if you are working on linux.
Kindly check if there is any content in $error or check $error variable value...
my another suggestion is rather than to check $file['error'],
check (getimagesize($_FILES["fileToUpload"]["tmp_name"]!==false)
Please make sure that a folder named 'cv' exists in your localserver.
And, I just noticed in your code:
$new_file_name = 'cv-'.$cl_name.'-'.$file_ext;
You will have an output like this: myfile-doc
When it is supposed to be: myfile.doc
So, I suppose it should be:
$new_file_name = 'cv-'.$cl_name.'.'.$file_ext;
I do not know if this could help you but I just notice it.

Only allow image files to be uploaded to my server with PHP

I'm trying to make a script in which I only allow .png, .jpeg and .gif files to be uploaded, based on MIME types. What I have so far is this:
if(file_exists($root."/upload/gallery/".$_FILES["image"]["name"]))
{
$filename = explode(".",$_FILES['image']['name']);
$randomnumber = rand(0, 10000);
$imageName = $filename[0].$randomnumber.".".$filename[1];
}
else
{
$imageName = $_FILES['image']['name'];
}
$image = mysql_real_escape_string(htmlspecialchars("/upload/gallery/".$imageName));
$allowed = array('image/jpeg', 'image/png', 'image/gif');
if(in_array($_FILES['image']['name'], $allowed)){
echo "Allowed!";
die;
}
else {
echo "Not allowed!";
die;
}
I was almost certain this should work. But it always echoes Not allowed! while I choose files with the correct MIME type, what am I doing wrong here? The code includes a check for files in my upload folder that already have the same name and if so adds a random number to the filename.
You are comparing the allowed list against the file name, not the type.
The type of the file will be contained in an array of applicable types in:
$_FILES['image']['type']

Check file PDF or image before upload

I am studying PHP but I don't get the right way by myself. I'd like having Img always required (and I check this in the form input required attribute) but I can decide if upload PDF or not. The script doesn't continue if I don't select both.
I have this:
// image select from form
$img = basename($_FILES['img']['name']);
$allow_img = array('jpg', 'png', 'jpeg');
$ext_img = explode('.', strtolower($_FILES['img']['name']));
$type_img= end($ext_img);
//pdf select from form
$pdf = basename($_FILES['pdf']['name']);
$allow_pdf = array('pdf');
$ext_pdf = explode('.', strtolower($_FILES['pdf']['name']));
$type_pdf= end($ext_pdf);
if ($img || $pdf) {
if(!in_array($type_img, $allow_img) || !in_array($type_pdf, $allow_pdf) ) {
echo "<p><a href='../admin.php'><img style='border:none;' src='../../img/arrow-left.png' /></a>Only jpg, png, jpeg and PDF.</p>";
}
}
Here you go a super fast way to accomplish this:
$filename = $_FILES['img']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
// allowed extensions
$allowed = array('jpeg', 'png', 'jpeg', 'gif');
if (in_array($ext, $allowed)) {
echo "<p><a href='../admin.php'><img style='border:none;' src='../../img/arrow-left.png' /></a>Only jpg, png, jpeg and PDF.</p>";
}
That's it :)
You need javascript for this.
Before you send return, you have check type of file.
Most likely the second basename() call crashes, since no $_FILES['pdf'] is present when no pdf file is uploaded. But you don't even check for an error here... Take a look into the http servers error log file, most likely you will see the error there.
That said: always look into the log files if something unexpected happens. And always test for a variables existance before you use it. And always do error checking when calling some function which might not return what you expect.
You can use pathinfo() inbuilt php function,
$File = $_FILES['image']['name'];
$Infos = pathinfo($File);
echo $extension = $info[extension];
echo "<pre>"; print_r($Infos); echo "</pre>";
$extension = strtolower( $extension);
if( $extension=='pdf'){
// do your stuff
}

Why this php file upload validation script not working?

Dear friends, this is a script which simply upload file and insert filename into database, why is this not working ? It's just upload the file and send filename to db even after validation . Please help
<?php
//file validation starts
//split filename into array and substract full stop from the last part
$tmp = explode('.', $_FILES['photo']['name']);
$fileext= $tmp[count($tmp)-1];
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(in_array($fileext, $allowedexts)){
return true;
}else{
$form_error= "Upload file was not supported<br />";
header('Location: apply.php?form_error=' .urlencode($form_error));
}
//file validation ends
//upload dir for pics
$uploaddir = './uploads/';
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile);
// $photo value is goin to db
$photo = $upload_filename;
function send_error($error = 'Unknown error accured')
{
header('Location: apply.php?form_error=' .urlencode($error));
exit; //!!!!!!
}
//file validation starts
//split filename into array and substract full stop from the last part
$fileext = end(explode('.', $_FILES['photo']['name'])); //Ricky Dang | end()
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(!in_array($fileext, $allowedexts))
{
}
//upload dir for pics
$uploaddir = './uploads/';
if(!is_dir($uploaddir))
{
send_error("Upload Directory Error");
}
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
if(!file_exists($uploadfile ))
{
send_error("File already exists!");
}
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
if(move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile))
{
send_error('Upload Failed, cannot move file!');
}
// $photo value is goin to db
$photo = $upload_filename;
This is a cleared up version to yours, give that a go and see if you get any errors
You can find the extension of file by using this code also.
$tmp = end(explode('.', $_FILES['photo']['name']));
now $tmp got the extension of file.
Why not use PHP's built-in functions to extract the extension from the filename?
$fileext = pathinfo($_FILES['photo']['name'],PATHINFO_EXTENSION);
And if the file extension is valid, you're returning from the function without doing anything further, if it's invalid you're setting the header, but the code logic will continue to your file processing
You blindly assume the file upload succeeded, but there's many reasons for it to fail, which is why PHP provides ['error'] in the $_FILES array:
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK) {
// uploaded properly, handle it here...
} else {
die("File upload error, code #" . $_FILES['photo']['error']);
}
The error codes are defined here.

Categories