File (picture) Upload not working - image

Okay so I just basically got this code online.
It works locally (to upload a file), but it doesn't wanna work on the website.
(I've already put the permissions at 0777, for the folder, but it still won't upload.
<header>
<?php
function UploadOne($fname)
{
$uploaddir = 'pictures/';
if (is_uploaded_file($fname['tmp_name']))
{
$filname = basename($fname['name']);
$uploadfile = $uploaddir . basename($fname['name']);
if (move_uploaded_file ($fname['tmp_name'], $uploadfile))
$res = "File " . $filname . " was successfully uploaded and stored.<br>";
else
$res = "Could not move ".$fname['tmp_name']." to ".$uploadfile."<br>";
}
else
$res = "File ".$fname['name']." failed to upload.";
return ($res);
}
?> </header>
<body>
<?php
if ($_FILES['picture']['name'] != "")
{
$res = UploadOne($_FILES['picture']);
$filname = $_FILES['picture']['name'];
echo ($res);
}
?>
<h1>UPLOADING FILES</h1>
<form name="fupload" enctype="multipart/form-data" action="upfiles.php" method="post">
<input type="file" name="picture" />
<input type="submit" value="Submit" />
</form>
</body>

Related

codeigniter upload 2 files (images and video ) in separate field

Hi i am new in codeigniter , I want to upload image and video in same form with different field. i did but it store either one. last one is stored like video.
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Image</span></div>
<input id="html_btn" type="file" id="fileToUpload" name="fileToUpload" />
</div>
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Video</span></div>
<input id="html_btn" type="file" id="videoToUpload" name="videoToUpload" />
</div>
And my controller is
public function videoupdate() {
$data['user_data'] = $this->session->userdata('user_logged_in');
if (($this->session->flashdata('success')))
$data['success'] = $this->session->flashdata('success');
else
$data['error'] = $this->session->flashdata('error');
if (!empty($data['user_data']['user_id'])) {
$title = $_POST['title'];
$description = htmlentities($_POST['description']);
$target_dir = './cms/uploads/blog/video3/';
$temp = explode('.', $_FILES['fileToUpload']['name']);
$video = explode('.', $_FILES['videoToUpload']['name']);
if (!empty($_FILES['fileToUpload']['name'])) {
$newfilename = round(microtime(true)) . '.' . end($temp);
} else {
$newfilename = "";
}
if (!empty($_FILES['videoToUpload']['name'])) {
$videofilename = round(microtime(true)) . '.' . end($video);
} else {
$videofilename = "";
}
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], './cms/uploads/blog/video3/' . $newfilename);
move_uploaded_file($_FILES['videoToUpload']['tmp_name'], './cms/uploads/blog/video3/' . $videofilename);
$createddate = date('Y-m-d H:i:s');
$ipaddress = $_SERVER['REMOTE_ADDR'];
$status = $this->microblog_model->insertBlogvideo($title, $description, $newfilename, $videofilename, $data['user_data']['user_id'], $createddate, $ipaddress);
I found your code for upload files is working fine. As I check it in separate php file:
<pre>
<?php
if(isset($_POST)){
$temp = explode('.', $_FILES['fileToUpload']['name']);
$video = explode('.', $_FILES['videoToUpload']['name']);
try{
//upload image
if (!empty($_FILES['fileToUpload']['name'])) {
$newfilename = round(microtime(true)) . '.' . end($temp);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], './uploads/' . $newfilename)){
echo "Image Uploaded<br/>";
}
}
//upload video
if (!empty($_FILES['videoToUpload']['name'])) {
$videofilename = round(microtime(true)) . '.' . end($video);
if(move_uploaded_file($_FILES['videoToUpload']['tmp_name'], './uploads/' . $videofilename)){
echo "Video Uploaded<br/>";
}
}
}catch(Exception $e){
print_r($e);
}
}
?>
</pre>
<form method="post" enctype="multipart/form-data">
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Image</span></div>
<input id="html_btn" type="file" id="fileToUpload" name="fileToUpload" />
</div>
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Video</span></div>
<input id="html_btn" type="file" id="videoToUpload" name="videoToUpload" />
</div>
<input type="submit" name="submit">
</form>
You should check the size of video you are trying to upload and the maximum upload size allowed. I hope this will help. Because I checked it multiple times with many images and videos and found it is working fine.

