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.
Related
Please i need help on this.
I was uploading an image to my server using the move_uploaded_file() method, the method returns true bu the uploaded file was not found inside the specified directory on my server. i have checked thoroughly, searched for the file on the server in case it was uploaded to another directory, checked the permission on the directory but all seems perfect. i really dont know what went wrong .
Here is the snippet of the code.
$uploaddir = './upload_dir/';
$allowed = array('gif', 'png', 'jpg','bmp');
$filename = $_FILES['uploadfile']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$data = array();
if (!in_array($ext, $allowed)) {
$data['status'] = 'error';
$data['error_message'] = 'Invalid file type';
}
else{
$file_name = time() . '_' . uniqid() . '_' . basename($_FILES['uploadfile']['name']);
$file_name = preg_replace('/[^a-z0-9_\.\-]+/i', '_', $file_name);
$file = $uploaddir . $file_name;
if (isset($_FILES['uploadfile']['tmp_name']) && move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
$data['status'] = 'success';
$data['file_name'] = $file_name;
} else {
$data['status'] = 'error';
}
echo json_encode($data);
}
Thanks in advance.
Please use is_uploaded_file($_FILES['uploadfile']['tmp_name']) instead of isset($_FILES['uploadfile']['tmp_name']) for security reason check here
And for the upload dir use $uploaddir = $_SERVER['DOCUMENT_ROOT'] . "/upload_dir/"; instead of $uploaddir = './upload_dir/'; to get absolute path instead of relative one.
thanks everyone. I gave the wrong permission to the folder. that seems to be the problem for my own case.
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'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);
So i have the following codes that uploads an image to the dir /uploads.
<?php
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode('', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
I tried to change the code a bit. So instead of uploading to the directory, i wanted it to upload to my rackspace. I am using the following codes (which works with my other file uploads)
// cloud info
$username = ""; // username
$key = ""; // api key
// Connect to Rackspace
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
// Get the container we want to use
$container = $conn->get_container('ContainerName');
// store file information
$localfile = $_FILES['pic']['tmp_name'];
$filename = $_FILES['pic']['name'];
// upload file to Rackspace
$object = $container->create_object($filename);
$object->load_from_filename($localfile);
?>
I replaced the part where the image uploads to the dir /upload to the above one. It's not working.
I am using this HTML5 drag & drop uploader.
http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/
Help please.
I had a problem similar to this. The issue I had was that the object doesn't have the file type associated with it. Someone probably can explain it better as I am a PHP newb, but this is what I used for it to work for me:
$object = $container->create_object($filename);
$object->content_type = "image/jpeg"; //This is where the issue is
$object->load_from_filename($localfile);
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.