Codeigniter switch language with url - codeigniter

I have built it all: I mean switching languages with hooks works, but now I want to get language from the url and switch it then, like:
http://localhost/about-me
or
http://localhost/o-meni
So if I send first link to someone it should automatically detect language and display that page and all navigation links in that language.
In the routes I have already forwarded to my main controller's function param which language I want to use. Now I need to set that language. But if I do $this->session->set_userdata('site_lang', "српски") language in behind doesn't change for everything.
I have noticed that, that in existing language switcher, redirection is used after setting language session to selected language, redirect to referral link, but now how to manage direct user input?
I hope I made myself clear and hope someone will get into this.
Thank you.

I found a solution like this:
Update 1:
I did it like this, first in language switcher:
class LanguageSwitcher extends CI_Controller {
public function __construct() {
parent::__construct();
}
function switchLang($language = "") {
$lang_en['about-me'] = 'o-meni';
$lang_sr['o-meni'] = 'about-me';
$lang_en['services'] = 'usluge';
$lang_sr['usluge'] = 'services';
$lang_en['products'] = 'proizvodi';
$lang_sr['proizvodi'] = 'products';
$lang_en['downloads'] = 'preuzimanja';
$lang_sr['preuzimanja'] = 'downloads';
$lang_en['contact'] = 'kontakt';
$lang_sr['kontakt'] = 'contact';
if ($language === "") {
$language = 'српски';
}
$this->session->set_userdata('site_lang', $language);
$referrer = strtolower($this->agent->referrer());
//log_message('error', "switchLang:" . $referrer . ", lang:" . $language);
if ($referrer !== "") {
$l = str_replace(base_url(), "", substr($referrer, strrpos($referrer, base_url())));
if (urldecode($language) === 'српски' && array_key_exists($l, $lang_en)) {
$referrer = str_replace($l, $lang_en[$l], $referrer);
} else
if (urldecode($language) === 'english' && array_key_exists($l, $lang_sr)) {
$referrer = str_replace($l, $lang_sr[$l], $referrer);
}
redirect($referrer);
}
}
}
and secondly in my controller, create a function to call:
private function redirectLanguage($param) {
$site_lang = urldecode($this->session->userdata('site_lang'));
//echo $param . "+" . $site_lang;
if ($param === "sr" && ($site_lang === "english" || $site_lang === "")) {
$this->session->set_userdata('site_lang', "српски");
$this->lang->load("message", "српски");
} else if ($param === "en" && ($site_lang === "српски" || $site_lang === "")) {
$this->session->set_userdata('site_lang', "english");
$this->lang->load("message", "english");
}
}
like this:
public function about($param = "") {
$this->redirectLanguage($param);
$this->load->view('header');
$this->load->view('main_starts');
$this->load->view('about-me');
$this->load->view('main_ends');
$this->load->view('footer');
}
this way I can catch it if directly pasted to the browser address bar and load the messages and set session site_lang.
Now it works, all except some issues in IE and EDGE;
Update 2:
I had to add this to make sure it will work in other browsers too:
$browser = $this->agent->browser();
if ($browser === "Chrome" || $browser === "Firefox") {
header("Cache-Control: max-age=3600, public");
} else {
header("Expires: Sun, 19 Nov 1978 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
}
because sessions won't work well in internet explorer if caching is turned on so better turn it off.

Related

laravel + vue js API store function doesn't work on shared hosting but works well on localhost

All cruds work well both on shared hosting and localhost except create (store).
here is my addtoqueue controller:
public function store(Request $request)
{
$last = antri::whereDate('created_at', Carbon::today())->latest()->first();
if ( $last ) {
$tambah = $last->number + 1;
}
else {
$tambah = 1;
}
$newantri = new antri;
$newantri->user_id = $request->user_id;
$newantri->number = $tambah;
$newantri->called = 0;
$newantri->save();
return $newantri;
}
model:
class antri extends Model
{
use HasFactory;
}
api route :
Route::post('queue', [addtoqueue::class, 'store']);
the trigger:
<v-btn elevation="2" v-on:click="increase" >Ambil Nomor Antrian</v-btn>
the script:
methods: {
increase: function() {
axios.post('/api/queue/', {
user_id: this.user.id
})
. then( response=> {
if( response.status == 200 ) {
this.$emit('itemchanged');
}
})
. catch( error => {
console.log(error);
})
window.location.reload();
}
tested using postman worked well too on both local and share hosting database.
can anyone figure out what seems to be the problem?
I found the problem. I got Status Code 301 moved permanently every time post method is requested. this caused the url structure changed from domain/api/target to domain/public/api/targetand of course it won't hit the store function in the controller.
I edited .htaccess file in public folder from:
RewriteRule ^ %1 [L,R=301]
to
RewriteRule ^ %1 [L,R=307]
which means from permanently moved to temporarily redirected.
and this solved my problem.

DOMPDF not downloading file when using AJAX

I'm trying to work with the BarryVdh/DOMPDF code in my Laravel project.
I made a page with a print button, with
Print
This is calling the controller function :
public function printFacturen(Request $request) {
$facturen = Factuur::all();
view()->share('facturen', $facturen);
$pdf = PDF::loadView('pdf.facturen');
return $pdf->download('invoice.pdf');
}
This is successfully downloading the PDF file.
My route is :
Route::get('/print-facturen', 'PrintController#printFacturen')->name('print_overzicht_facturen');
But, I need the content of a radio button to fill my PDF instead.
So I change my a href to
Print
I add a jQuery function :
$(".printbtn").click(function(e)
{
var option = $("input[name='factuur_selectie']:checked").val();
$.ajax({
type: 'POST',
url: 'print-facturen',
data: {"optionID": option}
})
});
And my controller is changed to
public function printFacturen(Request $request) {
$option = $request->get('optionID');
$facturen = Factuur::all();
$searchFacturen = new \Illuminate\Database\Eloquent\Collection();
foreach ($facturen as $factuur) {
if ($option == 1) {
$searchFacturen->add($factuur);
}
else if ($option == 2) {
if ($factuur->voldaan == true) {
$searchFacturen->add($factuur);
}
}
else if ($option == 3) {
if ($factuur->voldaan == false) {
$searchFacturen->add($factuur);
}
}
}
view()->share('facturen', $searchFacturen);
$pdf = PDF::loadView('pdf.facturen');
return $pdf->download('invoice.pdf');
}
I can see my optionID successfully, but the PDF file is NOT being downloaded anymore ... :-(
As I got a POST error, I added this route :
Route::post('/print-facturen', 'PrintController#printFacturen')->name('print_overzicht_facturen');
When inspecting the network, I see this :
SORRY, I'm not allowed yet to post pictures here :-(
(https://user-images.githubusercontent.com/5870500/32404394-3555952c-c14f-11e7-82c3-2d000d1a2661.png)
What am I doing wrong ?
Best regards,
Davy
You need to set proper http response headers:
header('Content-Type: application/octet-stream; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$filename.'"');
Other simple option to do it will be to dynamic modify link on radio click to get link like: example.org/download?radio=1

adding git tag (version ) info and change history to website

I am using Laravel for site development purposes. What would be nice is to have a button on the main page that shows the current version of the project. When clicking on the button, one would see all of the changes that have taken place (in the form of git commits) to the system. Is there a way to do this? If so, how?
TIA
On click of the button initiate an ajax call
$("#button").on("click", function () {
url: window.location.origin + '/fetch-git-commits',
type: "get",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
// data contains the git commit informations
$(".container").html(data);
}
});
In the Route.php file add an entry
Route::get('fetch-git-commits', 'YourController#getGitCommits');
In the controller
public function getGitCommits ()
{
exec('git log', $output);
$history = array();
foreach($output as $line) {
if(strpos($line, 'commit') === 0) {
if(!empty($commit)) {
array_push($history, $commit);
unset($commit);
}
$commit['hash'] = substr($line, strlen('commit'));
}
else if(strpos($line, 'Author') === 0) {
$commit['author'] = substr($line, strlen('Author:'));
}
else if(strpos($line, 'Date') === 0) {
$commit['date'] = substr($line, strlen('Date:'));
}
else {
if(isset($commit['message']))
$commit['message'] .= $line;
else
$commit['message'] = $line;
}
}
return $history; // Array of commits, parse it to json if you need
}
References:
Reading a git commit message from php
Parse git log with PHP to an array
There is a little package for that:
https://github.com/tremby/laravel-git-version

submit form if don't have error

i am using ajax for send active form by this function
public function Link()
{
$id=$this->params['id'];
$url=$this->params['url'];
$dviId=$this->params['divId'];
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() { $.ajax({url: '".$url."',type: 'POST',success : function(res){ $('#".$dviId."').html(res);}});});";
$view = $this->getView();
AjaxAsset::register($view);
if ($js2 !== '') {
$view->registerJs($js2);
}
return ;
}
And want to show error if any happened else send form
There is a plugin in jquery to do client side validation if you are using javascript and want to do initial validation of the form.
http://jqueryvalidation.org/
Also you can use "required" attribute in your text tags to do some intial checks. More can be found here:
http://www.w3schools.com/tags/att_input_required.asp
Hope this helps a bit.
You can also set enableAjaxValidation to true in your form.
There is an example in the docs about that (see the controller part).
public function Link()
{
$id=$this->params['id'];
$url=$this->params['url'];
$dviId=$this->params['divId'];
if(isset($this->params['confirm'])) {
$confirm = "if(confirm('".$this->params['confirm']."')){";
$endConfirm = "}";
}
else
{
$confirm = "";
$endConfirm = "";
}
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() {".$confirm."$.ajax({url: '".$url."',type: 'POST',beforeSend: function(){ $('body').addClass('wait');},complete: function(){ $('body').removeClass('wait');},success : function(res){ $('#".$dviId."').html(res);}});".$endConfirm."});";
$view = $this->getView();
AjaxAsset::register($view);
if ($js2 !== '') {
$view->registerJs($js2);
}
return ;
}

Duplicate site in CodeIgniter

I have a question, how to show 404 error if the page doesn't exist.For example if I have bloc.com and I add at the end of link bloc.com/?id=45 it redirects to the homepage but the page doesn't exists. In CodeIgniter exists a config :
$config['enable_query_strings'] = TRUE;
If I change to FALSE it gives errors at utm tags, how to show 404 if the page is bloc.com/?=45 but work fine at utm tags.Please help me.
function show($id = 0)
{
$date= $this->model->get_date($id);
if($date)
{
....
}
else
{
show_404();
}
}
I edited my question.
Would this not work?
public function show()
{
if (isset($_GET['id']) )
{
if ( $check = $this->model->get_date($_GET['id']) )
{
......
}
else
{
echo 'show_404()';
}
}
else
{
echo 'no ID set';
}
}

Resources