Uploading image dont have an extension - php

I created a form and am trying to upload image to directory and add the path in database. Hence, i submit the form only the image filename gets submitted without file extension name and also it wont be uploaded in the directory.
Below is my php code
if(isset($_POST['addcourse'])) {
$uploadDirectory = "images/";
if (!isset($_FILES['passport']) || !is_uploaded_file($_FILES['passport']['tmp_name'])) {
$passport_data = $_FILES['passport']['tmp_name']; //file input
// $passport_name = $_FILES['passport']['name']; //unique id for random filename
$passport_size = $_FILES['passport']['size'];
$unique_name = uniqid();
$extension = pathinfo($_FILES['passport']['name'], PATHINFO_EXTENSION);
// $target_file = $uploadDirectory.basename($_FILES['passport']['name']);
$target_file = $uploadDirectory . basename($unique_name . "." . $extension);
$passport_name = $unique_name . "." . $extension;
move_uploaded_file($passport_data, $target_file);
$name = mysqli_escape_string($myConn, $_POST["name"]);
$code = mysqli_escape_string($myConn, $_POST["code"]);
$course_req = mysqli_escape_string($myConn, $_POST["course_req"]);
$course_des = mysqli_escape_string($myConn, $_POST["course_des"]);
$sql = "INSERT INTO courses (name,code,course_req,course_des,passport)
VALUES ('$name','$code','$course_req','$course_des','$passport_name')";
if (mysqli_query($myConn, $sql)) { ?>
<script type="text/javascript">
alert("New Course Created Successfully");
window.location = "addcourse";
</script>
<?php } else {
echo "Error: " . $sql . ":-" . mysqli_error($myConn);
}
mysqli_close($myConn);
}
}
?>
Below is the form i created
<form class="form-horizontal" action="insert" method="post" role="form" enctype="multipart/form-data">
<div class="form-group row">
<label class="control-label col-sm-3 align-self-center">Course Name:</label>
<div class="col-sm-9">
<input type="text" name="name" class="form-control" id="course" placeholder="Enter Course Name">
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-3 align-self-center">Course Code:</label>
<div class="col-sm-9">
<input type="text" name="code" class="form-control" id="code" placeholder="Enter Course Code">
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-3 align-self-center">Course Requirements:</label>
<div class="col-sm-9">
<textarea type="text" name="course_req" class="form-control" id="course_req" rows="3"></textarea>
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-3 align-self-center">Course Description:</label>
<div class="col-sm-9">
<textarea type="text" name="course_des" class="form-control" id="course_des" rows="3"></textarea>
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-3 align-self-center">Featured Image:</label>
<div class="col-sm-9">
<input type="file" id="myfile" name="myfile"> </div>
</div>
<div class="form-group">
<!-- <input type="submit" name="addcourse" class="btn btn-primary" Value="addcourse">
--> <button type="submit" name="addcourse" class="btn btn-primary">Submit</button>
<button type="submit" class="btn bg-danger">Cancel</button>
</div>
</form>
Attached image is how the database looks like after submission
I have checked the file naming and i expect the generated temp file name to be stored in passport field of table, then moved it the target folder.

My basic example (upload and read a file) is like that :
<?php
if (isset($_FILES['the_key']['error']) && $_FILES['the_key']['error'] == UPLOAD_ERR_OK)
{
if (is_uploaded_file($_FILES['the_key']['tmp_name']))
{
$extension = strrpos($_FILES['the_key']['name'], '.'); // locate the last dot
if ($extension !== false)
{
$extension = substr($_FILES['the_key']['name'], 1 + $extension);
// if needed add here a custom extension validation instead of ctype_alnum
$extension = ctype_alnum($extension) ? '.' . strtolower($extension) : '.unknown';
}
else
$extension = '.no-extension';
$filename = sha1(mt_rand()) . $extension ; // get a name
move_uploaded_file($_FILES['the_key']['tmp_name'], $filename); // take the file
readfile($filename); // read
unlink($filename); // delete
exit;
}
}
?>
<form method=post enctype="multipart/form-data">
<input type=file name=the_key>
<input type=submit>

Related

move_uploaded_file( ) not working on video/audio/pdf

