Adding Meta data to a codeigniter view from a controller - codeigniter

In my controller I have added this code.For different view files there are different functions.How can I add meta tags for different function for different views?
This is my controller:
<?php
class home extends CI_Controller {
function index()
{
$data['meta_title'] = 'Tracenow | iOS Version';
$data['meta_description'] = 'Responsive HTML5 Theme in iOS Style';
$data['meta_keywords'] = 'responsive html5 theme, ios, android, material design, landing, application, mobile, blog, portfolio, bootstrap 3, css, jquery, flat, modern';
$data['meta_author'] = '8Guild';
$data['meta_viewport'] = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
$this->load->view('home_page/home_page');
}
function about()
{
$this->load->view('home_page/about');
}
function blog()
{
$this->load->view('home_page/blog');
}
function blog_single()
{
$this->load->view('home_page/blog-single');
}
}
?>

For this you can simply use this in your controller:
$data['meta_title'] = 'Your meta title';
$data['meta_description'] = 'Your meta description';
$data['meta_keywords'] = 'Your meta keywords';
And you view should be like:
<title><?php echo $meta_title; ?></title>
<meta name="description" content="<?php echo $meta_description; ?>" />
<meta name="keywords" content="<?php echo $meta_keywords; ?>" />
Hopefully it will help you. or if you need any help please comment below.

You can use this library
Meta Tags

On your Controller
$data['metas'] = array(
array('name'=>'description', 'content'=>'A short but sweet DEFAULT description of this fine site'),
array('name' =>'keywords', 'content'=>'some awesome DEFAULT keywords for those rascally web crawlers')
);
On your View
<?php
foreach($metas as $meta)
{?>
<meta name="<?=$meta['name']?>" content="<?=$meta['content']?>" />
<?php }?>

class Home extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->helper('html'); //Load global helper 'html'
}
[...]
//in controller: meta tag
$meta = array(
array(
'name' => 'robots',
'content' => 'no-cache'
),
array(
'name' => 'description',
'content' => 'My Great Site'
),
array(
'name' => 'keywords',
'content' => 'love, passion, intrigue, deception'
),
array(
'name' => 'robots',
'content' => 'no-cache'
),
array(
'name' => 'Content-type',
'content' => 'text/html; charset=utf-8', 'type' => 'equiv'
)
);
//HTML
<!DOCTYPE html>
<head>
<title></title>
<?= meta($meta) ?> //use helper HTML to show meta tag
</head>
// Generates:
// <meta name="robots" content="no-cache" />
// <meta name="description" content="My Great Site" />
// <meta name="keywords" content="love, passion, intrigue, deception" />
// <meta name="robots" content="no-cache" />
// <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
Font:https://codeigniter.com/userguide3/helpers/html_helper.html?highlight=helper

In your controller :
$this->output->set_common_meta($page_title, $page_description, $page_keywords); // for title, description, keywords
$this->output->set_meta('property_name', 'property_value'); // for other properties

Related

laravel page The information you’re about to submit is not secure and later 419 page expired error on deployment

