Why this php file upload validation script not working? - php

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.

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.

PHP upload multiple files code assistance

I have some code running on my site which works well to upload single files from file input form elements - but I now need a multiple file input form element to accept more than 1 file and upload them all to the server and store the details of the filenames uploaded in a comma separated string... Any ideas on how to make this work with the code I am using below:
form field:
<input name="logoexamples[]" id="blogoexamples" type="file" class="textInput" value="notrelevant" multiple>
PHP code (that works to accept 1 file uploaded, but not more than 1....?):
<?php
// initialize output;
$output = true;
// valid extensions
$ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf', 'jpg', 'jpeg', 'png', 'eps', 'svg', 'gif', 'ai');
// create unique path for this form submission
//$uploadpath = 'assets/uploads/';
// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.
// UPLOAD TO FOLDER IN /ASSETS/UPLOADS/ WITH ID OF THE PARENT PROJECT FOLDER RESOURCE
// Get page ID
// $pageid = $modx->resource->get('id');
// $uploadpath = 'assets/uploads/'.$pageid.'/';
// Get parent page title
$parentObj = $modx->resource->getOne('Parent');
$parentpageid = $parentObj->get('pagetitle');
$uploadpath = 'assets/uploads/'.$parentpageid.'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );
// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive
// is the file name empty (no file uploaded)
if($filename != '') {
// is this the right type of file?
if(in_array($ext, $ext_array)) {
// clean up file name and make unique
$filename = mb_strtolower($filename); // to lowercase
$filename = str_replace(' ', '_', $filename); // spaces to underscores
$filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
// full path to new file
$myTarget = $target_path . $filename;
// JWD - save uploaded filenames as a session var to get it on the redirect hook
$_SESSION['briefing_submittedfiles_' . $sf] = 'http://www.example.com/assets/uploads/'.$parentpageid.'/'.$filename;
// create directory to move file into if it doesn't exist
mkdir($target_path, 0755, true);
// is the file moved to the proper folder successfully?
if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
// set a new placeholder with the new full path (if you need it in subsequent hooks)
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
// set the permissions on the file
if (!chmod($myTarget, 0644)) { /*some debug function*/ }
} else {
// File not uploaded
$errorMsg = 'There was a problem uploading the file.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
} else {
// File type not allowed
$errorMsg = 'Type of file not allowed.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
// if no file, don't error, but return blank
} else {
$hook->setValue($sf, '');
}
}
return $output;
I had something similar coded for my website, this code is super old so don't judge or use it directly. Just an example.
if(isset($_POST['upload'])){
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "../FOLDER NAME/" . $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
copy($newFilePath, $newFilePath1);
$filename = basename($_FILES['upload']['name'][$i]);
// add $filename to list or database here
$result = "The files were uploaded succesfully.";
}else{
$result = "There was an error adding the files, please try again!";
}
}
}

Change name of uploaded file

I have been trying to change the name of a file after an upload with my script.
I want every file to be named as "testing". Later I am going to change "testing" to a
variable that gets a unique name. Now I just want to change the name to "testing".
Also the script always says error although the file are uploaded.
Can I get some help here please?
Here is my code:
<?php
$uploadDir = 'images/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO $db_table ( Image ) VALUES ('$filePath')";
mysql_query($query) or die('Error, query failed');
}
?>
I think you need
$fileName = "testing"; //maybe add extension
instead of getting original filename from $_FILES. Although after the file is moved you may end up with a situation of overwriting existing files as they all has the same name. To prevent that (for testing purposes) you may add something to $fileName, maybe a short random string.

move_uploaded_file is making a file called 'array'?

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";
}
}

File uploaded with ftp_nb_put to FileZilla FTP server in PHP is corrupted

I'm trying to upload a file using an html form. The upload method is via FTP to a FileZilla server. I have successfully uploaded the file but it seem like only it's file extension and file name are the ones that get uploaded. The file is always corrupted and doesn't display it's file size when viewing the transferred file in windows explorer. This is my code. Please help.
include 'Connections/ftpgangconnect.php';
ini_set("upload_max_filesize", "250M");
ini_set("post_max_size", "250M");
if (isset($_POST['upload'])) {
$name = $_FILES['myfile'] ['name'];
$size = $_FILES['myfile'] ['size'];
$type = $_FILES['myfile'] ['type'];
$temp = $_FILES['myfile'] ['tmp_name'];
$error = $_FILES['myfile'] ['error'];
$content = $_FILES['myfile']['content'];
$temp = $_FILES['myfile'] ['tmp_name'];
$name = $_FILES['myfile']['name'];
$dest_file ="/".$name;
// upload the file
$upload = ftp_nb_put($ftp, $dest_file, $temp, FTP_BINARY);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $name";
ftp_close($ftp);
}
}
Check the examples for the ftp_nb_put function. You should be calling the ftp_nb_continue in a loop, until the upload is finished:
// upload the file
$upload = ftp_nb_put($ftp, $dest_file, $temp, FTP_BINARY);
while ($upload == FTP_MOREDATA)
{
// Continue uploading...
$upload = ftp_nb_continue($ftp);
}
Though unless you need to do anything else in the loop, its pointless to use ftp_nb_put. Just use a simple ftp_put instead:
$upload = ftp_put($ftp, $dest_file, $temp, FTP_BINARY);

Categories