I've done an upload page that should upload the files and set their name in the database. It works just perfect with the pictures , but the sound formats and the other ones doesn't seem to work.
This is how my html part look
<form method="post" enctype="multipart/form-data">
<div class="card card-login">
<?= FH::csrfInput() ?>
<div class="card-header text-center" data-background-color="rose" >
<h3 class="card-title">Upload</h3>
</div>
<div class="card-content">
<div class="input-group">
<span class="input-group-addon">
</span>
<div class="form-group label-floating">
<label class="control-label"><h4>Chose a name for the file</h4></label>
<br>
<input type="textd" name="name" id="name" class="form-control" value="">
</div>
<br><br>
<div class="form-group label-floating">
<label class="control-label"><h4>Choose a file</h4></label>
<br>
<input type="file" id="file" name="file" >
</div>
</div>
</div>
<div class="footer text-center">
<div class="file-upload">
<label for="submit" class="file-upload__label">
<div class="isa_error_class">
<?= FH::displayErrors($this->displayErrors)?>
</div>
<button class="btn btn-wd btn-lg" data-background-color="rose">Submit</button>
</label>
<input type="submit" name="submit" value="Submit" class="file-upload__input">
</div>
</div>
</form>
And there is the php part
if($this->request->isPost())
{
$this->request->csrfCheck();
$upload->assign($this->request->get());
$upload->user_id = Users::currentUser()->id;
$upload->name .= "." . pathinfo($_FILES['file']['name'] , PATHINFO_EXTENSION);
$value = pathinfo($_FILES['file']['name'] , PATHINFO_EXTENSION);
$upload->format = Upload::setFormat($value);
$dir = Users::currentUser()->id;
if(move_uploaded_file($_FILES["file"]["tmp_name"],'files' . DS . $dir . DS . $upload->name ))
{
if($upload->save())
{
Router::redirect('upload');
}
else
{
$upload->addErrorMessage('file','There were a problem saving in the database.');
}
}
else
{
$upload->addErrorMessage('file','There were a problem uploading it.');
}
}
The DS is the separator. The image formats seems to work perfect , but the other formats don't. Any ideas ?
You should check if u have allowed file_uploads = On in your php.ini and also check the maximum file size upload_max_filesize= 20M and to make sure that you are not passing it.

Move uploaded file in php work only sometimes when use multiple uploads

I have a web page for uploading tile image and a concept design image using that tile with a single submit button. But when uploading 2 images with a single submit, move uploaded file is not working always. Sometimes it just moves tile images only, not concept image.
Here is my code:
if(isset($_POST['upload']))
{
$name=$_POST['name'];
$size=$_POST['size'];
$finish=$_POST['finish'];
/* Concept Image */
$concept=$_FILES['concept']['name'];
$contmp=$_FILES['concept']['tmp_name'];
$location='concept';
$upload=move_uploaded_file($contmp,'concept/'.$concept);
$confile='concept/'.$concept;
/* Tile Image */
$image=$_FILES['image']['name'];
$imgtmp=$_FILES['image']['tmp_name'];
$location='tileimage';
$uploading=move_uploaded_file($imgtmp,"tileimage/".$image);
$upfile="tileimage/".$image;
$qry="insert into tile_list value('','$name','$size','$finish','$upfile','$confile')";
$ex=mysqli_query($con,$qry);
$query="insert into availcolors value('','$name','$name','$upfile','$confile')";
$exe=mysqli_query($con,$query);
}
and here is my html markup:
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-4">TILE IMAGE<br>
</label>
<div class="col-sm-10 col-md-offset-0 col-md-4">
<input type="file" class="form-control" name=image>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">CONCEPT 3D<br>
</label>
<div class="col-sm-10 col-md-offset-0 col-md-4">
<input type="file" class="form-control" name="concept">
</div>
</div>
<div class="col-sm-10 col-md-7 col-md-offset-4">
<button type="submit" name="upload"><img src="images/upload.jpg" alt="" width="106" height="25" class="img-responsive"></button>
</div>
<form>
Please help me to find out what is the problem
Please try this code:
<?php
//error_reporting(0);
if(isset($_POST['upload']))
{
$name = $_POST['name'];
$size = $_POST['size'];
$finish = $_POST['finish'];
/* Concept Image */
$aMyUploads = array();
foreach ($_FILES as $key => $aFile) {
for($i = 0; $i<count($aFile['error']); $i++){
//echo $aFile['error'][$i]; exit;
if(0 === $aFile['error'][$i]){
if($i == 0)
$newLocation = 'concept/'.$aFile['name'][$i];
else if($i == 1)
$newLocation = 'tileimage/'.$aFile['name'][$i];
}
if(0 === $aFile['error'][$i] && (false !== move_uploaded_file($aFile['tmp_name'][$i], $newLocation))){
$aMyUploads[] = $newLocation;
} else {
$aMyUploads[] = '';
}
}
}
if(is_array($aMyUploads)){
$confile=$aMyUploads[0];
$upfile=$aMyUploads[1];
$qry="insert into tile_list value('','$name','$size','$finish','$upfile','$confile')";
$ex=mysqli_query($con,$qry);
$query="insert into availcolors value('','$name','$name','$upfile','$confile')";
$exe=mysqli_query($con,$query);
}else{
echo "ERROR :: Not insert Please try";
}
}
?>
<html>
<form method="post" enctype="multipart/form-data" class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label class="control-label col-sm-4">TILE IMAGE<br></label>
<div class="col-sm-10 col-md-offset-0 col-md-4">
<input type="file" class="form-control" name="upload_files[]">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">CONCEPT 3D<br></label>
<div class="col-sm-10 col-md-offset-0 col-md-4">
<input type="file" class="form-control" name="upload_files[]">
</div>
</div>
<div class="col-sm-10 col-md-7 col-md-offset-4">
<button type="submit" name="upload"><img src="images/upload.jpg" alt="" width="106" height="25" class="img-responsive"></button>
</div>
</form>
</html>