I have a laravel project which I have deployed on heroku. It opens when I submit the form it initially says " The information you’re about to submit is not secure " and if i still submit it, is says "419 page expired"
I tried a lot of solutions
my form sample is
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Upload File</title>
</head>
<body>
<!-- store route as action -->
<div class="container">
<div class="row">
<div class="col-12">
<br><br><br>
<form action="{{route('video')}}" method="post" enctype="multipart/form-data">
#csrf
{{ csrf_field() }}
<input type="file" class="form-control" name="videothing" id="videotitle" accept=" video/*">
<input type="submit" class="btn btn-sm btn-block btn-danger" value="Upload" onclick="spinner()">
</form>
#if (session('message'))
<h1 id="v">{{ session('message') }}</h1>
#endif
Laravel 419 Page Expired on production server. [ framework : Laravel | version : 7.5.2 ]
Laravel 6 Showed 419 | page expired
I followed these links and when I commented the
\App\Http\Middleware\VerifyCsrfToken::class,
in kernel.php, the error stops but on submitting the form it does not redirect to route rather just reloads the page,
I am sure it is CSRF issue but can't resolve it
In my VerifyCsrfToken.php, I did included
protected $except = [
//
'https://laraveluploading.herokuapp.com/',
'https://laraveluploading.herokuapp.com/video',
];
my session.php is
<?php
use Illuminate\Support\Str;
return [
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => env('SESSION_CONNECTION', 'mysql'),
'table' => 'sessions','books','videos',
'store' => env('SESSION_STORE', null),
'lottery' => [2, 100],
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
'path' => '/',
'domain' => env('SESSION_DOMAIN', 'https://laraveluploading.herokuapp.com'),
'secure' => env('SESSION_SECURE_COOKIE',false),
'http_only' => true,
'same_site' => 'lax',
];
my web.php has
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Exceptions\Handler;
use Symfony\Component\Debug\Exception\FatalThrowableError;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
})->name("start");
Route::post('/upload', function (Request $request) {
try{
if($request->file("thing")=="")
{
// return back()->withInput();
return redirect()->route('start')->with('message', 'Insert Data!');
}
else
{
$name=$request->file("thing")->getClientOriginalName();
$book=DB::table('books')->where('Title',$name)->count();
if($book>0)
{
return redirect()->route('start')->with('message', 'Document already exists!');
}
else{
$lang=$request->input("lang");
$cato=$request->input("catogory");
Storage::disk("google")->putFileAs("",$request->file("thing"),$name);
$url=Storage::disk('google')->url($name);
$details=Storage::disk("google")->getMetadata($name);
$path=$details['path'];
DB::insert('insert into books (Title, Catogory, Language, Url, FileId) values (?,?,?,?,?)', [$name,$cato,$lang,$url,$path]);
return redirect()->route('start')->with('message', 'Successfully uploaded document, you have recieved token!');
}
}
}
catch(Throwable $e)
{
return redirect()->route('start')->with('message', 'some error occured');
}
})->name("upload");
Route::get('/video', function(){
return view('showvideo');
})->name("startvideo");
Route::post('/video', function (Request $request) {
try{
if($request->file("videothing")=="")
{
// return back()->withInput();
return redirect()->route('startvideo')->with('message', 'Insert video!');
}
else
{
$videoname=$request->file("videothing")->getClientOriginalName();
$video=DB::table('videos')->where('video_name',$videoname)->count();
if($video>0)
{
return redirect()->route('startvideo')->with('message', 'Video name already exists!');
}
else{
// $lang=$request->input("lang");
// $cato=$request->input("catogory");
Storage::disk("google")->putFileAs("",$request->file("videothing"),$videoname);
$videourl=Storage::disk('google')->url($videoname);
// $videodetails=Storage::disk("google")->getMetadata($videoname);
// $path=$details['path'];
DB::insert('insert into videos (video_name, video_url) values (?,?)', [$videoname,$videourl]);
return redirect()->route('startvideo')->with('message', 'Successfully uploaded video');
}
}
}
catch(Throwable $e)
{
return redirect()->route('startvideo')->with('message', 'Some error occured in video uploading');
}
})->name("video");
in my application config var on heroku i have added the database credendtials (which is on azure) and also the google client id, secret key, refresh token required for connection with google drive.
I did tried my other solutions from different links but of no use.
Please help me resolve the issue.

Laravel 5.7 Ajax post request returns 419 status code

