Using session_start with Laravel OR using Laravel sessions across php files - php

I am using a Laravel app, and on one of my custom pages I have the following:
index1.php:
require_once __DIR__ . '/../../../vanguard/extra/auth.php';
$request->session()->forget('token1');
$request->session()->put('token1', $generate_token1);
$request->session()->keep(['token1']);
redirectTo('index2.php');
index2.php:
require_once __DIR__ . '/../../../vanguard/extra/auth.php';
$token1 = $request->session()->get('token1');
echo $token1;
It seem's the session isn't being saved across the pages. If I use all the code on one file it works. Any ideas?
I am using this because I can't seem to use session_start(); with Laravel.

Rather making a custom page make a class
define a class with a namespace
and use it in any of your pages inside any page like below.
Here are my steps :
The content for app/library/myFunctions.php is below :
<?php namespace App\library {
class myFunctions {
public function is_ok() {
return 'myFunction is OK';
}
}
}
?>
At resources/views/test.blade.php , I added :
<?php
$FmyFunctions1 = new myFunctions;
$is_ok = ($FmyFunctions1->is_ok());
?>
Then at composer.json within "autoload": I added :
"files": [
"app/library/myFunctions.php"
],
And within app\Http\Controllers\HomeController.php at public index() I add :
return view('test');

Related

Making global helper functions in a php mvc

I have been following a tutorial to develop a mvc using php.
In the framework all the configuration settings are stored in a Config.php(Config class) under App namespace. The properties are constant so If I want to access a property, I have to use the namespace first anywhere I want to access it. So now I can access it like below
Config::DB_NAME OR Config::DB_HOST
So, Is there any way I can define a global helper function say config() using which I can access those values?
Say, If I want to access DB_NAME , I would typeconfig('DB_NAME')
Also, If I want to define some other global helper functions, How can make it?
To make the question more clear. Take Laravel's hleper functions. There is a helper function config() which returns a value from various configuration files. Like config('app.name') will return the APP Name.
These helper functions can be accessed from anywhere, Vies, Models, and Controllers.
Here is what I think can be done.
I don't want to group the functions in a class, that way I have to use namespaces.
Maybe, I can use traits to group the functions.
But How to make it available in each class. I can use use Helpers, but then
How would I access the function from a view file which doesn't have a classs?
Any, idea or suggestion would be helpful.
Config.php
<?php
namespace App;
class Config
{
const DB_HOST = 'localhost';
const DB_NAME = 'mvc';
const DB_USER = 'root';
const DB_PASSWORD = '';
const SHOW_ERRORS = false;
}
The project is currently on github, If anyone want a look of the files structure can see here
Edit
Maybe I can have config.php file which just returns an associative array.
Yet I need a helper function to get the values from it. The file would be like this.
<?php
return [
'DB_HOST'=>'localhost',
'DB_NAME'=>'mvc',
'DB_USERNAME'=>'root',
'DB_PASSWORD' =>'',
];
Thanks to you all for your help and support.
I, finally, found a solution. It's working and good for now. Maybe there is some other way but It will work for me for now.
Here are the steps that I followed to solve it.
Defined all my configuration setting in a separate file called Configs.php This file just returns an associative array.
Configs.php
<?php
return [
'DB_HOST' => 'localhost',
'DB_NAME' => 'mvc',
'DB_USER' => 'root',
'DB_PASSWORD' => '',
'SHOW_ERRORS' => false
];
I used composer to autoload my Helpers.php file. I didn't give it any namespace so it is globally loaded.
Helpers.php (OLD)
<?php
if(!function_exists('config')) {
function config($key)
{
$config_array = include 'Configs.php';
if (array_key_exists($key,$config_array))
{
return $config_array[$key];
}
}
}
Helpers.php (Updated - Suggested by Magnus Erikkson)
<?php
if (!function_exists('config')) {
function config($key, $fallback = null)
{
static $config;
if (is_null($config)) {
$config = include 'Configs.php';
}
return array_key_exists($key, $config)
? $config[$key]
: $fallback;
}
}
Both files Config.php and Helpers.php are under App directory
and here is composer.json
{
"require": {
"twig/twig": "^2.0",
"phpmailer/phpmailer": "^6.0"
},
"autoload": {
"files": [
"app/helpers.php"
],
"psr-4": {
"Core\\":"Core/",
"App\\":"App/"
}
}
}
Now, I can access it in my controller like config('DB_NAME') and it is working!