Issue when trying to update clients info

I'm having an issue where when I go to upload or update a client, it will automatically take the clients profile off if you do not add an image to upload. But If I just want to update their website or motto, and click update, I don't want to have to try and search their image down again and upload it just to update a few items. Any Ideas on why it's doing this? Thank You In Advance.
Heres my code:
<?php
//Gets The Users info when editing it.
$stmt = $DB_con->prepare('SELECT * FROM sponsors WHERE id='.$id);
$stmt->execute();
if($stmt->rowCount() > 0)
{
$row=$stmt->fetch(PDO::FETCH_ASSOC);
extract($row);
}
?>
<div class="col-xs-12 col-sm-6 col-md-8">
<form method="post" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label for="sponsor_name" class="col-sm-3 control-label">Sponsor Name:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_name" id="sponsor_name" value="<?php echo $name;?>">
</div>
</div>
<div class="form-group">
<label for="sponsor_phone" class="col-sm-3 control-label">Sponsor Phone Number:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_phone" id="sponsor_phone" value="<?php echo $phone;?>">
</div>
</div>
<div class="form-group">
<label for="sponsor_moto" class="col-sm-3 control-label">Sponsors Motto:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_motto" id="sponsor_motto" value="<?php echo $motto;?>">
</div>
</div>
<div class="form-group">
<label for="sponsors_website" class="col-sm-3 control-label">Sponsors Website:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_website" id="sponsor_website" value="<?php echo $website;?>">
</div>
</div>
<div class="form-group">
<label for="sponsor_on" class="col-sm-3 control-label">Sponsor on or off?:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_on" id="sponsor_on" value="<?php echo $live;?>">
</div>
</div>
<div class="form-group">
<label for="image" class="col-sm-3 control-label"> Profile Picture </label>
<div class="col-sm-9">
<p><img id="image" src="../images/sponsors/<?php echo $row['logo'];?>" height="150" width="150" /></p>
<div class="col-sm-9">
<input class="input-group" type="file" name="user_image" accept="image/*" />
</div>
<br>
<br>
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" name="btn_save_updates" class="btn btn-info waves-effect waves-light">Update Sponsor</button>
Delete Sponsor</button>
</div>
</div>
</div>
</form>
Heres my PHP code that will update the Database.
<?php
if(isset($_GET['edit_id']) && !empty($_GET['edit_id']))
{
$id = $_GET['edit_id'];
$stmt_edit = $DB_con->prepare('SELECT * FROM sponsors WHERE id =:uid');
$stmt_edit->execute(array(':uid'=>$id));
$edit_row = $stmt_edit->fetch(PDO::FETCH_ASSOC);
extract($edit_row);
}
else
{
header("Location: ../../login.php");
}
if(isset($_POST['btn_save_updates']))
{
$username = $_POST['user_name'];
$description = $_POST['description'];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if($imgFile)
{
$upload_dir = '../images/sponsors/';
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userprofile = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 5000000)
{
unlink($upload_dir.$edit_row['logo']);
move_uploaded_file($tmp_dir,$upload_dir.$userprofile);
}
else
{
$errMSG = "Sorry, Your File Is Too Large To Upload. It Should Be Less Than 5MB.";
}
}
else
{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF Extension Files Are Allowed.";
}
}
else
{
$userprofile = $edit_row['userprofile'];
}
if(!isset($errMSG))
{
$sponsorname = $_POST['sponsor_name'];
$motto = $_POST['sponsor_motto'];
$phone = $_POST['sponsor_phone'];
$website = $_POST['sponsor_website'];
$son = $_POST['sponsor_on'];
$stmt = $DB_con->prepare('UPDATE sponsors SET name=:sname, motto=:smotto, phone=:sphone,website=:swebsite,live=:son, logo=:upic WHERE id=:uid');
$stmt->bindParam(':sname',$sponsorname);
$stmt->bindParam(':smotto',$motto);
$stmt->bindParam(':sphone',$phone);
$stmt->bindParam(':swebsite',$website);
$stmt->bindParam(':son',$son);
$stmt->bindParam(':upic',$userprofile);
$stmt->bindParam(':uid',$id);
if($stmt->execute()){
?>
<script>
alert('Successfully Updated...');
window.location.href='managesponsors.php?action=sponsorupdated';
</script>
<?php
}
else{
$errMSG = "Sorry User Could Not Be Updated!";
}
}
}
?>

