Laravel 5 getClientOriginalExtension() returns empty string - laravel

I checked if file exists using Input::hasFile('File'), and it returns true and successfully got file's binary.
But Input::file('File')->getClientOriginalExtension() returns empty string.
Here's my controller
public function ConfirmWrite()
{
if (!Session::has('id')) {
return '0:Please log in.';
}
$Data = Request::all();
$Data['uid'] = Session::get('id');
$Data['mid'] = 0;
var_dump(Input::file('File')->getClientOriginalExtension());
return '1';
if (Input::hasFile('File')) {
$file = Input::file('File');
$rules = ['File' => 'mimes:jpeg,bmp,png,jpg|max:10000'];
$validator = Validator::make(['File' => $file], $rules);
if ($validator->fails()) {
return '0:Check your File.';
}
$Data['Thumbnail'] = $file->getClientOriginalExtension();
$destinationPath = 'images/post/thumbnail/';
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
$upload_success = $file->move($destinationPath, $Content . '.' . $Data['Thumbnail']);
echo "asdfasdfasdf : ".$Data['Thumbnail'];
if ($upload_success) {
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 320, 'small');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 700, 'medium');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 1920, '');
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
} else {
return '0:Somethings wrong';
}
} else {
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
}
}
And below code is Front-end Ajax code.
var fData = new FormData;
GlobalVar.Thumbnail == '' ? '' : fData.append('File', DataURLtoBlob(GlobalVar.Thumbnail));
fData.append('Title', $('.contents-details').find('h1').html());
fData.append('Subtitle', $('.contents-details').find('h2').html());
fData.append('Content', $('#post-editor').froalaEditor('html.get'));
fData.append('Align', EditorAlign);
fData.append('Tag', Tag);
fData.append('Share',GlobalVar.FBShare);
$.ajax({
url: '{{ URL::to('/post/write') }}',
type: 'post',
processData: false,
enctype: "multipart/form-data",
contentType: false,
cache: false,
data: fData,
headers: {
'X-CSRF-Token': '{{ csrf_token() }}',
},
success: function (result) {
var Check = $.trim(result).split(':');
$('.submit-loading').css('display', 'none');
if (Check[0] == '1') {
checkUnload = false;
location.href = '{{ URL::to('post') }}/' + Check[1];
} else {
console.log(result);
Warning(Check[1]);
}
},
});
I can't find where is bug code and mistake I made. Please help me. This make me mad.

The getClientOriginalExtension method returns the extension of the actual file uploaded some-image.pdf, this is not considered a safe value. Instead you could best use guessExtension.
The guessExtension method uses the actual mime type and returns the related file type.

Related

Download txt file with laravel and axios

Hello there
Hope you will be doing good.I want to download txt file generated on the fly from the controller of laravel i have search alot but could not find any solution.Please help out i will be very thankful.
Blade code with axios request
submitHandler:function(form,e){
var btn=document.querySelector("#BtnSubmit");
btn.style.display="none";var img=document.createElement("img");
img.setAttribute("src",base_url+'front/images/loading.gif');
var loader=document.querySelector("#loader");loader.appendChild(img);
var url="<?php echo route('database.export-txtProcess');?>";
var cur_url="<?php echo route('database.export-txt');?>";
//var tblExportSelect = $("#tblExportSelect").val();
var pushArray = [];
$.each($("#tblExportSelect option:selected"), function(){
pushArray.push($(this).data("id"));
});
var data = new FormData();
data.append('tblExportSelect',pushArray);
//$("#tblExportSelect").val(selected);
axios({
method: 'POST',
url: url,
data: data,
})
.then(function(res){
console.log(res);
})
e.preventDefault();
}
});
Controller Method
public function exportTxtProcess(Request $request){
/*dd($request->tblExportSelect);*/
$tables = explode(",", $request->tblExportSelect);
$destinationPath = public_path('/');
$result;
foreach ($tables as $table) {
$outputs = DB::select("SELECT * FROM $table");
$today = date("Y-m-d");
$fileName = $table."-".$today;
$fp = fopen($destinationPath . "$fileName.txt","wb");
foreach ($outputs as $output) {
$output = (array)$output;
#array_shift($output);
$removeUserId = #$output['user_id'];
$created_at = #$output['created_at'];
$updated_at = #$output['updated_at'];
if (($key = array_search($removeUserId, $output)) !== false) {
unset($output[$key]);
}
if (($key1 = array_search($created_at, $output))) {
unset($output[$key1]);
}
if (($key2 = array_search($updated_at, $output))) {
unset($output[$key2]);
}
if (is_null($created_at) OR $created_at == '') {
unset($output['created_at']);
}
if (is_null($updated_at) OR $updated_at == '') {
unset($output['updated_at']);
}
$netResult = $this->getTableFields($table,$output);
fwrite($fp,$netResult);
}
$result = fclose($fp);
}
/*$arr = array(['Good' => true,'message' => 'Data has been successfully imported.'], 200);
echo json_encode($arr);*/
if ($result) {
$pathToFile = $destinationPath . "$fileName.txt";
$downloaded = response()->download($pathToFile)->deleteFileAfterSend();
}
}
I want to download when txt file which is created as above but instead of download it streaming in the console.
Thank in advance
You have to pass the headers. Most importantly you are not returning the reponse.
$headers = [
'Content-type' => 'text/plain',
'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
'Content-Length' => sizeof($content)
];
return response()->download($pathToFile, $fileName,$headers)->deleteFileAfterSend();

