Error: HTTP/1.1 401 Unauthorized - codeigniter

I made an upload system where the user uploads a file and that file is saved and then read by php. The values are inserted into a database. The whole thing works great on the development server but not on the live server.
I have another upload system on the live site that works fine. I tried uploading it to a different folder but that didnt work either.
Just so you know the other day i had problems with the mime type. So for example i uploaded a csv file but the server read it as a text/plain document. I configured configured codeigniter to allow that for csv's so that shouldnt be the problem. Just thought it was worth mentioning.
ERROR:
A PHP Error was encountered
Severity: Warning
Message: fopen(http://144.119.190.87/designUploads/testing.csv): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized
Filename: controllers/headquarters.php
Line Number: 682
==================================================
PHP:
public function importDesign () {
// setting config options
$config['upload_path'] = './designUploads/';
$config['allowed_types'] = 'csv';
$config['overwrite'] = 'true';
// loading upload library
$this->load->library('upload', $config);
// write errors to view file
$error = '';
if (!$this->upload->do_upload('userfile')) {
$this->upload->delete($lastId);
} else {
$data = array('upload_data' => $this->upload->data());
}
$fileData = $this->upload->data();
$name = $fileData['file_name'];
Line 680 ---> if (($handle = fopen(base_url('designUploads/'. $name), "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$query = $this->db->query('
UPDATE rollout_systems
SET Mig_type = "'. $data[2] .'",
hardw_destination = "'. $data[3] .'",
new_model = "'. $data[4] .'",
new_system = "'. $data[5] .'",
Mig_Class = "'. $data[6] .'"
WHERE sys_name = "'. $data[0] .'"
AND EAM_User = "'. $data[1] .'"
');
if ($query) {
redirect('headquarters/migrationDetails');
}
}
fclose($handle);
}
}

Thanks to you two that tried to help. Found the problem while comparing both the uploads i have code. As it turns out fopen() does not support base_url(). Once i got rid of that it worked.

Related

Storage disk S3 can not put file when deploy to server

I'm having a problem using Storage::disk('s3')->put() to store files to AWS S3 in laravel.
I am writing an api to upload files, everything works fine in the local environment, but when I deploy to the server it doesn't work, and the server returns a 500 error and there is no data in response
This is my code:
public static function uploadFile($file = null, $folder = null){
try {
$bucket = '';
if (empty($file->getClientOriginalName()) || empty($file->getSize())) return ResponseHelpers::clientBEErrorResponse('File Empty !', '');
if ((substr($folder, 0, 1) != '/') && !empty($folder)) $folder = '/' . $folder;
$ex_file = explode('.', $file->getClientOriginalName());
$extent = strtolower($ex_file[(count($ex_file) - 1)]);
unset($ex_file[(count($ex_file) - 1)]);
if (in_array($extent, ['jpg', 'jpeg', 'png', 'gif', 'xlsx', 'docs', 'pdf', 'docx', 'ppt', 'pptx'])) {
$uploadDir = $bucket . $folder.'/'. Str::slug($ex_file[0]).'-'.time().'.'.$extent;
if (in_array($ex_file[0], ['jpg', 'jpeg', 'png'])){
$image = \Image::make(file_get_contents($file));
$upload = Storage::disk('s3')->put($uploadDir, $image->encode('jpeg', 50));
} else{
$upload = Storage::disk('s3')->put($uploadDir, file_get_contents($file));
}
if ($upload){
return ResponseHelpers::showResponse([
'preview' => env('AWS_URL').$uploadDir,
'path' => $uploadDir
], '');
}
return ResponseHelpers::serverErrorResponse();
} else {
return ResponseHelpers::clientBEErrorResponse('Please Select File Type JPG, JPEG, PNG, GIF, XLSX, DOCS Too Upload', '');
}
} catch (\Exception $ex) {
return ResponseHelpers::serverErrorResponse($ex->getMessage(), '');
}
}
I can't even catch the error using try catch.
I tried using this function to upload files when using form with html in blade file view and strangely it still works. Looks like it only crashes when it's an API. I have checked and compared the input data of both ways, they are exactly the same.
Everything stops working when running here: Storage::disk('s3')->put($uploadDir, file_get_contents($file))
Response is completely empty and doesn't have any data or anything
Please check for me. Thanks

Upload Multiple Image when code moved to another laptop it shows error

I did my best to debug this code in my first laptop and successfully worked it out but now when i move it to another laptop it suddenly began to show some errors again which i cannot understand the reason why.
Controller
public function uploadCollateralImage_Front()
{
$config['upload_path'] = './uploads/files';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '2408';
$config['max_width'] = '2408';
$config['max_height'] = '2408';
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile1')){
$error = array('error'.'hey' => $this->upload->display_errors());
var_dump( $error); die;
}else{
$fileName = $this->upload->data();
$post_image = $fileName['file_name'];
// var_dump($post_image); die;
return $post_image;
}
}
View
<?php
$attributes = array('name' => 'applicationform');
$hidden = array('userfile1' => 'userfile1');
echo form_open_multipart("Client_Dashboard/applicationPost",$attributes, $hidden);
?>
Front-view Image
<input type="file" name="userfile1" class="w3-margin-left w3-col s10 w3-teal w3-medium w3-hover-white w3-wide " required/>
and my main method
public function applicationPost(){
$data_vehicleinformation = array();
$data_vehicleinformation['FrontImage'] = $this->uploadCollateralImage_Front();
check_insert_user = $this->foo_app->apply_loan($data_log, $data_user,
$data_loanapplication, $data_collateraldetails_app, $data_vehicleinformation ,
$data_paymentdetails, $data_loanpayment, $data_loanapproval,
$data_loanrequest);
}
it show some error like
array(1) { ["errorhey"]=> string(43) "
You did not select a file to upload.
" }
which totally means it did not end up saving in database. and i thought that my DB is the error maybe because of the collation or what other matter but its not it only show the error from function uploadCollateralImage()
as by your comment:
moved CI installation from PHP Version 5.6.23-windows8 to PHP Version
5.5.11-Windows7 Ultimate
the Codeigniter 3.x manual says:
Server Requirements
PHP version 5.6 or newer is recommended.
please check all server requirements here

file upload directory not created in my vps

file upload directory not created in my vps its show me blank page in error massege
Here is my code.
$dir_exist = true; // flag for checking the directory exist or not
if (!is_dir('./assets/uploads/profile_pictures/' . $id))
{
mkdir('./assets/uploads/profile_pictures/' . $id, 0777, true);
$dir_exist = false; // dir not exist
}
if ( ! $this->upload->do_upload('upload_profile_picture'))
{
if(!$dir_exist)
rmdir('./assets/uploads/profile_pictures/' . $id);
$error = array('error' => $this->upload->display_errors());
//$this->session->set_flashdata('error', $error[1]);
print_r($error);
}
else
{
$upload_data = $this->upload->data();
$new_name=$upload_data['file_name'];
//$this->session->set_flashdata('error', $data[1]);
}
if($new_name=='0'){
$new_name=$temp_profile_pic;
}
$date = str_replace( ':', '', $date);
if (!is_dir('uploads/'.$date)) {
mkdir('./uploads/' . $date, 0777, TRUE);
}
Please try above code and check if this code is working then definately the issue is different.
and check the id is not getting : either it will never created new dir.
Here is the reference: https://www.socketloop.com/tutorials/codeigniter-php-create-directory-if-does-not-exist-example

How to upload image file using codeigniter?

I want upload image file on server & want to stored image in database.
How can I store image file in database & also get the image file from database. Please help to solved this problem.
i have done this code in project..
but when uploading image on server upload_path not found.
In controller
$config['upload_path'] = base_url().'aplication/upload/'; // the uploaded images path
$config['allowed_types'] = 'jpg|jpeg|png';/*types of image extentions allowed to be uploaded*/
$config['max_size'] = '3048';// maximum file size that can be uploaded (2MB)
$this->load->library('upload',$config);
if ( ! is_dir($config['upload_path']) ) /* this checks to see if the file path is wrong or does not exist.*/
{
echo( $config['upload_path']);
die("THE UPLOAD DIRECTORY DOES NOT EXIST"); // error for invalid file path
$this->load->library('upload',$config); /* this loads codeigniters file upload library*/
}
if ( !$this->upload->do_upload() )
{
$error=array('error'=>$this->upload->display_errors());
//echo "UPLOAD ERROR ! ".$this->upload->display_errors(); //image error
// $this->load->view('main_view',$error);
}
else
{
$file_data=$this->upload->data();
$data['img']=base_url().'.application/upload/'.$file_data['file_name'];
echo("Image upload successfully..");
//================================================
// $this->load->model('insert_model');
// $this->insert_model->submit_image();
//==========================================
//$this->insert_model->insert_images($this->upload->data());
// $this->load->model('insert_model');
//$this->insert_model->submit_image();
}
That is quite easy. Just create image upload function once in your controller. Here is one function I wrote:
function image_upload($path, $size, $width, $height, $new_name, $ext)
{
$config['upload_path'] = $path;
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = $size;
$config['file_name'] = time() . $new_name . "." . $ext;
$config['max_width'] = $width;
$config['max_height'] = $height;
$this->load->library('upload', $config); //Load codeigniter's file upload library
if (!$this->upload->do_upload())
{
return false;
} else
{
return $config['file_name'];
}
}
Now in the action function of form where you have file input field call this function as follows do as follows:
if ($_FILES['userfile']['name'] != "")//Check if file was selected by the user
{
$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);//Get the extension of file
$picture_name = $this->image_upload("your/upload/directory/", 10000, 10000, 100000, "test", $ext);
//Now save this $picture_name in database
}
else
{
print_r($this->upload->display_errors());//Display errors if file does not get uploaded successfully
}
Thats it.
Read This, then you will get how to upload file.
Now how to store it into DB.!
In controller use this :
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$img_data = array('upload_data' => $this->upload->data());
$full_url = "/uploads/".$img_data['upload_data']['file_name'];
$reply = $this->model_name->upload_image($full_url);
}
In model using upload_image($full_url) function store image name with path, so that you can get back that path whenever needed.