PSR4 not working?

Class not found, apparently. I've tried various things but nothing works.
Composer:
"autoload": {
"psr-4": {
"App\\": "application/"
}
}
File structure:
https://i.imgur.com/h9wOEqI.png
<?php
namespace App\Library\Classes;
defined('START') or exit('We couldn\'t process your request right now.');
class Application
{
private static $libraries = array();
public static function get($library) {
if (isset(self::$libraries[$library]) && isset(self::$classes[$library])) {
return self::$libraries[$library];
}
$fixedLibrary = str_replace('.', '/', $library);
$file = ROOT . '/application/library/classes/' . strtolower($fixedLibrary) . '.php';
self::$libraries[$library] = $library;
$declared = get_declared_classes();
$workingClass = end($declared);
self::$libraries[$library] = new $workingClass();
return self::$libraries[$library];
}
}
?>
Error is on this line:
Application::get('test')->test();
Yet, if I change it to this, it works:
include ROOT . '/application/Library/Application.php';
App\Library\Classes\Application::get('test')->test();
The PSR4 is not built-in part or PHP, you need an implementation of autoloader to use this standard such as provided by the Composer.
When you install or update depedencies, composer generates the relevant code of autoloading, but you can directly update it by the command dump-autoload, as #jibsteroos said. Next you should explicitly include the file vendor/autoload.php in the entry point of your application.
Also, error message says about class Application, but you should add the use statement at first:
use App\Library\Classes\Application;
Application::get('test')->test();
Or use the fully qualified class name (class name with namespace prefix):
\App\Library\Classes\Application::get('test')->test();

How to integrate razorpay payment gateway in codeigniter