Hi I'm new to Laravel and I'm trying to build a login form with ajax form submission.
I copied & built a sample form with Metronic template, and trying to use ajax request to get the login check.
My code works totally fine if I exclude it from VerifyCsrfToken checking. But I do want the token validation to work.
I have read multiple post about csrf token, tried but still returns status code 419.
Sorry for the long code below, but here they are
(I know I have not done anything about setting sessions and stuff, please ignore for now coz the code returns 419 status anyway)
routes/web.php
Route::post('/auth/login', array('uses' => 'Auth\LoginController#postLogin'))->name('login');
Route::get('/landing', array('uses' => 'IndexController#landing'))->name('landing');
login.blade.php
<head>
<meta charset="utf-8" />
<title>{{ config('app.name') }} ({{ config('app.env') }})</title>
<meta name="description" content="Latest updates and statistic charts">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no">
<meta name="csrf-token" content="{{ csrf_token() }}">
<!--
Global css & js here
-->
</head>
<body>
<form class="m-login__form m-form" method="post" action="{{ route('login') }}">
#csrf
<!--
Form content here
-->
</form>
<!--begin::Page Scripts -->
<script type="text/javascript">
var form_action = '{{ route('login') }}';
</script>
<script src="{{ URL::asset('login.js')}}" type="text/javascript"></script>
<!--end::Page Scripts -->
</body>
login.js
var handleSignInFormSubmit = function() {
$('#m_login_signin_submit').click(function(e) {
e.preventDefault();
var btn = $(this);
var form = $(this).closest('form');
form.validate({
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
if (!form.valid()) {
return;
}
btn.addClass('m-loader m-loader--right m-loader--light').attr('disabled', true);
var formData = form.serialize();
$.ajax({
url:form_action,
type:'POST',
data: formData,
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType: 'json',
success:function(data){
if(data.auth){
$(location).attr('href', data.intended);
}
else{
btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
showErrorMsg(form, 'danger', 'Incorrect username or password. Please try again.');
}
},
error: function (data) {
btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
showErrorMsg(form, 'danger', 'Incorrect username or password. Please try again.');
}
});
});
}
Auth\LoginController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\URL;
use Response;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/landing';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function postLogin(Request $request) {
$auth = false;
$credentials = $request->only('email', 'password', 'remember_token');
if (Auth::attempt($credentials, $request->has('remember_token'))) {
$auth = true; // Success
}
if($auth){
if ($request->ajax()){
$response = array(
'auth' => true,
'code' => 101,
'intended' => URL::route('landing')
);
}
else{
$response = array(
'auth' => true,
'code' => 102,
'intended' => URL::route('landing')
);
}
return Response::json($response);
}
else{
$response = array(
'status' => 'error',
'msg' => 'Error',
);
return Response::json($response);
}
}
}
Part of the reponse error
message: "", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "/var/www/imas/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
line: 204
message: ""
UPDATED:
I put everything in one php file, did put csrf-token meta in head + ajaxsetup in script, still getting 419 status code
(Note: The "test123" is a post method in route file)
<!DOCTYPE html>
<html lang="en">
<!-- begin::Head -->
<head>
<meta charset="utf-8" />
<title>{{ config('app.name') }} ({{ config('app.env') }})</title>
<meta name="description" content="Latest updates and statistic charts">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no">
<meta name="csrf-token" content="{{ csrf_token() }}">
<!--begin::Web font -->
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js"></script>
<script>
WebFont.load({
google: {"families":["Poppins:300,400,500,600,700","Roboto:300,400,500,600,700"]},
active: function() {
sessionStorage.fonts = true;
}
});
</script>
<!--end::Web font -->
<!--begin:: Global Mandatory Vendors -->
<!--end:: Global Mandatory Vendors -->
<!--begin:: Global Optional Vendors -->
<!--end:: Global Optional Vendors -->
<!--begin::Global Theme Styles -->
<!--end::Global Theme Styles -->
<!--begin::Page Vendors Styles -->
<!--end::Page Vendors Styles -->
<!--begin:: Custom CSS -->
#yield('pagespecificstyles')
<!--end:: Custom CSS -->
</head>
<!-- end::Head -->
<!-- begin::Body -->
<body class="m-page--fluid m--skin- m-content--skin-light2 m-header--fixed m-header--fixed-mobile m-aside-left--enabled m-aside-left--skin-light m-aside-left--fixed m-aside-left--offcanvas m-footer--push m-aside--offcanvas-default">
<!-- begin:: Page -->
<div class="m-grid m-grid--hor m-grid--root m-page">
<!-- BEGIN: Header -->
#include('admin.top')
<!-- END: Header -->
<!-- begin::Body -->
<div class="m-grid__item m-grid__item--fluid m-grid m-grid--ver-desktop m-grid--desktop m-body">
<!-- BEGIN: Left Aside -->
#include('admin.sidenav')
<!-- END: Left Aside -->
<div class="m-grid__item m-grid__item--fluid m-wrapper">
<form name="form1" id="form1">
Name: <input type="name" name="username" id="username"/><br/>
Password: <input type="password" name="password" id="password"/><br/>
<input type="button" value="Submit" name="btn_submit" id="btn_submit"/>
</form>
</div>
</div>
<!-- end:: Body -->
<!-- begin::Footer -->
#include('admin.footer')
<!-- end::Footer -->
</div>
<!-- end:: Page -->
<!-- begin::Scroll Top -->
#include('admin.scrolltop')
<!-- end::Scroll Top -->
<!-- begin:: Script -->
#include('admin.script')
#yield('pagespecificscripts')
<script>
var formPath = '{{ route('test123') }}';
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#btn_submit').click(function(){
var formData = $('#form1').serialize();
$.ajax({
type:'POST',
url:formPath,
data:formData,
success:function(data){
alert(data);
}
});
});
});
</script>
<!-- end:: Script -->
</body>
<!-- end::Body -->
</html>
Use this in the head section HTML:
<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
And in your ajax used it in data:
<script>
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content') } });
</script>
Please refer Laravel Documentation CSRF Protection