Prevent duplicate entry in database Codeigniter

I would like to know how to prevent my upload function to insert duplicate entries into the database by using the uid.
public function upload(){
if(!empty($_FILES['uploaded_file']))
{
$path = FCPATH . "/file_attachments/signature_file/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
$base64 = base64_encode(file_get_contents($_FILES['uploaded_file']['tmp_name']));
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path))
{
$data = array (
'uid' => $this->user->get_uid(),
'image' => $base64,
'name' => basename( $_FILES['uploaded_file']['name']),
);
$this->load->database('employee');
$this->db->insert('signatures', $data);
// echo "The file ". basename( $_FILES['uploaded_file']['name']).
// " has been uploaded";
$alert = "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
else
{
// echo "There was an error uploading the file, please try again!";
$alert ="There was an error uploading the file, please try again!";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
}
}
Here's my view file. I haven't got the time to edit the unnecessary things in here. The problem is still that if it got duplicate entries the database error still shows up and that is what I'm preventing to do so. Cheers!
<div class="bod">
<div class="insta">
<form enctype="multipart/form-data" style="padding-top: 10px" name="exit_form" method="post" action="<?= base_url() ?>signature_uploader/upload">
<input type="hidden" name="uid" value="<?= $agent->get_uid() ?>" />
<input type="hidden" name="gid" value="<?= $agent->get_gid() ?>" />
<input type="hidden" name="fname" value="<?= $agent->get_fname() ?>" />
<input type="hidden" name="lname" value="<?= $agent->get_lname() ?>" />
<div style="text-align: center; font-size: 25pt; margin-bottom: 15px">Signature Uploader</div>
<table width="105%">
<tr>
<td width="40%"><strong>Name: </strong><input class="textinput" disabled="disabled" type="text" name="full_name" id="textfield3" size="35" value="<?= $agent->get_fullName() ?>" /></td>
<tr/>
<tr>
<td><label>Upload Image File:</label><br /> <input name="uploaded_file" type="file" accept=".png" required/>
</tr>
<table/>
<br />
<input type="submit" value="Submit" class="button1" />
</form>
<br/>
</div>
You can use from Codeigniter form validation to prevent from duplicate entry:
at first you must get the uid in the form view like this:
<input type="hidden" name="uid" value="<?php echo $this->user->get_uid() ?>">
and then in your controller:
public function upload(){
if(!empty($_FILES['uploaded_file']))
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('uid', 'UID', 'is_unique[signatures.uid]');
if ($this->form_validation->run() == FALSE)
{
// Your Code if the uid is duplicate
$alert ="Could't upload because of duplicate entry!";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
else
{
// Your Code if the uid is unique
$path = FCPATH . "/file_attachments/signature_file/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
$base64 = base64_encode(file_get_contents($_FILES['uploaded_file']['tmp_name']));
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
$data = array (
'uid' => $this->input->post('uid'),
'image' => $base64,
'name' => basename( $_FILES['uploaded_file']['name']),
);
$this->load->database('employee');
$this->db->insert('signatures', $data);
// echo "The file ". basename( $_FILES['uploaded_file']['name']).
// " has been uploaded";
$alert = "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
} else{
// echo "There was an error uploading the file, please try again!";
$alert ="There was an error uploading the file, please try again!";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
}
}
}
Either you can check weather such file exists or not, but normally while creating a code which uploads file, has a function which will generate unique name for each file that we upload. So in such cases it will have duplicate entries with different name.
Only way i see is to create a function that will check weather the file name already exists in database.

Adding a file field to the manifest file