Hi i am trying to integrate razorpay payment gateway in codeigniter. The code that I'm using is
View Code
<?php echo form_open_multipart('user/addcredit/'); ?>
<div class="form-group">
<script
src="https://checkout.razorpay.com/v1/checkout.js"
data-key="razorpay_key">
</script>
</div>
<?php echo form_close(); ?>
Controller code
class User extends CI_Controller
{
public function addcredit()
{
require_once (APPPATH . 'base_url()/litehires/assets/razorpay-php/Razorpay.php');
use Razorpay\Api\Api;
$api = new Api('rzp_test_KEY_ID', ''rzp_test_KEY_ID');
if (isset($_POST['razorpay_payment_id']) === false) {
die("Payment id not provided");
}
$id = $_POST['razorpay_payment_id'];
echo json_encode($payment->toArray());
}
}
What I got to know is that I cannot use 'use' keyword inside the function. But I'm not able to find alternative way to do the integration. I haven't use composer, so would appreciate if anyone could please tell me how to integrate this payment without composer
You can easily put the use keyword at the top of that file. If there is already an Api class clashing with this, you can do the following:
<?php
require_once (APPPATH . 'base_url()/litehires/assets/razorpay-php/Razorpay.php');
use Razorpay\Api as RazorpayApi;
class User extends CI_Controller
{
public function addcredit()
{
$api = new RazorpayApi('rzp_test_KEY_ID', 'rzp_test_KEY_ID');
This will include the file, then use the class, so it is available below in the controller.
Disclaimer: I work for Razorpay.

Class Not Found / Cannot redeclare class

Hello i am having a weird issue when try including some classes in a file in my laravel project. This is the file:
<?php namespace Libraries\MPowerLib;
require("mpower/dependency_check.php");
set_include_path(get_include_path() . PATH_SEPARATOR . realpath(dirname(__FILE__)));
abstract class MPower {
const VERSION = "1.2.0";
}
if (strnatcmp(phpversion(),'5.3.0') >= 0) {
define('JSON_ENCODE_PARAM_SUPPORT', true);
}else{
define('JSON_ENCODE_PARAM_SUPPORT', false);
}
require_once("mpower/setup.php");
require_once("mpower/customdata.php");
require_once("mpower/checkout.php");
require_once("mpower/checkout/store.php");
require_once("mpower/checkout/checkout_invoice.php");
require_once("mpower/checkout/onsite_invoice.php");
require_once("mpower/direct_pay.php");
require_once("mpower/direct_card.php");
require_once("mpower/libraries/Requests.php");
require_once("mpower/utilities.php");
Now when i use require_once i get:
Class 'Libraries\MPowerLib\MPower_Checkout_Invoice' not found
However when i use just require it works but i keep getting this error:
Cannot redeclare class libraries\mpowerlib\mpower_checkout
I am totally perplexed by this, have played around with the code trying include and include_once but still no change.
1.Add the mpower composer package to your composer.json file instead of adding the library manually
"require": {
"laravel/framework": "5.2.*",
"sirakoff/mpower_php":"dev-master"
},
2.Autoload the package by adding this to your composer.json file
"psr-0": {
"Sirakoff\\":["src/"]
}
3. Set Mpower keys and Tokens in your controllers constructor method
public function __construct(){
\MPower_Setup::setMasterKey("dd6f2c90-f075-012f-5b69-00155d866600");
\MPower_Setup::setPublicKey("test_public_oDLVlm1eNyh0IsetdhdJvcl0ygA");
\MPower_Setup::setPrivateKey("test_private_zzF3ywvX9DE-OSDNhUqKoaTI4wc");
\MPower_Setup::setMode("test");
\MPower_Setup::setToken("ca03737cf942cf644f36");
}
4. Now you can make use of the package in your controller
public function makePayment(Request $request)
{
$co = new \MPower_Checkout_Invoice();
//addItem(name_of_item,quantity,unit_price,total_price,optional_description)
$co->addItem("13' Apple Retina 500 HDD",1,1.99,1.99);
$co->addItem("Case Logic laptop Bag",2,1.50,3.00,"Black Color with white stripes");
$co->addItem("Mordecai's Bag",2,1.99,3.98);
$co->setTotalAmount(8.97);
$co->setDescription("Payment for general goods.");
$co->addTax("VAT (15)",50);
$co->addTax("NHIL (10)",50)
$co->addCustomData("Firstname","Alfred");
$co->addCustomData("Lastname","Rowe");
$co->addCustomData("CartId",929292872);
if($co->create()) {
//Your code here
}
}

Where do I put Laravel 4 helper functions that can display flash messages?

I've written a simple display_messages() function that will search Session::get('errors') for flash data and echo it to the screen.
Where do I put this function? In Codeigniter, you had a helpers folder where you could stick all your little global helper methods.
As Usman suggested,
create a file /application/libraries/demo.php
define a class Demo() { inside it
call the function like so: {{ Demo::display() }}
Works because libraries and models are autoloaded in start.php line 76. I believe that filenames must match Classnames (note capital).
<?php
class Demo {
public static function display() {
if( !$message = Session::get('errors'))
$message = 'No Errors';
echo "<pre>print_r($message)</pre>";
}
}
Can't quite figure out why I had a problem using the classname Common, there may be a conflict (you could define a namespace if this were important)...
Create a folder helpers within your app folder and create a file application_helper.php. With such code:
// app/helpers/application_helper.php
function display_messages()
{
exit('Yes');
}
Then open your composer.json file in root. autoload app/helpers/application_helper.php with composer files.
"autoload": {
....
"files": [
"app/helpers/application_helper.php"
]
Done, you can now call display_messages().
Some autoloaders may require you to run composer dump command for the first time.
Thank you memeLab provided a very useful answer which helped me a lot. I just wanted to expand on his answer as the "libraries" folder was not an auto load directory, at least not in the release/current version of L4 I am using. Also the start.php seems to have been expanded to be the start folder with global.php, local.php, and artisan.php.
So to use your own classes for separate libraries or helpers with the L4 lazy auto loader you just have to include whichever folder you want to store these in to the global.php. For example I added a libraries folder to the directory list.
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/models',
app_path().'/database/seeds',
// this a custom path
app_path().'/libraries',
));
Then whatever class you define in that folder as classname.php can be called via CLASSNAME::methodName($someVar); in your controllers.
class CLASSNAME {
public static function methodName($someVar=NULL) {
// whatever you want to do...
return $message;
}
}
So in this fashion you can create a helper class and define different methods to use throughout your controllers. Also be careful defining regular functions outside of your Class in this manner will cause you grief because they will not work (because the class is not always loaded). (for example someFunctionName($someVar); instead of CLASSNAME::methodName($someVar);) If you want to create functions in this manner you would need to make sure the is loaded, however I will not elaborate on this because it is better practice to use the lazy loader classes for such things so you only load the classes you really need.
Thanks again to memeLab and Usman, I would not have gotten as far without their answers. :)
For loading Classes:
Create app/libraries/class/Message.php, and add class in file
class Message {
public static function display() {
}
}
Add "app/libraries/class" to composer.json
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/libraries/class"
]
},
Finally run composer dump-autoload in command line.
You can access that by Message::display()
For loading plain non-object php Functions:
Create app/libraries/function/display_messages.php, and add function in file
function display_messages() {
}
add one line in start/global.php
require app_path().'/libraries/function/display_messages.php';
You can access that just by display_messages()
Add this in app/start/global.php
require app_path().'/config/autoload.php';
require app_path().'/start/loader.php';
App::instance('loader',new loader($autoload));
create a new file loader.php in app/start and add:
class loader{
private $helpers = array();
public $autoload = array(
'helpers' => array()
);
function __construct($autoload = array()) {
if (!empty($autoload))
$this->autoload = $autoload;
foreach ($this->autoload as $key => $value)
{
$function = strtolower($key);
$this->$function($value);
}
}
function helpers($helpers=array())
{
if (!is_array($helpers))
$helpers = explode(",",$helpers);
foreach ($helpers as $key => $value) {
$this->helper($value);
}
}
function helper($helper = '',$path = '/')
{
$folder = app_path().'/helpers'.$path;
if (file_exists($folder.$helper.'.php') && !in_array($helper, $this->helpers)){
$this->helpers[] = $helper;
require $folder.$helper.'.php';
}
else{
$segments = explode('/',$helper);
if (is_dir($folder.$segments[0])){
array_shift($segments);
$this->helper($segments,$path.$segments[0].'/');
}
}
}
}
create a new file autoload.php in app/config and add:
$autoload['helpers'] = array('functions'); // my autoload helpers!
create a new folder helpers in app/ , add your helper files. ( es. myhelper.php )
function myhelper()
{
echo 'helper';
}
in your controller add:
App::make('loader')->helper('myhelper');
myhelper();
In L3, I would normally create a application/libraries/helpers.php file, and require_once() it in my application/start.php. Similar to how L3 has a laravel/helpers.php file.
I'm assuming there is something similar you can do in L4.
EDIT: Just looking at the source, app/start/local.php seems like it might be the place.
I used this tutorial and i think is the easiest method: http://laravel-recipes.com/recipes/50/creating-a-helpers-file
First create the file app/helpers.php
Then either load it at the bottom of app\start\global.php as follows.
// at the bottom of the file
require app_path().'/helpers.php';
Or change your composer.json file and dump the autoloader.
{
"autoload": {
"files": [
"app/helpers.php"
]
}
}
$ composer dump-auto
then you can write your functions in helpers.php and call them from anywhere
function myfunction($result){
return $result;
}
open root_folder/vendor/laravel/framework/src/Illuminate/Support/helpers.php
and you can add your function
if ( ! function_exists('display_messages'))
{
function display_messages()
{
return ...
}
}

Categories