How to add dropzone to laravel upload

I have upload function and view.
Someone could tell me how I should edit my function in controller and view to add dropzone.
Here is my controller and view:
Controller:
public function getUpload()
{
return View::make('foto/upload');
}
public function postUpload()
{
$file = Input::file('image');
$filename = $file->getClientOriginalName();
$path = 'uploads';
return $file->move($path, $filename);
}
View:
{{Form::open(array('url' => 'foto/upload', 'files' => true))}}
{{Form::file('image')}}
{{Form::submit('Upload')}}
{{Form::close()}}
my
<head>
<link rel="stylesheet" href="http://adres/assets/css/bootstrap.min.css">
<link rel="stylesheet" href="http://adres/assets/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="http://adres/assets/css/dropzone.css">
<script type="text/javascript" src="http://adres/assets/js/jquery.js"></script>
<script type="text/javascript" src="http://adres/assets/js/dropzone.js"></script>
<style>
body { padding-top: 70px; }
</style>
</head>
This isn't really a Laravel specific question.
But this is how you add a class attribute in Form::open method. You just have to add it into the options array. like so: {{Form::open(array('url' => 'foto/upload', 'files' => true, 'class' => 'dropzone'))}}, as long as it's these "reserved" word: ['method', 'url', 'route', 'action', 'files'], Form::open will just throw your options array property=>value pair into the form element.

CodeIgniter and showing images / uploading images

I am working on a gallery which is supposed to say "Please upload an image" if there are no images in the folder, but next to that also show the image uploaded but these things arent working correctly.
no errors are being shown.
Uploading images and changing them into thumbnails work and they go in the correct folder, but pulling them out is a different story, I have checked these values and they go to the correct destination:
$this->gallery_path = realpath(APPPATH . '../images');
$this->gallery_path_url = base_url() . 'images/';
and this is my autoload:
$autoload['helper'] = array('url', 'form', 'file');
this is the view where I am suspecting $data is coming out empty?:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Gallery</title>
</head>
<body>
<div id="gallery">
<?php if (isset($data) && count($data)) : ;?>
<?php foreach($images as $image): ?>
<div class="thumb">
<a href="<?php echo $image['url']; ?>">
<img src="<?php echo $image['thumb_url']; ?>" />
</div>
<?php endforeach; else: ?>
<div id="blank_gallery">Please upload an image</div>
<?php endif; ?>
</div>
<div id="upload">
<?php
echo form_open_multipart('gallery');
echo form_upload('userfile');
echo form_submit('upload', 'Upload');
echo form_close();
?>
</div>
</body>
</html>
this is my controller:
<?php
class Gallery extends CI_Controller
{
function index()
{
$this->load->model('Gallery_model');
if($this->input->post('upload'))
{
//handle upload
$this->Gallery_model->do_upload();
}
$data['images'] = $this->Gallery_model->get_images();
$this->load->view('gallery', $data);
}
}
?>
this is the model:
<?php
class Gallery_model extends CI_Model{
var $gallery_path;
var $gallery_path_url;
function __construct()
{
parent::__construct();
$this->gallery_path = realpath(APPPATH . '../images');
$this->gallery_path_url = base_url() . 'images/';
}
function do_upload()
{
//handle userfile
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => $this->gallery_path,
'max_size' => 2000
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload())
{
die($this->upload->display_errors());
}
$image_data = $this->upload->data();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->gallery_path . '/thumbs',
'maintain_ratio' => true,
'width' => 150,
'height' => 100
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
if(!$this->image_lib->resize())
{
die($this->image_lib->display_errors());
}
}
function get_images(){
$files = scandir($this->gallery_path);
$files = array_diff($files, array('.', '..', 'thumbs'));
$images = array();
foreach ($files as $file){
$images[] = array(
'url' => $this->gallery_path_url . $file,
'thumb_url' => $this->gallery_path_url . 'thumbs/' . $file,
);
}
}
}
?>
Any help much appreciated!
function get_images(){
/* all the stuff you already have... */
/* return the array! */
return $images;
}