image update cannot takeplace

I am trying to upload image to the database by update query using php file upload where database already contain a file Here is my code, problem is I doesnot get the new file.
if (isset($_POST["events"]) && isset($_POST["description"]))
{
$id = $_POST["id"];
$title = $_POST["events"];
$_POST["description"] = trim($_POST["description"]);
$description = $_POST["description"];
if(isset($_POST['images']) && !empty($_POST['images']))
{
$filetmp = $_FILES["images"]["tmp_name"];
$filename = $_FILES["images"]["name"];
$filetype = $_FILES["images"]["type"];
$filepath = "photo2/".$filename;
move_uploaded_file($filetmp,$filepath);
}
else
{
$filepath = $_POST['old_image_path'];
}
$update1 = update_query($title,$description,$filepath,$id);
if($update1)
{
header("location:hotel1_galery_event.php?msg=Update Sucess");
}
}
HTML Code Preview
<form action="hotel1_galery_eventedit.php" method="post" class="col-sm-4" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?php echo $val->event_id;?>">
<div class="form-group has-info">
<label class="control-label" for="inputSuccess">Event title</label>
<input type="text" class="form-control" name="events" value="">
</div>
<div class="form-group has-info">
<label class="control-label" >Event Description</label>
<textarea name="description" class="form-control text-left" rows="3">
</textarea>
</div>
<div class="form-group has-info">
<label>Event Related images</label>
<input type="hidden" name="old_image_path" value="<?php echo $val->image_path?>">
<input type="file" name="images" value="something">
</div>
<button type="submit" class="btn btn-primary">
<span>UPDATE</span>
</button>
</form>
input type='file' POST you file in $_FILES
SO instead of this
if(isset($_POST['images']) && !empty($_POST['images']))
You have to check your condition as
if (!empty($_FILES['images']['name'])) {
$filetmp = $_FILES["images"]["tmp_name"];
$filename = $_FILES["images"]["name"];
$filetype = $_FILES["images"]["type"];
$filepath = "photo2/" . $filename;
move_uploaded_file($filetmp, $filepath);
}

Uploading files to Amazon S3 with PHP ends up with a 28 byte file

I am working on a project where users can upload files to the site that is stored in an Amazon S3 bucket.
This doesn't really work though.. The server sees the file and everything seems good, apart from the file only being 28 bytes big when it ends up on amazon..
This is my code so far:
controller
public function uploadFile()
{
$data['username'] = $this->input->cookie('username', TRUE);
$data['pagetitle'] = "Upload file";
$data['userid'] = $this->userid;
$this->load->template('uploadFile', $data);
}
public function takeUpload()
{
$config['upload_path'] = './images/screenshots/';
$config['allowed_types'] = 'gif|jpg|png';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$projectFileLoc = $_FILES['projectFile']['tmp_name'];
$projectFileName = $_FILES['projectFile']['name'];
if (!($this->upload->do_upload("previewImage")) && !($this->s3->putObject($projectFileLoc, '3dnation', $projectFileName, $this->s3->ACL_PUBLIC_READ)))
{
echo "Something went wrong...";
}
else
{
$imgData = $this->upload->data();
$previewImage = $imgData['file_name'];
//TODO: Add image to DB
}
}
The view file (uploadFile.php)
<div class="row">
<div class="col-xs-12 col-sm-12">
<div class="jumbotron">
<h1>Upload files</h1>
</div>
</div><!--/span-->
</div><!--/row-->
<div class="row">
<div class "col-xs-12 col-sm-12">
<form action="/home/takeUpload" method="POST" role="form" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="title" placeholder="Title" name="title" required>
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<input type="textfield" class="form-control" id="description" placeholder="Enter a description here" name="description" required>
</div>
</div>
<div class="form-group">
<label for="projectFile" class="col-sm-2 control-label">Project/Scene files (accepted formats: zip, rar, 3ds)</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="projectFile" name="projectFile" required>
</div>
</div>
<div class="form-group">
<label for="previewImage" class="col-sm-2 control-label">Preview image</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="previewImage" name="previewImage" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Upload</button>
</div>
</div>
</form>
</div>
</div>
I am building it with the latest Codeigniter with this S3 library
What is wrong?
You must call to putObject with an array, if you want use a file you must call too "putObjectFile" function:
Check the definition in the class:
public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null)
{
return self::putObject(self::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType);
}
A example from the original library:
// Simple PUT:
if (S3::putObject(S3::inputFile($file), $bucket, $uri, S3::ACL_PRIVATE)) {
echo "File uploaded.";
} else {
echo "Failed to upload file.";
}
As you can see in the doc

Categories