My plugin requires a user to upload a file.
The manifest field doesn't set the form enctype="multipart/form-data" so when a file is uploaded it gets lost.
Is there a way to change this?
form xml :
<field name="con_image" type="file" label="" description="" hint="Image"/>
default.php
<div class="controls">
<?php if (!empty($this->item->con_image) && file_exists(JPATH_SITE.'/images/contact_image/thumb_' . $this->item->con_image)) : ?>
<img src="<?php echo JRoute::_(JUri::root() . 'images/contact_image/thumb_' . $this->item->con_image, false);?>">
<?php endif; ?>
<input type="hidden" name="jform[con_image]" id="jform_image_hidden" value="<?php echo $this->item->con_image; ?>" />
<?php echo $this->form->renderField('con_image'); ?>
</div>
your view table file code for image upload:
$files = $app->input->files->get('jform', array(), 'raw');
$array = $app->input->get('jform', array(), 'ARRAY');
if (!empty($files['con_image']['name']))
{
// Deleting existing files
$oldFiles = PlansHelpersPlans::getFiles($this->id, $this->_tbl, 'con_image');
foreach ($oldFiles as $f)
{
$oldFile = JPATH_ROOT . '/images/contact_image/' . $f;
if (file_exists($oldFile))
{
unlink($oldFile);
}
}
$this->con_image = "";
$singleFile = $files['con_image'];
jimport('joomla.filesystem.file');
// Check if the server found any error.
$fileError = $singleFile['error'];
$message = '';
if ($fileError > 0 && $fileError != 4)
{
switch ($fileError)
{
case 1:
$message = JText::_('File size exceeds allowed by the server');
break;
case 2:
$message = JText::_('File size exceeds allowed by the html form');
break;
case 3:
$message = JText::_('Partial upload error');
break;
}
if ($message != '')
{
$app->enqueueMessage($message, 'warning');
return false;
}
}
elseif ($fileError == 4)
{
if (isset($array['con_image']))
{
$this->con_image = $array['con_image'];
}
}
else
{
// Replace any special characters in the filename
jimport('joomla.filesystem.file');
$filename = JFile::stripExt($singleFile['name']);
$extension = JFile::getExt($singleFile['name']);
$filename = preg_replace("/[^A-Za-z0-9]/i", "-", $filename);
$filename = rand()."-".$filename . '.' . $extension;
$uploadPath = JPATH_ROOT . '/images/contact_image/' . $filename;
$fileTemp = $singleFile['tmp_name'];
if (!JFile::exists($uploadPath))
{
if (!JFile::upload($fileTemp, $uploadPath))
{
$app->enqueueMessage('Error moving file', 'warning');
return false;
}
}
//$this->con_image .= (!empty($this->con_image)) ? "," : "";
$this->con_image = $filename;
}
}else{
$this->con_image = $array['con_image'];
}
Still you have problem then check HERE
Download my simple component : https://github.com/erakashpatel/Important-notes/blob/master/com_helloworld.zip
OR
https://github.com/erakashpatel/Important-notes/blob/master/com_test.zip
I hope its works.Thanks in advance.
for xml :
Joomla File form field type in xml:
https://docs.joomla.org/File_form_field_type
<field name="myfilevalue" type="file" label="Enter some text" description="Choose an image from your computer with maximum 100KB" size="10" accept="image/*" />
OR
if your file field in html form then used :
<input type="file" name="jform[myfilevalue]" >
I hope its help,
else provide more description please

How can i upload image from front-end in magento?