No active access token with ajax based app

I am developing an app with 2 files:
index.php (application container)
process.php (called in ajax)
index.php
<?php
include 'config.php';
include 'lib/functions.php';
require_once 'lib/sdk/facebook.php';
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => SECRET
));
$userID = $facebook->getUser();
if (!$userID)
{
$scope = 'read_stream, publish_stream, user_likes, user_photos, user_status, friends_hometown, friends_location, friends_likes, photo_upload';
$params = array(
'scope' => $scope,
'redirect_uri' => "https://apps.facebook.com/".APP_NAME."/"
);
$loginUrl = $facebook->getLoginUrl($params);
}
else
{
$access_token = $facebook->getAccessToken();
}
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>Facebook App</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link href="/css/style.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="/js/jquery.js"></script>
</head>
<body style="margin:0 !important; padding: 0 !important;">
{ SOME HTML }
<script type="text/javascript">
function loadData()
{
$.ajax({
url: "process.php",
type: 'POST',
cache: false,
data: {
id_sessione: function(){return $("#id_sessione").val();}
},
dataType: "json",
success: function(data) {
if (data.status == "FAILURE")
alert('failure');
else
console.log(data);
}
});
}
/********* INIT ********/
$(document).ready(function(){
if ($("#userID").val() != "0")
loadData();
else
top.location = '<?php echo $loginUrl; ?>';
});
</script>
<input id="id_sessione" type="hidden" value="<?php echo session_id(); ?>" />
<input id="userID" type="hidden" value="<?php echo $userID; ?>" />
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo APP_ID; ?>',
frictionlessRequests: true
});
FB.Canvas.setAutoResize(7);
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/it_IT/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
and process.php
<?php
session_id($_POST['id_sessione']);
session_start();
include 'config.php';
include 'lib/functions.php';
require_once 'lib/sdk/facebook.php';
set_time_limit(120);
$memory_limit = ini_set('memory_limit', '512M');
try
{
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => SECRET
));
$userID = $facebook->getUser();
$user_profile = $facebook->api('/me');
{ SOME FQL QUERIES AND DATA PROCESSING }
echo json_encode(array(
'status' => 'SUCCESS',
.... other info
));
} catch (Exception $e) {
$handle = fopen(ROOT_PATH.'/log/'.$userID.'_'.uniqid().'.txt', 'a+') or die('Cannot open file');
fwrite($handle, $e->getMessage()."\n");
fwrite($handle, $e->getTraceAsString()."\n");
fclose($handle);
echo json_encode(array(
'status' => 'FAILURE'
));
}
In 95% of cases application works fine but sometimes $facebook->api('/me'); trows the exception "An active access token must be used to query information about the current user." and the $userID is equal to 0.
In order to have the same session id in all files I have to start manually session with the session_id passed by index.php in POST. This is because some browser (IE, safari) don't pass cookies of third party pages in iframe. (http://stackoverflow.com/questions/9930671/safari-3rd-party-cookie-iframe-trick-no-longer-working)
Any suggestions?
Thank you
check whether the session value is passing properly or not?

Resources