how to create a new div of json response array from controller

I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}

Codeigniter upload file with dropzone and parameters

Somehow it just doesnt upload the image to the folder. It goes so far as adding to the database (what model is all about) however no upload.
I hope to know what im doing rong. See my code bellow
The
HTML
<div class="dropzone infile dz-clickable" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" id="file" type="file" multiple />
</div>
</div>
JS
var myDropzone = new Dropzone("#my-dropzone", {
url: admin_url+'add_image/material',
files: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function (data) {
this.on("sending",function(file, xhr, formData){
file.token = Math.random().toString(36).substr(2,9);
formData.append("token",file.token);
formData.append("type", file.type);
formData.append("size", file.size);
});
this.on("complete", function (file) {
console.log(file);
});
this.on("successmultiple", function(file, response) {
console.log(file);
});
this.on("errormultiple", function(file, response) {
console.log(file);
});
this.on("removedfile",function(file){
var token = file.token;
$.ajax({
type:"post",
data:{token:token},
url: admin_url+'remove_image',
cache:false,
dataType: 'json',
success: function(res){
}
});
});
},
dictDefaultMessage: "<div class='drag-icon-cph'><i class='material-icons'>touch_app</i></div><h5>Plaats hier bestanden om te uploaden</h5>",
dictRemoveFile : "Bestand verwijderen"
});
PHP (Codeigniter)
public function add_image($type, $rel_id = 0){
if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
$path = getcwd() . '/uploads/';
$tmpFilePath = $_FILES['file']['tmp_name'];
if (!empty($tmpFilePath) && $tmpFilePath != '') {
$path_parts = pathinfo($_FILES["file"]["name"]);
$extension = $path_parts['extension'];
$extension = strtolower($extension);
$allowed_extensions = array(
'jpg',
'jpeg',
'png'
);
if (!in_array($extension, $allowed_extensions)) {
set_alert('warning', 'PHP blocked file extention');
return false;
}
$filename = uniqid(rand(), true).'.'.$extension;
$newFilePath = $path . '/' . $filename;
// Upload the file into the upload dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$CI =& get_instance();
$config = array();
$config['image_library'] = 'gd2';
$config['source_image'] = $newFilePath;
$config['new_image'] = $filename;
$config['maintain_ratio'] = true;
$CI->load->library('image_lib', $config);
$CI->image_lib->initialize($config);
$CI->image_lib->resize();
$CI->image_lib->clear();
$data = array(
'rel_type' => $type,
'rel_id' => $rel_id,
'attachment_key' => $this->input->post('token'),
'file_name' => $filename,
'filetype' => $this->input->post('type'),
'size' => $this->input->post('size'),
'dateadded' => date('Y-m-d H:i:s')
);
$id = $this->back_model->add_image($data);
if($id != ''){
array_push($_SESSION['tmp_image'],$id);
}
unlink($newFilePath);
}
}
}
}
The folder uploads is created and for security i added a empty index.html file.
.htaccess is standard Codeigniter

How to Ajax with select2 auto fill another input field

please your help ,how to auto fill with ajax + select2 using medoo framework database to autofill another input in same form .
this my ajax code :
$('.matrix').select2({
ajax: {
url: "index.php",
dataType: 'json',
data: function (params,page) {
return {
q: params.term, // search term
qa: 'matrix'
};
},
processResults: function (data,params) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
},
//cache: true,
},
minimumInputLength: 3,
placeholder: "<?php _e('Please Select'); ?>",
});
Please your advice .
This my search data :
case "matrix":
$searchstring = "";
if(isset($_GET['q'])) $searchstring = $_GET['q'];
if($searchstring != "") {
$items = $database->select("tbl_matrix", "*", [ "OR" => [
"bc_name[~]" => $searchstring
]]);
} else {
$items = $database->select("tbl_matrix", "*");
}
$results = array();
$results[0]['id'] = 0;
$results[0]['text'] = __('None');
$i = 1;
foreach($items as $item) {
$results[$i]['id'] = $item['id'];
$results[$i]['text'] = $item['bc_code']." ".$item['bc_name'];
$i++;
}
echo json_encode($results);
break;

stop page reloading when using ajax

I've created a wordpress plugin to vote on a post, using ajax.
When you click the 'vote' link the jquery popup works, your vote is added but then the page reloads
add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");
function my_user_vote() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$user_id = get_current_user_id();
date_default_timezone_set('GMT+2');
$dateVoted = get_user_meta($user_id, 'date');
$today = date('d M Y');
if ($dateVoted === $today){
//Already Voted
echo '<script language="javascript">';
echo 'alert("already voted")';
/*
echo 'alert("User ID: ' . $user_id . '")';
echo 'alert("Date Voted: ' . $dateVoted . '")';
echo 'alert("Today: ' . $today . '")';
*/
echo '</script>';
}else{
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
update_user_meta( $user_id, 'date', $today );
}
die();
}
function my_must_login() {
echo "You must log in to vote";
die();
}
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( "my_voter_script", WP_PLUGIN_URL.'/video-of-the- day/my_voter_script.js', array('jquery') );
wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'my_voter_script' );
}
I also have a jquery file:
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
}
else {
alert("Your vote could not be added")
}
}
});
})
});
why is the ajax not working?
Try this
jQuery(".user_vote").click( function(e) {
e.PreventDefault();
});

Resources