I am trying to upload single image from front-end in my custom module. This is my form in test/template/test.phtml
<form action="<?php echo Mage::getUrl('text/index/save') ?>" method="post" enctype="multipart/form-data">
<label for="sb_link">Image</label>
<input type="file" id="bs_image" name="bs_image" required="true"/>
<input type="submit" value="Submit" />
Here is my controller where i am uploading images in media folder and saving name in databse.
<?php
public function saveAction() {
echo $path = Mage::getBaseDir() . '/test';
if (!file_exists($path)) {
mkdir($path, 777, true);
}
try {
$fname = $_FILES['test']['name'];
$uploader = new Varien_File_Uploader('test');
$uploader->setAllowedExtensions(array('png', 'gif', 'jpeg', 'docx'));
$uploader->setAllowCreateFolders(true);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$uploader->save($path, $fname);
} catch (Exception $e) {
echo 'Error Message: ' . $e->getMessage();
}
$contact = Mage::getModel('test/test');
$contact->setData('bs_image', $bs_image);
$contact->save();
$this->_redirectReferer();
}
I am getting this error.Error Message: File was not uploaded.
Thanks
I have checked your code. In form you use the name as bs_image for image field. But in controller you get the post file as $_FILES['test']['name'];. Change this to $_FILES['bs_image']['name']; .
Make sure that you have put end form tag in your file.
You need to access file name like this
$fname = $_FILES['bs_image']['name'];

CodeIgniter - Image submit button not working

I am using CI to create a project for a client, I have a submit button as an image but it doesn't seem to be submitting the form, the code I have at the moment is.
<input type="image" name="trialSubmit" id="trialSubmit" src="<?php echo base_url().'images/subscribe_free.jpg'; ?>" style="height:29px;width:207px;border-width:0px;" />
The code I have to use at the moment is as follows
<input type="submit" name="trialSubmit" value=" Subscribe Free " id="" class="button" />
If anyone could shed some light on why it's not working with the image, that would be tight.
Cheers,
Is it across all browsers? Or IE specific? What about if you add an onclick event just for testing? onclick="javascript:document.formidhere.submit()"
I'd recommend using either <input type="submit" /> or my preference would be to use <button type="submit> due to browser inconsistencies with <input type="image" /> and just style the button with something like:
button{
background:url('/images/subscribe_free.jpg') no-repeat;
height:29px;
width:207px;
border:0;
}
Try adding value="trialSubmit" to get the image to submit. Seemed to work for me.
You could also see if this answer helps:
image submit button
**inside the view(as comerciales in my case)**,
<form action= "<?php echo site_url()?>/admin/doupload" method="post" enctype="multipart/form-data" >
<b> Select the image to upload( Maximum size 500 kb, jpg, jpeg): </b>
<input style="color:#00A76F" type="file" name="fileToUpload" id="fileToUpload">
<div class="input-group" style="left:10%;width:85%;">
<input class="btn btn-success pull-right" style="background:#00A76F" type="submit" value="Upload Image" name="submit">
</div>
</form>
<div class="modal-body">
<div id="user_data">
<?php
if (!empty($massage)){
echo $massage ;
}
?>
</div>
**inside the controller define a method**
public function doupload(){
$root1 = $_SERVER['DOCUMENT_ROOT'];;
$target_dir = $root1."/nawaloka/uploads/";
// $target_dir = $root1."/nawaloka/application/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$data['massage']= "Sorry, your file is too large.";
$partials = array('content' => 'Admin/comerciales');
$this->template->load('template/admin_template', $partials,$data);
$uploadOk = 0;
}
if (is_dir($target_dir) && is_writable($target_dir)) {
// do upload logic here
} else {
echo 'Upload directory is not writable, or does not exist.';
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "jpeg" ) {
$data['massage']= "Sorry, only JPG, JPEG files are allowed.";
$partials = array('content' => 'Admin/comerciales');
$this->template->load('template/admin_template', $partials,$data);
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$data['massage']= "Sorry, your file was not uploaded.";
$partials = array('content' => 'Admin/comerciales');
$this->template->load('template/admin_template', $partials,$data);
// if everything is ok, try to upload file
} else {
array_map('unlink', glob("/var/www/html/nawaloka/uploads/*"));
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],"/var/www/html/nawaloka/uploads/shamith.jpg")) {
$data['massage']= "The image ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
$partials = array('content' => 'Admin/comerciales');
$this->template->load('template/admin_template', $partials,$data);
//echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
$data['massage']= "Sorry, there was an error while uploading your file.";
$partials = array('content' => 'Admin/comerciales');
$this->template->load('template/admin_template', $partials,$data);
}
}
}

Resources