PHP upload file not working right - php

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.

Related

Cannot upload file with custom php function

I try using function to upload different kind of file by giving it variables. As shown below:
<?
function fn_fileUpload($data,$dir,$uid){
include_once($_SERVER['DOCUMENT_ROOT']."/cgi-bin/connect.php");
if(isset($data) && $data['error'] === UPLOAD_ERR_OK){
$fileTmpPath = $data['tmp_name'];
$fileName = $data['name'];
$fileSize = $data['size'];
$fileType = $data['type'];
$fileNameCmps = explode(".", $fileName);
$fileExt = strtolower(end($fileNameCmps));
$newFileName = $uid . '.' . $fileExt;
//check file ext
$okEXT = array('jpg', 'jpeg', 'png','doc','docx','pdf');
if (in_array($fileExt, $okEXT)) {
$fileDir = '/'.$dir.'/';
$dest_path = $fileDir.$newFileName;
if(move_uploaded_file($fileTmpPath, $dest_path)){
try{
$stmt2=$mysqli->prepare("insert into job_file (jfile_id, job_id, jfile_name, jfile_size, jfile_type, jfile_ext) valies(?,?,?,?,?,?)");
$stmt2->bind_param('iisiss',$zero,$uid,$newFileName,$fileSize,$fileType,$fileExt);
$stmt2->execute();
$result = 'ok';
}catch(mysqli_sql_exception $err){
$result=$err;
}
}else{
$result = 'Cannot upload file!';
}
}//in_array
}//if(isset
return $result;
}
?>
And this is how to use:
//upload file
$job_file=fn_fileUpload($_FILES['job_file'],'uploads',$_POST['passport_id']);
//upload photo
$job_img=fn_fileUpload($_FILES['job_img'],'photos',$_POST['passport_id']);
From here, the function always return : Cannot upload file!. At first I think. It might have something to do with move_uploaded_file but the file was there in /uploads directory but not with /photos. Both directories CHMOD 755 (tried 777 but no luck).
The db went through correctly. Is there any idea how to fix this?
You can only use move_uploaded_file() ONCE on a temporary file that has been uploaded through a form. This function destroys the temporary file after it has been moved, so the for the first upload in the uploads directory you can do it well but in for the second one no.

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.

How to validate multiple uploaded file using 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.

how to check uploaded file is video and make ensure really video type

Selected file is not notepad file with extension avi, mp4 etc.
I tried this:
$file_allowed = array('gif','png' ,'jpg','avi','mp4','wmv','mov','flv','webm','ogv','mp3','m4a','ogg','oga');
$uploaded_filename = $_FILES['attachment']['name'];
$file_ext = pathinfo($uploaded_filename, PATHINFO_EXTENSION);
if(!in_array($file_ext,$file_allowed) )
{
exit;
}
Try this variable for validation
$_FILES["attachment"]["type"];
Try changing your code like this:
$file_allowed = array('gif','png' ,'jpg','avi','mp4','wmv','mov','flv','webm','ogv','mp3','m4a','ogg','oga');
$uploaded_filename = $_FILES["attachment"]["type"];
$file_ext = pathinfo($uploaded_filename, PATHINFO_EXTENSION);
if(!in_array($file_ext,$file_allowed) ) {
exit;
}

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