codeigniter uploading image from form

I have a field of my form (which is uploading personal picture). So the user selects image from pc and submit the form. I am later on handling all posted data via:
$this->input->post()
My method for insertion into database is:
public function add_user()
{
$data = array(
'membership'=>$this->input->post('membership_type'),
'fullname'=>$this->input->post('fullname'),
'username'=>$this->input->post('username'),
'password'=>md5($this->input->post('password')),
'email'=>$this->input->post('email'),
'city'=>$this->input->post('city'));
'profilepic'=>$this->input->post('profilepic'));
$this->db->insert('members',$data);
}
Now what I want to insert in the profilepic field is the path to the image on the server. I know am doing it wrong above because this way am inserting the picture posted to profilepic. I need some correction please. Is there a function that can perform upload and return the path? but again how can I associate the upload of picture with upload of user data?
Regards,
EDIT: Tried the code provided below and got this:
A PHP Error was encountered
Severity: Notice
Message: Use of undefined constant full_path - assumed 'full_path'
Filename: models/membership_model.php
Line Number: 29
A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by
(output started at
/home2/xsysdeve/public_html/system/core/Exceptions.php:185)
Filename: core/Common.php
Line Number: 438
Please try this one:
public function add_user()
{
$config['upload_path'] = '/file_path/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->do_upload('profilepic');
$data_upload_files = $this->upload->data();
$image = $data_upload_files[full_path];
$data = array(
'membership'=>$this->input->post('membership_type'),
'fullname'=>$this->input->post('fullname'),
'username'=>$this->input->post('username'),
'password'=>md5($this->input->post('password')),
'email'=>$this->input->post('email'),
'city'=>$this->input->post('city'));
'profilepic'=>$image;
$this->db->insert('members',$data);
}
For more information visit this link: http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
You can also try using 2 CI functions and check for the POST of the textual data as well as the image validation:
class SomeForm extends CI_Controller{
function add_user() //this function is your form
{
$this->load->view('templates/header');
$this->load->view('new_form_entry', array('error' => ' ' ));
$this->load->view('templates/footer');
}
function add_user_status() //this function is your form processing
{
$config['upload_path'] = './assets/images';
$config['allowed_types'] = 'gif|jpg|png';
//$config['max_size'] = '2000';
//$config['max_width'] = '340';
//$config['max_height'] = '190';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
//check for errors with the upload
$error = array('error' => $this->upload->display_errors());
$this->load->view('templates/header');
$this->load->view('new_form_entry', $error);
$this->load->view('templates/footer');
}
else
{
//upload the new image
$upload_data = $this->upload->data();
$image_name = $upload_data['file_name'];
if($_POST){
$data = array(
'author'=>$_POST['author'],
'name'=>$_POST['name'],
'image_thumb'=>'../assets/images/'.$image_name,
'video'=>$_POST['video'],
'title'=>$_POST['title'],
'body'=>$_POST['body'],
'created' => date('Y-m-d H:i:s')
);
//insert the new post
$this->your_database_model_name->insert_entry($data);
}
redirect(base_url().'SomeForm/index');
}
}
}

Resources