#how laravel facade works
Explore tagged Tumblr posts
pentesttestingcorp · 4 months ago
Text
Prevent HTTP Parameter Pollution in Laravel with Secure Coding
Understanding HTTP Parameter Pollution in Laravel
HTTP Parameter Pollution (HPP) is a web security vulnerability that occurs when an attacker manipulates multiple HTTP parameters with the same name to bypass security controls, exploit application logic, or perform malicious actions. Laravel, like many PHP frameworks, processes input parameters in a way that can be exploited if not handled correctly.
Tumblr media
In this blog, we’ll explore how HPP works, how it affects Laravel applications, and how to secure your web application with practical examples.
How HTTP Parameter Pollution Works
HPP occurs when an application receives multiple parameters with the same name in an HTTP request. Depending on how the backend processes them, unexpected behavior can occur.
Example of HTTP Request with HPP:
GET /search?category=electronics&category=books HTTP/1.1 Host: example.com
Different frameworks handle duplicate parameters differently:
PHP (Laravel): Takes the last occurrence (category=books) unless explicitly handled as an array.
Express.js (Node.js): Stores multiple values as an array.
ASP.NET: Might take the first occurrence (category=electronics).
If the application isn’t designed to handle duplicate parameters, attackers can manipulate input data, bypass security checks, or exploit business logic flaws.
Impact of HTTP Parameter Pollution on Laravel Apps
HPP vulnerabilities can lead to:
✅ Security Bypasses: Attackers can override security parameters, such as authentication tokens or access controls. ✅ Business Logic Manipulation: Altering shopping cart data, search filters, or API inputs. ✅ WAF Evasion: Some Web Application Firewalls (WAFs) may fail to detect malicious input when parameters are duplicated.
How Laravel Handles HTTP Parameters
Laravel processes query string parameters using the request() helper or Input facade. Consider this example:
use Illuminate\Http\Request; Route::get('/search', function (Request $request) { return $request->input('category'); });
If accessed via:
GET /search?category=electronics&category=books
Laravel would return only the last parameter, category=books, unless explicitly handled as an array.
Exploiting HPP in Laravel (Vulnerable Example)
Imagine a Laravel-based authentication system that verifies user roles via query parameters:
Route::get('/dashboard', function (Request $request) { if ($request->input('role') === 'admin') { return "Welcome, Admin!"; } else { return "Access Denied!"; } });
An attacker could manipulate the request like this:
GET /dashboard?role=user&role=admin
If Laravel processes only the last parameter, the attacker gains admin access.
Mitigating HTTP Parameter Pollution in Laravel
1. Validate Incoming Requests Properly
Laravel provides request validation that can enforce strict input handling:
use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; Route::get('/dashboard', function (Request $request) { $validator = Validator::make($request->all(), [ 'role' => 'required|string|in:user,admin' ]); if ($validator->fails()) { return "Invalid Role!"; } return $request->input('role') === 'admin' ? "Welcome, Admin!" : "Access Denied!"; });
2. Use Laravel’s Input Array Handling
Explicitly retrieve parameters as an array using:
$categories = request()->input('category', []);
Then process them safely:
Route::get('/search', function (Request $request) { $categories = $request->input('category', []); if (is_array($categories)) { return "Selected categories: " . implode(', ', $categories); } return "Invalid input!"; });
3. Encode Query Parameters Properly
Use Laravel’s built-in security functions such as:
e($request->input('category'));
or
htmlspecialchars($request->input('category'), ENT_QUOTES, 'UTF-8');
4. Use Middleware to Filter Requests
Create middleware to sanitize HTTP parameters:
namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class SanitizeInputMiddleware { public function handle(Request $request, Closure $next) { $input = $request->all(); foreach ($input as $key => $value) { if (is_array($value)) { $input[$key] = array_unique($value); } } $request->replace($input); return $next($request); } }
Then, register it in Kernel.php:
protected $middleware = [ \App\Http\Middleware\SanitizeInputMiddleware::class, ];
Testing Your Laravel Application for HPP Vulnerabilities
To ensure your Laravel app is protected, scan your website using our free Website Security Scanner.
Tumblr media
Screenshot of the free tools webpage where you can access security assessment tools.
You can also check the website vulnerability assessment report generated by our tool to check Website Vulnerability:
Tumblr media
An Example of a vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.
Conclusion
HTTP Parameter Pollution can be a critical vulnerability if left unchecked in Laravel applications. By implementing proper validation, input handling, middleware sanitation, and secure encoding, you can safeguard your web applications from potential exploits.
🔍 Protect your website now! Use our free tool for a quick website security test and ensure your site is safe from security threats.
For more cybersecurity updates, stay tuned to Pentest Testing Corp. Blog! 🚀
3 notes · View notes
oddevan · 2 years ago
Text
Use Laravel’s Illuminate Database Query Builder With WordPress
I’ve been working on Smolblog, a social web blogging app. To help me get to a minimally viable product sooner, I’ve been building it on top of WordPress. However, WordPress is built exclusively for the MySQL database, and I eventually want Smolblog to work with many different databases, especially SQLite. This means, for my own code, I need to abstract the database away.
The first pass I had at this was to simply have Query objects and services to handle those. This would effectively abstract away the entire data layer, making it completely system-agnostic. It wouldn’t even need to be a traditional database. But as I built this system out, I was making more and more assumptions about what the database and data code would look like. And while the database code was all abstracted away, I still had to write it. A lot of it. And every line I wrote using $wpdb was another line I’d have to rewrite someday.
I’ve been looking at other frameworks to use, and Laravel is by far the strongest contender. Their approach to dependency injection and services seems to line up well with how I’ve organically built Smolblog to this point. So when I found out that their database abstraction layer also included a way to use the library without taking on the entire Laravel framework, I decided to make “someday” today.
Prerequisites
Composer: While you can use this library without using Composer, it’s very much not recommended. That being said, if you’re using this in a plugin for general use or otherwise don’t have control over your entire WordPress environment, be sure to use Mozart or some other tool to isolate the namespaces of your dependencies.
Populated database constants: Some of the more modern WordPress setups use a connection string or other way to connect to MySQL. I didn’t find a way to get that information out of the $wpdb constant, so this code relies on having DB_HOST and other constants from wp-config.php defined.
PDO::MySQL: Illuminate DB uses PDO to handle databases, so you’ll need to make sure your PHP server has the PDO::MySQL extension installed. I’m using the official PHP image, so I needed to add these two lines to my Dockerfile:
RUN docker-php-ext-install pdo_mysql RUN docker-php-ext-enable pdo_mysql
Step 1: Dependency Injection
We’re going to use dependency injection to separate creating the database connection from using the database connection. This way the database connection can change without as much code changing.
The documentation for Laravel’s query builder involves calling their DB facade, a global class that calls a singleton instance. Digging through the documentation and code, it looks like the underlying class conforms to the Illuminate\Database\ConnectionInterface interface. So that’s what we’ll use in our service’s constructor:
use Illuminate\Database\ConnectionInterface; class ContentEventStream implements Listener { public function __construct( private ConnectionInterface $db, ) { } }
Inside the service, we’ll follow the documentation, replacing any use of the DB facade with our $db object:
$this->db->table('content_events')->insert(['column' => 'value']);
Step 2: Connection Factory
Now that we know what we need, we need to create it.
The README for the Illuminate Database package has good starting instructions. We’ll combine those with data from wp-config.php and $wpdb:
use Illuminate\Database\Capsule\Manager; use Illuminate\Database\ConnectionInterface; function getLaravelConnection(): ConnectionInterface { global $wpdb; $capsule = new Manager(); $capsule->addConnection( [ 'driver' => 'mysql', 'host' => DB_HOST, 'database' => DB_NAME, 'username' => DB_USER, 'password' => DB_PASSWORD, 'charset' => DB_CHARSET, 'prefix' => $wpdb->prefix, ] ); return $capsule->getConnection(); }
(As mentioned, we’re pulling the connection information straight from configuration. If you know how to get it from $wpdb, let me know!)
The prefix property on the connection works much the same way as WordPress' table prefix. Since we’re using the connection object to also build our queries, it will add the prefix to our queries automatically. Using this property will also use the correct tables for blogs in multisite, so data from one blog doesn’t leak into another.
For Smolblog, I only want one set of tables regardless of multisite. I also want to prefix the Smolblog-specific tables, mostly so they’re all in one place when I’m scrolling. So my prefix property looks like this:
$capsule->addConnection( [ // ... 'prefix' => $wpdb->base_prefix . 'sb_', ] );
Because I don’t want a global object or the Eloquent ORM, I can ignore the rest of the setup from the project README.
Finally, we’ll want to store this created object somewhere central. Smolblog uses a simple dependency injection container, so we’ll store it there. The first time a service that needs a database connection is created, the container will run this function and provide the object.
(Honestly, the container probably deserves a blog post of its own; you can look at the source code in the meantime.)
Step 3: Update the Schema
We have our code to build queries. We have our connection to the database. The only thing we need now is the actual tables for the database.
Here is where we can use WordPress to its full extent. We will be using the dbDelta function in particular. This will tie into WordPress' existing system for updating the database structure alongside WordPress itself.
Some plugins tie this migration code to an activation hook, but we want to be able to modify the tables even after the plugin is activated. So our process will look like this:
Loop through the different tables we will need.
Check the blog options for a schema version.
If the version matches what we have in code, we’re up-to-date. Skip to the next table.
Pass the new table schema to dbDelta and let it do its thing.
Save the schema version to blog options.
Rinse and repeat for each table.
At this point, I should bring up some of the caveats with the dbDelta function. The comments on the WordPress documentation are invaluable here, especially as they point out a few things that need to be consistent with our schemas.
Because there’s so many things that need to be consistent, we’ll isolate the unique parts of our table schemas to two things:
A name. Because every table needs one. We will declare it without the prefix.
The fields excluding the primary key. We can have UNIQUE indexes on other fields for a similar effect, but every table will have an auto-incrementing id field.
A series of values keyed to short strings? That sounds like an array! Here’s part of what Smolblog’s schema array looks like:
class DatabaseHelper { public const SCHEMA = [ 'content_events' => <<<EOF event_uuid varchar(40) NOT NULL UNIQUE, event_time varchar(30) NOT NULL, content_uuid varchar(40) NOT NULL, site_uuid varchar(40) NOT NULL, user_uuid varchar(40) NOT NULL, event_type varchar(255) NOT NULL, payload text, EOF, 'notes' => <<<EOF content_uuid varchar(40) NOT NULL UNIQUE, markdown text NOT NULL, html text, EOF, ]; public static function update_schema(): void { foreach ( self::SCHEMA as $table => $fields ) { self::table_delta( $table, $fields ); } } //... }
A brief aside: Smolblog uses UUIDs for its unique identifiers, and they’re stored here as full strings in fields ending with _uuid. I ran into trouble storing them as bytes, and something in WordPress would frequently mess with my queries when I had fields named things like user_id and site_id. I’m noting this here in case you run into the same things I did.
When WordPress loads the plugin, it will call the update_schema function declared here. That function loops through the array, extracts the table name and fields, and passes them to this function:
public static function table_delta( string $table, string $fields ): void { global $wpdb; $table_name = $wpdb->base_prefix . 'sb_' . $table; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id bigint(20) NOT NULL AUTO_INCREMENT, $fields PRIMARY KEY (id) ) $charset_collate;"; if ( md5( $sql ) === get_option( $table . '_schemaver', '' ) ) { return; } require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( $sql ); update_option( $table . '_schemaver', md5( $sql ) ); }
This function takes care of the boilerplate we talked about earlier and runs the steps:
It creates the table name using the same pattern as before: the base prefix plus sb_.
It creates a CREATE TABLE SQL statement using the table name and fields. (It’s okay to build a SQL query this way because all of the data is coming from constants inside the PHP file; none of it is coming from form data or other untrusted sources.)
It takes the MD5 hash of the SQL statement and compares that to the saved option for this table. The hash will change when the code changes, so this is a quick way to keep our code and database in-sync.
If the database needs to be updated, it requires the correct file from WordPress Core and runs the dbDelta function.
Finally, it saves the MD5 hash to the blog options so we know what version the database is on.
By calculating the version using the hash of the actual SQL, we don’t have to worry about whether some other version number has been updated. This may or may not be the approach you want to take in a production application, but it has proven very useful in development. This is the same idea as using the filemtime function as the “version number” of static CSS and JavaScript in your theme.
So there we have it. We’ve used the connection information in WordPress to hook up a Laravel database connection. And at some point in the future, it’ll be that much easier to let Smolblog work with SQLite which will in turn let Smolblog work on even more web hosts. And you can use this to do whatever you want! Maybe you just wanted to transfer some skills from Laravel to WordPress. Maybe you’re just in it for the academic challenge.
One thing you can do with this is unit-test your services using an in-memory SQLite database… and I’ll leave you with that.
final class DatabaseServiceUnitTest extends \PHPUnit\Framework\TestCase { private \Illuminate\Database\Connection $db; private DatabaseService $subject; protected function setUp(): void { $manager = new \Illuminate\Database\Capsule\Manager(); $manager->addConnection([ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); $manager->getConnection()->getSchemaBuilder()->create( 'content_events', function(\Illuminate\Database\Schema\Blueprint $table) { $table->uuid('event_uuid')->primary(); $table->dateTimeTz('event_time'); $table->text('payload'); } ); $this->db = $manager->getConnection(); $this->subject = new DatabaseService(db: $this->db); } public function testItPersistsAContentEvent() { $event = new class() extends ContentEvent { public function __construct() { parent::__construct( id: Identifier::fromString('8289a96d-e8c7-4c6a-8d6e-143436c59ec2'), timestamp: new \DateTimeImmutable('2022-02-22 02:02:02+00:00'), ); } public function getPayload(): array { return ['one' => 'two', 'three' => 'four']; } }; $this->subject->onContentEvent($event); $expected = [ 'event_uuid' => '8289a96d-e8c7-4c6a-8d6e-143436c59ec2', 'event_time' => '2022-02-22T02:02:02.000+00:00', 'payload' => '{"one":"two","three":"four"}', ]; $this->assertEquals((object)$expected, $table->first()); $this->assertEquals(1, $table->count()); } }
1 note · View note
laravelvuejs · 6 years ago
Text
Laravel Beginner tutorial | Laravel Facade - simplest explanation - Laravel
Laravel Beginner tutorial | Laravel Facade – simplest explanation – Laravel
Laravel Beginner tutorial | Laravel Facade – simplest explanation – Laravel
[ad_1]
Simplest Explanation of Laravel Facades. Implement your own Facade. What is Laravel Facades.
Full course at https://bitfumes.com/courses/laravel/laravel-for-beginner-from-download-to-deploy
Check https://bitfumes.com For ads free and more advanced courses (use Coupon code WELCOME60 to get 60% discount)
Join Our…
View On WordPress
0 notes
decodewebin · 6 years ago
Text
Json and Laravel Eloquent with example
JSON is short form of JavaScript Object Notation, which is used to store data and since it is very lightweight hence majorly used for transporting data to and from a web server. In earlier days, XML was used for this very purpose but writing and reading XML data was very tedious while JSON on the other hand, is self describing.
In today’s topic I am going to show you how to store JSON data into MySQL and access those data using laravel eloquent query builders.
Storing JSON data in MySQL using Laravel
First let’s create a dummy table using migration command.
Schema::create(json_examples, function (Blueprint $table) {             $table->bigIncrements('id');             $table->string('name');             $table->text('json_details'); //using text datatype to store json             $table->timestamps();         });
As you can see I used text datatype for storing json.
Next, let’s create a corresponding Model for the same
php artisan make:model JsonExample
JsonExample.php
public static function create($data) {     $new = new self();     $new->name = $data['name'];     $new->json_details = $data['json_details''];     $new->save(); }
So in controller we can do something like this:
public function storeEmpData(Request $request) {     ...     $name = $request->name';     $details = ['emp_code' => '001', 'date_of_joining' => Carbon::parse($request->doj), 'salary' => '50000'];         $dataToStore = [         'name' => $name,         'Json_details' => json_encode($details)       ];       //saving data       JsonExample::create($dataToStore); }
Processing Json data in Laravel eloquent.
Json data in where()
We can easily apply conditions on json data in laravel using -> (arrow notation), for example, fetch records where salary is more than 50000.
JsonExample.php
public static function getSalaryMoreThan($salary) {     return self::where('json_details->salary','>',$salary)->get(); }
Access json data using json_extract()
Another example, we need records of employees who joined the company before a date for instance 9th November 2018.
JsonExample.php
public static function getEmployeesBeforeDate($date) {     return self::whereDate("json_extract('json_details', '$.doj')", '<', $date)->get() }
As you can see above, I used json_extract() method which is MySQL’s function to extract a field from JSON column since I can not simply instruct eloquent using arrow operator like
return self::whereDate('json_details->doj', '<', $date)->get()
Rather I have to explicitly tell eloquent to extract json field and then proceed.
JSON data in DB::raw()
Many times we need to use MySQL’s aggregate functions like SUM() as per the requirement, in that case we use DB facade. For example,
select(DB::raw('sum(...)'))
How to access json field in MySQL’s aggregate function ?
It is very simple, let’s take an example, we need to sum total salary of employees.
public static function findTotalSalary() {     return self::select(DB:raw('sum("json_extract('json_details', '$.salary')") as total_salary'))->get(); }
Conclusion
That’s all about this topic friends, I hope you learned something new which you haven’t thought about. I thought I should share this knowledge as I encountered such problem while working on a project today where I do save additional data in json format. Do comment your reviews and experiences below.
Thank you :)
Ebooks available now
You can download this article’s PDF eBooks for offline reading from below:
Issuu
Slide Share
Edocr
AuthorStream
Scribd
4 notes · View notes
laravelnews4u · 6 years ago
Photo
Tumblr media
How A Facade Works in Laravel 5 https://t.co/OBJdKGLiN9 #laravel #php #dev #css3 #html5 #js #coder #code #geek #angularjs #coding #developer #bootstrap #lumen #js #Programming #jquery #ajax #javascript https://t.co/iuGimJGJ4X
2 notes · View notes
shotsloading167 · 4 years ago
Text
Phpstorm Xdebug Laravel
Tumblr media
Phpstorm Xdebug Laravel Tutorial
Phpstorm Xdebug Laravel Artisan Serve
Xdebug Phpstorm Cli
Integrate Xdebug with the PHP interpreter Open the active php.ini file in the editor: In the Settings/Preferences dialog Ctrl+Alt+S, click PHP. On the PHP page that opens, click next to the CLI Interpreter field. I have a AngularJS + Laravel application and not able to setup debugging. On project root folder I have a PHP file and the debugger breaks at this file always. I use PHPStorm and have unchecked the '.
Features
Lots of PHP developers create their applications using Laravel, a free, open source PHP web application framework. It is built on top of several Symfony components, and provides a development framework that makes common tasks such as authentication, routing, sessions and caching much easier to implement.
Last summer, we introduced support for Blade, the template language used by Laravel. Recoverit download mac. Support for artisan, the command line tool for Laravel developers, is baked into PhpStorm as well. Using the Laravel plugin and the Laravel IDE helper, we can further extend PhpStorm’s support for Laravel applications. Let’s see how!
The Laravel IDE Helper
After making sure Composer is available for use in our project, we can install the Laravel IDE helper into our project using the Composer | Add dependency… context menu. We can search for barryvdh/laravel-ide-helper and click Install to download the package and add it to our project.
After registering the ‘BarryvdhLaravelIdeHelperIdeHelperServiceProvider’service provider in our application and running artisan ide-helper:generate, PhpStorm will have code completion support and syntax highlighting for many of Laravel’s facades.
The Laravel Plugin for PhpStorm
To further enhance the Laravel experience, we can also install the Laravel Plugin. Under Settings (Preferences) | Plugins, click the Browse repositories… button and search for Laravel. The Install plugin button will download and install the plugin into our IDE.
Restart the IDE and enable the plugin under Settings (Preferences) | Other Settings | Laravel Plugin | Enable Plugin for this Project. All of a sudden, PhpStorm will know what all Laravel facades do, and provide code completion for controllers, views, routes, configuration, translations and many other things!
There’s not only code completion… We can navigate to these items as well! Using Ctrl+Click (CMD+Click on Mac OS X) or Go To Declaration (Ctrl+B / CMD+B), PhpStorm will navigate us to where, for example, a configuration entry is declared.
Working in Blade templates? The Laravel plugin also enhances that experience, for example with code completion for @section directives.
Anxious to learn more? Check our Laravel tutorial, which covers getting PhpStorm ready for Laravel development, code completion, navigation, automatic code inspections, command line tool support, debugging and unit testing!
Are you a Laravel developer? Give PhpStorm 8 a try! We have an elaborate tutorial on Laravel support in PhpStorm which will help you get the most out of our IDE. Your feedback is very welcome through the issue tracker, by posting in the comments below, or in our forums!
Develop with pleasure! – JetBrains PhpStorm Team
Stef Rouschop
min read
TLDR;
This guide will make you install Xdebug on your Mac without the performance downsides, but still being able to use all the Xdebug goodnesses. Most Xdebug setups only allow you to use it through a web browser plugin. This is not helpful when you’re following a TDD approach. So we’ll get it to work right from your tests in PhpStorm, no browser needed!
Having tests is awesome!
I’m a huge fan of tests in Laravel and try to develop as much as possible using the TDD approach. When a project grows over the years, your tests are becoming like a guard that will tell when you messed up functionality by adding or changing some code later on. This gives a peace of mind and has saved my bacon many times already.
PhpStorm has a great GUI for running PHPUnit tests where you’re able to click directly on the links to the scripts where a test fails. I love this workflow and I’ve never used phpunit on the command line since. Praat phonetics. However, when your tests fail, it can become somewhat cumbersome to figure out what is going on. The first thing I always do is add ->dump() to the request, that will point me in the right direction most of the time. But there are cases where you really need to dig into the code. This is where I previously placed some dd() in the code and then tried to follow the steps. Raise your hand if you’ve been there 🤚!
Xdebug is a wonderful tool that can help you with that, but I previously used it a long time ago with a browser plugin. Since PHPUnit gets really slow when Xdebug is installed and it also impacts the composer performance, I removed it from my system and never used it since. Until I recently discovered “on-demand Xdebug” in PhpStorm! This will not enable Xdebug by default, and will only use it when you need to.It’s really simple to set up and I love using it! You can also use it directly in your tests, so you don’t have to recreate the situation in your browser. I’ll show you how to install and use it in this article.
Install
In our company we only use Mac’s, I have no idea how to set this up on Windows, so you’ll have to google around if that’s your case. For Linux, it will more or less be the same (except for PHP installation) I think.
I’m assuming you’ve been using Homebrew to install the latest version of PHP. It’s as simple as brew install php.
Extensions as Xdebug have recently been removed from Homebrew and need to be installed using PECL. Luckily that is also really easy!pecl install xdebugThe install will add a reference to Xdebug in your php.ini file so it will be loaded by default. We don’t want that! So we’ll remove this reference. Here’s how to do it:On your command line enter: php --ini this will give you the path of the php.ini file that is used on your system.
Open the file in an editor of your choice, or use the default editor for this filetype. In the case of our example, we can do this with the command open /usr/local/etc/php/7.2/php.ini. This will open the php.ini file. We can see the reference added by the Xdebug installer on line 1: zend_extension=”xdebug.so”. We need to remove this line so Xdebug is not loaded by default anymore. Twitch deere. There, all done 🥳!
Tumblr media
PhpStorm setup
I’ll assume you have a setup for your TDD workflow in PhpStorm. The purpose of this guide is only to extend it with Xdebug. If you don’t have it, here is an old but still relevant video from Laracasts.com: Be Awesome in PHPStorm: Testing in PHPStorm.
We will need to tell PhpStorm where Xdebug is located for using it on demand. In the settings navigate to Languages and Frameworks and then PHP. On the CLI Interpreter click on the … button like in the screenshot.
Now we can specify where Xdebug is located on your system. In our example this is in /usr/local/lib/php/pecl/20170718/xdebug.so, but this path depends on the version and can be different on your system. So be sure to click on the folder icon to navigate through your system and find it.
When the path is correct and you hit the refresh button, you will see the Xdebug version that was found by PhpStorm.
Using it
Phpstorm Xdebug Laravel Tutorial
For sake of simplicity, we’ll create a simple test where we assert the content of two routes. The routes we’re about to test will just return some variables, nothing fancy going on here, you’ll get the idea. Laravel makes creating tests really easy with the artisan helper php artisan make:test TwoRoutesTest.
In the image below you can see how the tests are run when you’ll hit the green “play” button, nothing new here. Did you also know about the SHIFT + CTRL + R shortcut? Place your cursor in a test and hit the shortcut and only this single test will run. When you place the cursor outside of a test, all the tests of this test-file will run. I really love this shortcut 😍!
Now, let's use Xdebug!
Phpstorm Xdebug Laravel Artisan Serve
Go to your code and place some breakpoints on the left side of the lines. They will be marked with red circles when you click them. This time, don��t click the green “play” button, but the red bug on the right side of it.
Xdebug Phpstorm Cli
The test will stop on the first breakpoint. You’ll get a nice overview of all (global) variables in the debug screen. When you press the green “play / pause” button on the left side of the screen you’ll go to the next breakpoint. You can really dig in the code now to figure out where your bugs happen. I won’t go into detail about all the PhpStorm/Xdebug functionality. That might be a completely different blog post.
Happy debugging
I hope this will enhance your debugging workflow as much as it did for me!
Tumblr media
0 notes
pentesttestingcorp · 4 months ago
Text
Preventing LDAP Injection Vulnerabilities in Laravel
Introduction
In today’s cybersecurity landscape, web applications are frequently targeted by malicious actors using various injection techniques. One of the most dangerous is LDAP injection, which can allow attackers to manipulate Lightweight Directory Access Protocol (LDAP) queries, potentially compromising sensitive data. If you are developing applications with Laravel, it’s essential to be aware of this vulnerability and implement the necessary safeguards.
Tumblr media
In this blog post, we will discuss what LDAP injection is, how to prevent it in Laravel applications, and how our free tool can help to check website vulnerability and secure your website.
What is LDAP Injection?
LDAP injection is a form of attack where the attacker injects malicious code into an LDAP query to manipulate the results returned by the server. The attack typically occurs when user input is improperly sanitized, allowing the attacker to alter the structure of the LDAP query.
For example, consider an authentication mechanism where the user submits a username and password. If the input is not sanitized, an attacker could manipulate the query to authenticate as any user.
How LDAP Injection Works
Here’s a simple example of an LDAP query in Laravel that could be vulnerable to injection:
$ldapConnection = ldap_connect("ldap://localhost"); $dn = "uid=$username,dc=example,dc=com"; $filter = "(uid=$username)"; $search = ldap_search($ldapConnection, $dn, $filter);
If an attacker provides input like admin)(&(|(password=password, the $filter string will become:
$filter = "(uid=admin)(&(|(password=password)";
This could result in unintended behavior, such as returning all records in the LDAP database.
How to Prevent LDAP Injection in Laravel
To secure your Laravel application against LDAP injection, you should follow these best practices:
Sanitize User Input: Always sanitize user input before passing it to LDAP queries. You can use Laravel’s built-in validation and sanitization features.
Use Prepared Statements: Prepared statements ensure that the user input is treated as data rather than executable code. Laravel’s query builder and Eloquent ORM can help mitigate these risks in other contexts, but for LDAP, it’s essential to sanitize properly.
Limit User Input Length: Restrict the length of input fields like usernames and passwords to prevent overflows or other attack vectors.
Use Strong Authentication: Implement multi-factor authentication (MFA) to add an additional layer of security, even if LDAP injection is successful.
Monitor Logs for Unusual Activity: Regularly check the logs for any suspicious activity related to LDAP queries, such as unexpected characters or patterns in the username.
Example: Secure LDAP Query in Laravel
Below is an example of a more secure way to handle LDAP queries in Laravel using proper input validation:
use Illuminate\Support\Facades\Validator; public function authenticate(Request $request) { $validator = Validator::make($request->all(), [ 'username' => 'required|string|max:255', 'password' => 'required|string|min:8', ]); if ($validator->fails()) { return response()->json(['error' => 'Invalid input'], 400); } $username = htmlspecialchars($request->input('username')); $password = $request->input('password'); $ldapConnection = ldap_connect("ldap://localhost"); $dn = "uid=$username,dc=example,dc=com"; $filter = "(uid=" . ldap_escape($username, "", LDAP_ESCAPE_FILTER) . ")"; $search = ldap_search($ldapConnection, $dn, $filter); // Further LDAP authentication code }
In this example, we use htmlspecialchars() to sanitize the username and ldap_escape() to ensure the username is properly encoded before being included in the LDAP query.
How Our Free Tool Can Help
To help identify LDAP injection vulnerabilities in your website, we have a Free Website Security Scanner. Our tool performs a detailed security audit and can detect potential LDAP injection vulnerabilities, along with other common issues like SQL injection, cross-site scripting (XSS), and more.
Here’s a screenshot of the tool in action:
Tumblr media
Screenshot of the free tools webpage where you can access security assessment tools.
Vulnerability Assessment Report
After scanning your website with our tool for a website security test, you’ll receive a detailed vulnerability assessment report. This will include findings on LDAP injection risks, along with suggestions for remediation. Here’s a sample report:
Tumblr media
An Example of a vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.
Conclusion
LDAP injection can be a significant threat to your Laravel applications if left unaddressed. By understanding how the attack works and implementing secure coding practices, you can protect your applications from this dangerous vulnerability. Additionally, our free Website Security Checker can help you identify and resolve LDAP injection issues, ensuring your website stays secure.
For more detailed cybersecurity insights and best practices, visit our blog at Pentest Testing Corp Blog.
1 note · View note
scriptsouffle · 4 years ago
Text
Facades or Helpers?
In Laravel code we often use helpers and facades interchangably and many of the facades that are used most in Laravel are also available as Facades
eg.
view('order.show'); view::make('order.show');
This is so prevalent, that I thought that helpers were part of Facades so when I went to create my own facade I couldnt understand why the helper function didnt work.
Slowly it dawned on me this was not the case and what I really needed was a facade and a helper function.
I found this very helpful article on Laravel news
https://laravel-news.com/creating-helpers
This explains very simply what helper functions are, where and how your crate them and how you autoload them.
Now I have a facade and a helper function and I'm happy.
0 notes
t-baba · 8 years ago
Photo
Tumblr media
Gates and Policies in Laravel
Today, we're going to discuss the authorization system of the Laravel web framework. The Laravel framework implements authorization in the form of gates and policies. After an introduction to gates and policies, I'll demonstrate the concepts by implementing a custom example.
I assume that you're already aware of the built-in Laravel authentication system as that's something essential in order to understand the concept of authorization. Obviously, the authorization system works in conjunction with the authentication system in order to identify the legitimate user session.
If you're not aware of the Laravel authentication system, I would highly recommend going through the official documentation, which provides you with hands-on insight into the subject.
Laravel's Approach to Authorization
By now, you should already know that the Laravel authorization system comes in two flavors—gates and policies. Although it may sound like a complicated affair, I would say it's pretty easy to implement it once you get the hang of it!
Gates allow you to define an authorization rule using a simple closure-based approach. In other words, when you want to authorize an action that's not related to any specific model, the gate is the perfect place to implement that logic.
Let's have a quick look at what gate-based authorization looks like:
... ... Gate::define('update-post', function ($user, $post) { return $user->id == $post->user_id; }); ... ...
The above snippet defines the authorization rule update-post that you could call from anywhere in your application.
On the other hand, you should use policies when you want to group the authorization logic of any model. For example, let's say you have a Post model in your application, and you want to authorize the CRUD actions of that model. In that case, it's the policy that you need to implement.
class PostPolicy { public function view(User $user, Post $post) {} public function create(User $user) {} public function update(User $user, Post $post) {} public function delete(User $user, Post $post) {} }
As you can see, it's a pretty simple policy class that defines the authorization for the CRUD actions of the Post model.
So that was an introduction to gates and policies in Laravel. From the next section onwards, we'll go through a practical demonstration of each element.
Gates
In this section, we'll see a real-world example to understand the concept of gates.
More often than not, you end up looking at the Laravel service provider when you need to register a component or a service. Following that convention, let's go ahead and define our custom gate in the app/Providers/AuthServiceProvider.php as shown in the following snippet.
<?php namespace App\Providers; use Illuminate\Support\Facades\Gate; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Http\Request; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ 'App\Model' => 'App\Policies\ModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Gate::define('update-post', function ($user, $post) { return $user->id == $post->user_id; }); } }
In the boot method, we've defined our custom gate:
Gate::define('update-post', function ($user, $post) { return $user->id == $post->user_id; });
While defining a gate, it takes a closure that returns either TRUE or FALSE based on the authorization logic that's defined in the gate definition. Apart from the closure function, there are other ways you could define gates.
For example, the following gate definition calls the controller action instead of the closure function.
Gate::define('update-post', 'ControllerName@MethodName');
Now, let's go ahead and add a custom route so that we can go through a demonstration of how gate-based authorization works. In the routes file routes/web.php, let's add the following route.
Route::get('service/post/gate', 'PostController@gate');
Let's create an associated controller file app/Http/Controllers/PostController.php as well.
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Post; use Illuminate\Support\Facades\Gate; class PostController extends Controller { /* Make sure you don't user Gate and Policy altogether for the same Model/Resource */ public function gate() { $post = Post::find(1); if (Gate::allows('update-post', $post)) { echo 'Allowed'; } else { echo 'Not Allowed'; } exit; } }
In most cases, you'll end up using either the allows or denies method of the Gate facade to authorize a certain action. In our example above, we've used the allows method to check if the current user is able to perform the update-post action.
Users with sharp eyes would have noticed that we've only passed the second argument $post to the closure. The first argument, the current logged-in user, is automatically injected by the Gate facade.
So that's how you're supposed to use gates to authorize actions in your Laravel application. The next section is all about how to use policies, should you wish to implement authorization for your models.
Policies
As we discussed earlier, when you want to logically group your authorization actions for any particular model or resource, it's the policy you're looking for.
In this section, we'll create a policy for the Post model that will be used to authorize all the CRUD actions. I assume that you've already implemented the Post model in your application; otherwise, something similar will do.
The Laravel artisan command is your best friend when it comes to creating stubbed code. You can use the following artisan command to create a policy for the Post model.
$php artisan make:policy PostPolicy --model=Post
As you can see, we've supplied the --model=Post argument so that it creates all the CRUD methods. In the absence of that, it'll create a blank Policy class. You can locate the newly created Policy class at app/Policies/PostPolicy.php.
Let's replace it with the following code.
<?php namespace App\Policies; use App\User; use App\Post; use Illuminate\Auth\Access\HandlesAuthorization; class PostPolicy { use HandlesAuthorization; /** * Determine whether the user can view the post. * * @param \App\User $user * @param \App\Post $post * @return mixed */ public function view(User $user, Post $post) { return TRUE; } /** * Determine whether the user can create posts. * * @param \App\User $user * @return mixed */ public function create(User $user) { return $user->id > 0; } /** * Determine whether the user can update the post. * * @param \App\User $user * @param \App\Post $post * @return mixed */ public function update(User $user, Post $post) { return $user->id == $post->user_id; } /** * Determine whether the user can delete the post. * * @param \App\User $user * @param \App\Post $post * @return mixed */ public function delete(User $user, Post $post) { return $user->id == $post->user_id; } }
To be able to use our Policy class, we need to register it using the Laravel service provider as shown in the following snippet.
<?php namespace App\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Http\Request; use App\Post; use App\Policies\PostPolicy; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ 'App\Model' => 'App\Policies\ModelPolicy', Post::class => PostPolicy::class ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); } }
We've added the mapping of our Policy in the $policies property. It tells Laravel to call the corresponding policy method to authorize the CRUD action.
You also need to register the policies using the registerPolicies method, as we've done in the boot method.
Moving further, let's create a couple of custom routes in the routes/web.php file so that we can test our Policy methods there.
Route::get('service/post/view', 'PostController@view'); Route::get('service/post/create', 'PostController@create'); Route::get('service/post/update', 'PostController@update'); Route::get('service/post/delete', 'PostController@delete');
Finally, let's create an associated controller at app/Http/Controllers/PostController.php.
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Post; use Illuminate\Support\Facades\Auth; class PostController extends Controller { public function view() { // get current logged in user $user = Auth::user(); // load post $post = Post::find(1); if ($user->can('view', $post)) { echo "Current logged in user is allowed to update the Post: {$post->id}"; } else { echo 'Not Authorized.'; } } public function create() { // get current logged in user $user = Auth::user(); if ($user->can('create', Post::class)) { echo 'Current logged in user is allowed to create new posts.'; } else { echo 'Not Authorized'; } exit; } public function update() { // get current logged in user $user = Auth::user(); // load post $post = Post::find(1); if ($user->can('update', $post)) { echo "Current logged in user is allowed to update the Post: {$post->id}"; } else { echo 'Not Authorized.'; } } public function delete() { // get current logged in user $user = Auth::user(); // load post $post = Post::find(1); if ($user->can('delete', $post)) { echo "Current logged in user is allowed to delete the Post: {$post->id}"; } else { echo 'Not Authorized.'; } } }
There are different ways you could authorize your actions using Policies. In our example above, we’ve used the User model to authorize our Post model actions.
The User model provides two useful methods for authorization purposes—can and cant. The can method is used to check if the current user is able to execute a certain action. And the counterpart of the can method, the cant method, is used to determine the inability of the action execution.
Let’s grab the snippet of the view method from the controller to see what exactly it does.
public function view() { // get current logged in user $user = Auth::user(); // load post $post = Post::find(1); if ($user->can('view', $post)) { echo "Current logged in user is allowed to update the Post: {$post->id}"; } else { echo 'Not Authorized.'; } }
Firstly, we load the currently logged-in user, which gives us the object of the User model. Next, we load an example post using the Post model.
Moving ahead, we’ve used the can method of the User model to authorize the view action of the Post model. The first argument of the can method is the action name that you want to authorize, and the second argument is the model object that you want to get authorized against.
That was a demonstration of how to use the User model to authorize the actions using policies. Alternatively, you could use the Controller Helper as well, if you’re in the controller while authorizing a certain action.
… $this->authorize('view', $post); …
As you can see, you don’t need to load the User model if you use the Controller Helper.
So that was the concept of policies at your disposal, and it’s really handy while authorizing a model or a resource as it allows you to group the authorization logic in one place.
Just make sure that you don’t use gates and policies altogether for the same actions of the Model, otherwise it’ll create issues. That’s it from my side for today, and I’ll call it a day!
Conclusion
Today, it was Laravel authorization that took the center stage in my article. At the beginning of the article, I introduced the main elements of Laravel authorization, gates and policies.
Following that, we went through creating our custom gate and policy to see how it works in the real world. I hope you’ve enjoyed the article and learned something useful in the context of Laravel.
For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study on Envato Market.
As always, I would love to hear from you in the form of comments using the feed below!
by Sajal Soni via Envato Tuts+ Code http://ift.tt/2iWGhkh
1 note · View note
viralleakszone-blog · 6 years ago
Text
Yii Tutorial
http://www.viralleakszone.com/yii-tutorial/
Yii Tutorial
Yii Tutorial
Yii Tutorial for Beginners - Learn Yii in simple and easy steps starting from basic 
to advanced concepts with examples including Overview, Installation, Create Page, 
Application Structure, Entry Scripts, Controllers, Using Controllers, Using Actions,
 Models, Widgets, Modules, Views, Layouts, Assets, Asset Conversion, Extensions, 
Creating Extensions, HTTP Requests, Responses, URL Formats, URL Routing, Rules of 
URL, HTML Forms, Ad Hoc and AJAX Validations, Sessions, Using Flash Data, Cookies, 
Using Cookies, Files Upload, Formatting, Pagination, Sorting, Properties, 
Data Providers, Data Widgets, ListView Widgets, GridView Widgets, Events, 
Creating Event, Behaviors, Creating a Behavior, Configurations, Dependency 
Injection, Database Access, Data Access Objects, Query Builder, Active Record, 
Database Migration, Theming, RESTful APIs, RESTful APIs in Action, Fields, 
Testing, Caching, Fragment Caching, Aliases, Logging, Error Handling, 
Authentication, Authorization, Localization, Gii, Creating a Model, Generating 
Controller and Module.
Laravel
Laravel Tutorial
Laravel is a powerful MVC PHP framework, designed for developers who need a simple and elegant toolk
Laravel – Overview
IntroductionLaravel is an open-source PHP framework, which is robust and easy to understand. It foll
Laravel – Installation
For managing dependencies, Laravel uses composer. Make sure you have a Composer installed on yo
Laravel – Application Structure
The application structure in Laravel is basically the structure of folders, sub-folders and files in
Laravel – Configuration
In the previous chapter, we have seen that the basic configuration files of Laravel are included in
Laravel – Routing
In Laravel, all requests are mapped with the help of routes. Basic routing routes the request to the
Laravel – Middleware
Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism. T
Laravel – Namespaces
Namespaces are used in various programming languages to create a separate group of variable, functio
Laravel – Controllers
In the MVC framework, the letter ‘C’ stands for Controller. It acts as a directing traffic between V
Laravel – Request
In this chapter, you will learn in detail about Requests in Laravel.Retrieving the Request URIThe&nb
Laravel – Cookie
Cookies play an important role while dealing a user’s session on a web application. In this chapter,
Laravel – Response
A web application responds to a user’s request in many ways depending on many parameters. This chapt
Laravel – Views
In MVC framework, the letter V stands for Views. It separates the application logic a
Laravel – Blade Templates
Laravel 5.1 introduces the concept of using Blade, a templating engine to design a unique layou
Laravel – Redirections
Named route is used to give specific name to a route. The name can be assigned using the as&nbs
Laravel – Working With Database
Laravel has made processing with database very easy. Laravel currently supports following 4 database
Laravel – Errors and Logging
This chapter deals with errors and logging in Laravel projects and how to work on them.ErrorsA proje
Laravel – Forms
Laravel provides various in built tags to handle HTML forms easily and securely. All the major eleme
Laravel – Localization
Localization feature of Laravel supports different language to be used in application. You need to s
Laravel – Session
Sessions are used to store information about the user across the requests. Laravel provides various
Laravel – Validation
Validation is the most important aspect while designing an application. It validates the incoming da
Laravel – File Uploading
Uploading Files in Laravel is very easy. All we need to do is to create a view file where a user can
Laravel – Sending Email
Laravel uses free feature-rich library SwiftMailer to send emails. Using the library funct
Laravel – Ajax
Ajax (Asynchronous JavaScript and XML) is a set of web development techniques utilizing many we
Laravel – Error Handling
Most web applications have specific mechanisms for error handling. Using these, they track errors an
Laravel – Event Handling
Events provide a simple observer implementation which allows a user to subscribe and listen to vario
Laravel – Facades
Facades provide a static interface to classes that are available in the application’s serv
Laravel – Contracts
Laravel contracts are a set of interfaces with various functionalities and core services provided by
Laravel – CSRF Protection
CSRF refers to Cross Site Forgery attacks on web applications. CSRF attacks are the unauthorized act
Laravel – Authentication
Authentication is the process of identifying the user credentials. In web applications, authenticati
Laravel – Authorization
In the previous chapter, we have studied about authentication process in Laravel. This chapter expla
Laravel – Artisan Console
Laravel framework provides three primary tools for interaction through command-line namely: Art
Laravel – Encryption
Encryption is a process of converting a plain text to a message using some algorithms such that any
Laravel – Hashing
Hashing is the process of transforming a string of characters into a shorter fixed value or a key th
Laravel – Understanding Release Process
Every web application framework has its own version history and it is always being updated and maint
Laravel – Useful Resources
The following resources contain additional information on Laravel. Please use them to get more in-de
Discuss Laravel
Laravel is a powerful MVC PHP framework, designed for developers who need a simple and elegant toolk
Laravel Security
Security is important feature while designing web applications. It assures the users of the websit
0 notes
programmingbiters-blog · 7 years ago
Photo
Tumblr media
New Post has been published on https://programmingbiters.com/file-uploads-with-laravel-5-and-dropzone-drag-and-drop/
File Uploads with Laravel 5 and Dropzone drag and drop
File uploads with Laravel is incredibly easy, thanks to the powerful file systemabstraction that it comes bundled with. Couple that up with Dropzone’s drag and drop feature, and you have a robust file upload mechanism. Not only these are easy to implement, they provide a great number of features in very few lines of code.
# Setting up the uploads
We’ll create a database table that contains information about each of the uploads. Of course we are not going to store our file in the database itself, rather we’d store only some metadata of the file. So let’s create a schema.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public function up()
             Schema::create(‘uploads’, function (Blueprint $table)
            $table->increments(‘id’);
            $table->integer(‘user_id’)->unsigned()->index();
            $table->string(‘filename’);
            $table->bigInteger(‘size’);
            $table->softDeletes();
            $table->timestamps();
            $table->foreign(‘user_id’)->references(‘id’)->on(‘users’)->onDelete(‘cascade’);
        );
     Here only metadata we are storing are  filename  and size . filename  would be used to store and retrieve the file later. We add a foreign keyuser_id  to keep track of who uploaded the file. This can also be used to check the owner of a file. We are also going to use  SoftDeletes  to mark a file as deleted rather than actually delete the file from storage, when a user deletes a file.
Now, let’s  php artisan make:model Upload  to create a Upload  model for this table.
Next, we define the relationship between a user and an uploaded file – a user may upload many files and each uploaded file will belong to a user. Therefore, let’s define a one-to-many relationship in our User  and Upload  models.  In theUser model:
1
2
3
4
5
6
public function uploads()
    return $this->hasMany(Upload::class);
and the inverse relationship is defined in our Upload model:
1
2
3
4
5
6
public function user()
return $this->belongsTo(User::class);
Also while we are at it, let’s update the fillable  columns for our Upload  model.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use Illuminate\Database\Eloquent\SoftDeletes;
use App\User;
class Upload extends Model
    use SoftDeletes;
    protected $fillable = [
        ‘filename’, ‘size’,
    ];
    public function user()
          return $this->belongsTo(User::class);
     That’s all! Our Upload  model is now ready.
# Setting up dropzone
Now that our uploads backend is ready, let’s setup dropzone for drag and drop file uploads.
First we need to install dropzone, so let’s do a npm install dropzone —save . Next, we need to load the dropzone library. Since we are going to use Laravel Mix to compile our frontend assets, we can load the library withinresources/assets/js/bootstrap.js :
1
2
3
4
5
6
// Dropzone
window.Dropzone = require(‘dropzone’);
Dropzone.autoDiscover = false;
This will set Dropzone  to the window object. We are disabling the autoDiscover  option, which is used to automatically attach dropzone with any file input, which we do not need.
Now let’s add the styling for this (otherwise it’s going to look uglier than Voldemort’s face, trust me). We can do this in ourresources/assets/sass/app.scss .
1
2
3
4
5
6
7
8
@import “~dropzone/src/dropzone.scss”;
.dropzone
margin-bottom: 20px;
min-height: auto;
All set. So we can now compile the assets using npm run dev .
# Setting up routes
Before we start uploading any files, we need to define some routes. Here we’d create two routes, one for receiving the uploads and one for deleting the uploads, should a user choose to delete one.
1
2
3
4
5
Route::post(‘/upload’, ‘UploadController@store’)->name(‘upload.store’);
Route::delete(‘/upload/upload’, ‘UploadController@destroy’);
Let’s php artisan make:controller UploadController  to create the controller. We will use this UploadController  to process the uploads in the backend.
# Uploading files
Now that we have pulled in dropzone and attached it to the window object, we need to integrate dropzone within a view to start file uploads. We can simple do this using an id  tag.
1
2
3
<div id=“file” class=“dropzone”></div>
class=“dropzone”  is used to style the dopzone upload box. We can use the#file  to inject dropzone on this element. (tip: it is a best practice in laravel to create javascript snippets in separate partials and then including them in whichever blade template they are needed)
1
2
3
4
5
6
7
8
9
let drop = new Dropzone(‘#file’,
    addRemoveLinks: true,
    url: ‘ route(‘upload.store‘) ’,
    headers:
        ‘X-CSRF-TOKEN’: document.head.querySelector(‘meta[name=”csrf-token”]’).content
     );
We are instantiating the Dropzone  class on our #file and then passing in some addition configuration. addRemoveLinks  will add a remove link to every uploaded file, so a user can remove a file after uploading it. The url option is used to let dropzone know where to post the uploaded file to, in case we are not using a form. If we are using a form, by default dropzone would use the action attribute of the form as the post url (I’m not quite sure about this though, so please don’t take my words as is, and do correct me if I am wrong). We are using the upload.store  route which we have defined earlier.
headers are used to send additional headers to the server. Because we are posting our uploads, we need to send a  X–CSRF–TOKEN  header, otherwise our app will throw a  TokenMismatchException (this is used by laravel to protect our app against CSRF attacks). By default, the meta information in head contains a meta with the name  csrf–token . Therefore we select the meta and extract the content which gives us the token .
Dropzone provide’s a huge number of configuration options. Check out the documentation for all the available options. (Also don’t forget to thank the developer of dropzone )
Now that we are able to post files from the frontend, let’s work on our controller to receive and process the uploads on backend.
In the UploadController , let’s define a method storeUploadedFile() which receives a Illuminate\Http\UploadedFile and store all the metadata in our database.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protected function storeUploadedFile(UploadedFile $uploadedFile)
    $upload = new Upload;
    $upload->fill([
        ‘filename’ => $uploadedFile->getClientOriginalName(),
        ‘size’ => $uploadedFile->getSize(),
    ]);
    $upload->user()->associate(auth()->user());
    $upload->save();
    return $upload;
getClientOriginalName() gives us the original name of the file that has been uploaded. getSize() returns the size of the uploaded file in bytes. We thenassociate()  the upload with the currently logged in user. Finally we save the file and return the model instance.
In the  store() method, we accept a Request and then from that request, we extract the file.
1
2
3
4
5
6
public function store(Request $request)
    $uploadedFile = $request->file(‘file’);
We are going to store this file in our local filesystem. Of course you can upload it to Amazon S3 or any other cloud storage services and laravel provides an excellent documentation on how to configure different storage services. However, I’m going to store the uploads on our local disk only.
Next we need to save the file metadata like name, size and the user who uploaded it to our database. For this, we can use thestoreUploadedFile() method we implemented above.
1
2
3
$upload = $this->storeUploadedFile($uploadedFile);
This returns us an instance of the Upload model. We can now use this to store the file.
1
2
3
4
5
6
7
Storage::disk(‘local’)->putFileAs(
    ‘uploads/’ . $request->user()->id,
    $uploadedFile,
    $upload->filename
);
The Storage facade is used to interact with the disk in which we are going to store the file. Storage::disk(‘local’)  gives us an instance of the local disk. The default local storage root is storage/app .
putFileAs() method is used to automatically stream a given file to a storage location. The first argument ‘uploads/’ . $request->user()->id is the upload path. We are creating a new directory uploads and within that directory creating another directory using user’s id  and storing the file there, so that all files uploaded by a user goes to the same location. For example, if a user’s id is 7, any file he uploads will be stored at storage/app/uploads/7/ .
The second argument in putAsFile() method is theIlluminate\Http\UploadedFile instance and the last argument is the filename that will be used to store the file. Because at this point, we already have stored the file’s metadata in our database, we can simply get the name of the file by  $upload->filename .
At this point, file storing is complete. Finally we send back a JSON  response with the uploaded file’s id.
1
2
3
4
5
return response()->json([
    ‘id’ => $upload->id
]);
That’s all. The file has been stored on our local disk.
# Deleting files
To remove a file, Dropzone provides a removedfile event, which we can listen to and then send a delete request. We will use axios to send the request.
We can register to any dropzone event by calling .on(eventName,callbackFunction) on our dropzone instance. Check this documentation for a list of different dropzone events and when they are triggered.
Now we need to use the id of the uploaded file in order to send the delete request. But from the frontend how could we possibly know what’s the id of a uploaded file? Well, this is where the JSON response from thestore() method is useful. When we uploaded a file successfully, we are sending back the id of the file from the backend. On a successful upload, we can therefore associate this id  with the file on the frontend.
1
2
3
4
5
drop.on(‘success’, function(file, response)
file.id = response.id;
);
When a file has been uploaded successfully, dropzone triggers a success  event. We can register to this event to get the file instance and theresponse from the backend inside the callback function. We simple assign theresponse.id to file.id . Therefore, for every file that we have successfully uploaded, now we have an identifier associated with it to be used on the frontend. Great!
Now that we have an id associated with each file, deleting files is easy. We listen for removedfile  event and then use axios from the global window object to fire a delete request to the backend.
1
2
3
4
5
6
7
8
9
10
11
drop.on(‘removedfile’, function(file)
axios.delete(‘/upload/’ + file.id).catch(function(error)
drop.emit(‘addedfile’,
id: file.id,
name: file.name,
size: file.size,
);
);
);
Notice how we are chaining the catch() method. This to catch any error when removing a file. If an error occurs that prevented the file deletion, we want to add it back so that the user knows the deletion failed and they may try again. We do that simply by calling the emit() method and passing in the details of the file. This will call the default addedfile event handler and add the file back.
Okay. So our frontend is ready to delete files. Let’s start working on thedestroy()  controller method.
Because we are injecting the file id on our delete request, we can therefore accept the file we trying to delete , destroy(Upload $upload) , using  laravel’s route model binding.   The next thing we need to do is verify if the delete request is actually coming from the owner of the file. Let’s create a policy,UploadPolicy  for that.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
use App\User, Upload;
use Illuminate\Auth\Access\HandlesAuthorization;
class UploadPolicy
    use HandlesAuthorization;
    public function touch(User $user, Upload $upload)
             return $user->id === $upload->user_id;
     In the touch()  method, we are checking if the ids of the user who uploaded it and the user who is sending the delete request is same. In our destroy()  method, we can now use this touch()  method to authorize the request.
1
2
3
$this->authorize(‘touch’, $upload);
Finally we can delete the file.
1
2
3
4
5
6
7
8
public function destroy(Upload $upload)
$this->authorize(‘touch’, $upload);
$upload->delete();
Since we are using SoftDeletes , this will mark the file as deleted in the database.
That’s all folks.
The complete UploadController looks like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
namespace App\Http\Controllers;
use Storage;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use App\Upload;
class UploadController extends Controller
    public function __construct()
             $this->middleware(‘auth’);
         public function store(Request $request)
          $uploadedFile = $request->file(‘file’);
        $upload = $this->storeUploadedFile($uploadedFile);
        Storage::disk(‘local’)->putFileAs(
            ‘uploads/’ . $request->user()->id,
            $uploadedFile,
            $upload->filename
        );
        return response()->json([
            ‘id’ => $upload->id
        ]);
         public function destroy(Upload $upload)
             $this->authorize(‘touch’, $upload);
        $upload->delete();
         protected function storeUploadedFile(UploadedFile $uploadedFile)
             $upload = new Upload;
        $upload->fill([
            ‘filename’ => $uploadedFile->getClientOriginalName(),
            ‘size’ => $uploadedFile->getSize(),
        ]);
        $upload->user()->associate(auth()->user());
        $upload->save();
        return $upload;
       # Conclusion
There can be so many different ways of implementing file uploads. Dropzone’s documentation includes an example section that have quite a few in-depth excellent examples. Don’t forget to check that out!
0 notes
mbaljeetsingh · 7 years ago
Text
How to Send Emails in Laravel
In this article, we're going to explore the Mail API in the Laravel web framework. Laravel takes advantage of the popular SwiftMailer library, which is easy to use and comes with a variety of email drivers to choose from. In the latter stages of the article, we'll go through an in-depth demonstration of the concepts discussed in the first half of the article.
Setting Up the Prerequisites
Laravel implements a wrapper on top of the SwiftMailer library that makes email management very easy to configure and use at the same time. You can find the default mail settings at config/mail.php.
<?php return [ /* |-------------------------------------------------------------------------- | Mail Driver |-------------------------------------------------------------------------- | | Laravel supports both SMTP and PHP's "mail" function as drivers for the | sending of e-mail. You may specify which one you're using throughout | your application here. By default, Laravel is setup for SMTP mail. | | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses", | "sparkpost", "log", "array" | */ 'driver' => env('MAIL_DRIVER', 'sendmail'), /* |-------------------------------------------------------------------------- | SMTP Host Address |-------------------------------------------------------------------------- | | Here you may provide the host address of the SMTP server used by your | applications. A default option is provided that is compatible with | the Mailgun mail service which will provide reliable deliveries. | */ 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), /* |-------------------------------------------------------------------------- | SMTP Host Port |-------------------------------------------------------------------------- | | This is the SMTP port used by your application to deliver e-mails to | users of the application. Like the host we have set this value to | stay compatible with the Mailgun e-mail application by default. | */ 'port' => env('MAIL_PORT', 587), /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */ 'from' => [ 'address' => env('MAIL_FROM_ADDRESS', '[email protected]'), 'name' => env('MAIL_FROM_NAME', 'Example'), ], /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol |-------------------------------------------------------------------------- | | Here you may specify the encryption protocol that should be used when | the application send e-mail messages. A sensible default using the | transport layer security protocol should provide great security. | */ 'encryption' => env('MAIL_ENCRYPTION', 'tls'), /* |-------------------------------------------------------------------------- | SMTP Server Username |-------------------------------------------------------------------------- | | If your SMTP server requires a username for authentication, you should | set it here. This will get used to authenticate with your server on | connection. You may also set the "password" value below this one. | */ 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), /* |-------------------------------------------------------------------------- | Sendmail System Path |-------------------------------------------------------------------------- | | When using the "sendmail" driver to send e-mails, we will need to know | the path to where Sendmail lives on this server. A default path has | been provided here, which will work well on most of your systems. | */ 'sendmail' => '/usr/sbin/sendmail -bs', /* |-------------------------------------------------------------------------- | Markdown Mail Settings |-------------------------------------------------------------------------- | | If you are using Markdown based email rendering, you may configure your | theme and component paths here, allowing you to customize the design | of the emails. Or, you may simply stick with the Laravel defaults! | */ 'markdown' => [ 'theme' => 'default', 'paths' => [ resource_path('views/vendor/mail'), ], ], ];
When it comes to sending mails, Laravel supports different drivers to choose from. As you can see, the default MAIL_DRIVER is set to smtp.
If you are going to use the smtp driver to send mails then you're also required to set other related settings like MAIL_HOST, MAIL_PORT, MAIL_ENCRYPTION, MAIL_USERNAME, and MAIL_PASSWORD.
On the other hand, if you are going to use the sendmail driver, then you want to make sure that the sendmail system path is set to the correct value in the config/mail.php file.
You can also set the from address that will be used while sending mails under the from key. And finally, if you want to use Markdown-based email rendering, you can set those settings under the markdown key.
The cherry on the top is that you could also use third-party email service providers like Mailgun, Mandrill, SES, and SparkPost. If you are using one of those services, you need to make sure that you set the corresponding settings in the config/services.php file.
So that was a basic introduction to the mail API related settings in Laravel. From the next section onwards, we'll go through a custom example that shows you how to send emails.
Create the Mailable Class
In this section, we'll create the mailable class, which will be used to send emails. The mailable class is responsible for sending emails using a mailer that's configured in the config/mail.php file. In fact, Laravel already provides an artisan command that allows us to create a base template.
php artisan make:mail DemoEmail
That should create a blank email template at app/Mail/DemoEmail.php, as shown in the following snippet.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { return $this->view('view.name'); } }
Let's replace the contents of that file with the following.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * The demo object instance. * * @var Demo */ public $demo; /** * Create a new message instance. * * @return void */ public function __construct($demo) { $this->demo = $demo; } /** * Build the message. * * @return $this */ public function build() { return $this->from('[email protected]') ->view('mails.demo') ->text('mails.demo_plain') ->with( [ 'testVarOne' => '1', 'testVarTwo' => '2', ]) ->attach(public_path('/images').'/demo.jpg', [ 'as' => 'demo.jpg', 'mime' => 'image/jpeg', ]); } }
There are two important methods the mailable class generally implements—__construct and build. The __construct method is used to initialize objects that you're supposed to use in the email template. On the other hand, the build method is used to initialize more email-specific values like from, view template, attachments and similar.
In our case, we've passed the $demo object as a constructor argument, and it's assigned to the demo public property.
In the build method, we've initialized an email-specific configuration.
The from is used to set an email address that'll be used as a from address.
Using the view method, you can set the email template that will be used while sending an email using this mailable. In our case, we've set it to mails.demo, and it means that you need to create a view template file at resources/views/mails/demo.blade.php.
Next, the text method is used to set up the plain text version of an email template.
As we've just discussed, the __construct method is used to set up objects that'll be used in the email template, you can also use the with method that allows you to set the view data of a message.
Next, we've used the attach method to attach an image with a message.
Of course, we need to create email templates that we're supposed to use while sending emails. Go ahead and create a file resources/views/mails/demo.blade.php as shown in the following snippet.
Hello <i></i>, <p>This is a demo email for testing purposes! Also, it's the HTML version.</p> <p><u>Demo object values:</u></p> <div> <p><b>Demo One:</b> </p> <p><b>Demo Two:</b> </p> </div> <p><u>Values passed by With method:</u></p> <div> <p><b>testVarOne:</b> </p> <p><b>testVarTwo:</b> </p> </div> Thank You, <br/> <i></i>
Also, let's create the plain text version of that file at resources/views/mails/demo_plain.blade.php.
Hello , This is a demo email for testing purposes! Also, it's the HTML version. Demo object values: Demo One: Demo Two: Values passed by With method: testVarOne: testVarOne: Thank You,
So that was the mailable class at your disposal, and we've not done yet as we need to use the Mail facade to actually send mails. In the very next section, we'll explore how you can use the Mail Facade to send emails using the DemoEmail Mailable class that was just created in this section.
Wrapping Up
In this section, we'll create an example to demonstrate how you can use the Mailable class that was created in the last section.
Let's create a controller file at app/Http/Controllers/MailController.php with the following contents.
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Mail\DemoEmail; use Illuminate\Support\Facades\Mail; class MailController extends Controller { public function send() { $objDemo = new \stdClass(); $objDemo->demo_one = 'Demo One Value'; $objDemo->demo_two = 'Demo Two Value'; $objDemo->sender = 'SenderUserName'; $objDemo->receiver = 'ReceiverUserName'; Mail::to("[email protected]")->send(new DemoEmail($objDemo)); } }
It's important to note that we've included the Illuminate\Support\Facades\Mail Facade that will be used to send an email. In the send method, the following statement is responsible for sending an email by initialising the App\Mail\DemoEmail Mailable in the first place.
Mail::to("[email protected]")->send(new DemoEmail($objDemo));
The to method of the Illuminate\Support\Facades\Mail Facade returns an instance of the \Illuminate\Mail\PendingMail class, which already contains an appropriate mailer configured in the config/mail.php file.
And finally, we use the send method of the \Illuminate\Mail\PendingMail class that sends an actual email.
To test it, let's add an associated route in the routes/web.php file.
// Email related routes Route::get('mail/send', 'MailController@send');
And with that in place, you can run the http://ift.tt/2BSrKyg URL to see if it works as expected.
On the other hand, if you want to test your email templates quickly, without sending actual emails, there's a provision in Laravel that allows you to log all outgoing emails.
To achieve that, you need to set the value of MAIL_DRIVER to log in the config/mail.php file. Next, you could run the aforementioned URL and inspect the log file to check if the email template was logged there.
If everything goes fine, you should see an email being logged to the storage/logs/laravel.log file.
That's pretty much it as far as the mail feature is concerned in Laravel, and that concludes this article as well.
Conclusion
Today, we went through the mail API that comes built into Laravel, and it also supports a variety of drivers as well.
Starting with basic concepts, we implemented the mailable class that is an essential element in the mail API in Laravel as we moved on. At the end, we also tested the mailable class by creating a custom controller to see if it actually works.
If you're just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.
I would love to know your feedback in the form of queries and comments using the feed below!
via Envato Tuts+ Code http://ift.tt/2lq3bll
0 notes
pentesttestingcorp · 5 months ago
Text
Race Conditions in Laravel: Security Risks and Prevention
In this blog, we’ll explore what race conditions are, how they impact Laravel applications, and how to prevent them using practical coding examples. Additionally, we’ll show you how to assess your website’s vulnerabilities with our free Website Security Scanner tool.
Tumblr media
What Are Race Conditions?
A race condition arises when two or more processes or threads execute simultaneously, and the output depends on the sequence or timing of their execution. In Laravel, this issue typically occurs when working with database transactions, caches, or queues. For instance:
A user submits two simultaneous requests to withdraw money from their account.
Both requests bypass a balance check before the withdrawal is complete, leading to an overdraft.
These vulnerabilities not only disrupt functionality but can also be exploited by attackers to manipulate data or gain unauthorized access.
Impact of Race Conditions in Laravel Applications
Some potential consequences of race conditions include:
Financial fraud – Exploiting concurrent transactions.
Data inconsistency – Overwriting shared resources.
Privilege escalation – Gaining unauthorized access to protected resources.
How to Detect Race Conditions
Identifying race conditions can be challenging but is crucial for securing your Laravel application. Use our free Website Security Checker tool to scan your website for vulnerabilities, including those related to race conditions.
Coding Examples to Mitigate Race Conditions
Below are examples to demonstrate common race condition scenarios in Laravel and how to mitigate them effectively:
1. Database Locking Using Transactions
One way to prevent race conditions is by using database transactions with locks.
use Illuminate\Support\Facades\DB; DB::transaction(function () { $account = DB::table('accounts')->where('id', 1)- >lockForUpdate()->first(); if ($account->balance >= 100) { DB::table('accounts')->where('id', 1)- >decrement('balance', 100); } });
In this code:
lockForUpdate() ensures no other transaction can access the row until the current transaction completes.
2. Using Redis for Distributed Locking
For distributed applications, using Redis locks is a common solution:
use Illuminate\Support\Facades\Redis; $lock = Redis::lock('withdraw:account:1', 10); if ($lock->get()) { // Perform the operation Redis::unlock('withdraw:account:1'); }
This ensures that only one operation is performed on the shared resource.
3. Queues and Job Prioritization
Laravel's queues are also helpful in preventing race conditions. Prioritize jobs to ensure critical tasks are executed sequentially.
dispatch(new WithdrawMoney($accountId, $amount))->onQueue('transactions');
Image Example: Detect Race Conditions with Our Tool
To detect race condition vulnerabilities in your Laravel application, you can use our free Website Security Checker tool. Below is a screenshot of the tool's interface:
Tumblr media
Screenshot of the free tools webpage where you can access security assessment tools.
Additionally, after running the scan, you’ll receive a detailed vulnerability assessment report by our free tool to check Website Vulnerability, as shown below:
Tumblr media
An Example of a vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.
Preventing Race Conditions with Best Practices
Here are some tips to further secure your Laravel application:
Use optimistic and pessimistic locking – Manage concurrent database transactions effectively.
Implement atomic operations – Ensure that operations complete as a single unit.
Conduct regular vulnerability assessments – Regularly scan your site using tools like ours.
Secure Your Application with Our Tool
Identifying and fixing race conditions is critical for a secure web application. To ensure your website is free from race conditions and other vulnerabilities, visit our free Website Security checker tool at https://free.pentesttesting.com/.
Start improving your website's security today!
1 note · View note
pentesttestingcorp · 5 months ago
Text
Insecure Deserialization Vulnerabilities in Laravel: How to Protect Your Web Applications
Introduction: What is Insecure Deserialization?
Insecure deserialization is a vulnerability that occurs when untrusted data is deserialized into objects. In the context of a Laravel application, this could allow attackers to manipulate serialized objects, leading to remote code execution, data tampering, or other severe consequences.
Tumblr media
Understanding this vulnerability is crucial for maintaining a secure web application, and in this blog post, we will dive into how to identify and mitigate insecure deserialization in Laravel applications.
The Risk of Insecure Deserialization in Laravel
Laravel uses PHP’s native serialize() and unserialize() functions for object serialization. If user-controlled data is deserialized, malicious actors could inject code that manipulates the application’s behavior.
For instance, an attacker could inject a payload that, when deserialized, executes unwanted code, resulting in security breaches such as privilege escalation or system compromise.
Let’s break down an example of how this vulnerability works.
Coding Example: How Insecure Deserialization Works in Laravel
Consider a Laravel application that uses serialization to store user preferences in a session:
// Store user preferences in a session $userPreferences = ['theme' => 'dark', 'notifications' => 'enabled']; session(['user_preferences' => serialize($userPreferences)]);
Later, when the application retrieves these preferences:
// Retrieve and unserialize user preferences $userPreferences = unserialize(session('user_preferences'));
In this example, if the session data is manipulated or an attacker crafts a malicious payload, it could lead to harmful behavior. A simple attacker-controlled input like O:8:"stdClass":1:{s:3:"foo";s:5:"bar";} could cause the application to execute unintended actions.
Preventing Insecure Deserialization in Laravel
To prevent insecure deserialization, you should:
Avoid Unserialize User-Controlled Data: Don’t deserialize data from untrusted sources, especially user input. If necessary, use json_decode() instead of unserialize() as it is more secure for handling data.
Use Class Whitelisting: Laravel provides unserialize class whitelisting through the unserialize_callback_func PHP directive. This limits the classes that can be deserialized, reducing the risk of remote code execution.
Example:
ini_set('unserialize_callback_func', 'my_safe_callback');
3. Encrypt Serialized Data: Laravel supports built-in encryption mechanisms. By encrypting your serialized data, you ensure that an attacker cannot manipulate it even if they can access it.
Example:
use Illuminate\Support\Facades\Crypt; $encryptedData = Crypt::encrypt($userPreferences);
4. Regular Security Audits: Regular vulnerability assessments and penetration testing can help identify and fix deserialization issues before they become a threat.
How Our Free Website Security Tool Can Help
To make this process easier for you, our free Website Security Scanner tool helps you quickly detect vulnerabilities such as insecure deserialization on your Laravel application. It provides a detailed analysis of your website’s security and suggests the next steps.
Here’s a screenshot of our Website Security Checker:
Tumblr media
Screenshot of the free tools webpage where you can access security assessment tools.
After running the analysis, you will get a comprehensive vulnerability assessment report that highlights any potential security risks, including insecure deserialization. This can guide you in addressing vulnerabilities effectively.
Here’s a screenshot of a typical vulnerability assessment report:
Tumblr media
An example of a vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.
Conclusion
Insecure deserialization is a serious risk that can lead to devastating security breaches. However, by following best practices such as avoiding deserialization of user-controlled data, using encryption, and running regular security audits, you can significantly reduce this risk.
Leverage our free tool to check Website Vulnerability to ensure that your Laravel application is protected from this and other potential vulnerabilities.
Don’t wait for an attack to happen. Take proactive measures and secure your web applications today!
1 note · View note
programmingbiters-blog · 7 years ago
Photo
Tumblr media
New Post has been published on http://programmingbiters.com/how-to-get-current-url-in-controller-or-view-2-2/
Laravel - How to get current URL in controller or view?
We always require to get current URL path when work on ajax pagination or something, at that we require to get current page URL on Controller or blade file. So, you can get current url easily.
Laravel provide URL facade that way we can get current URL anywhere, as bellow you can see i use current() of URL facade. URL facade through you can get your current page url from every where. So you can check your current url this way:
Example:
$currentURL = URL::current(); dd($currentURL);
0 notes
t-baba · 7 years ago
Photo
Tumblr media
How to Send Emails in Laravel
In this article, we're going to explore the Mail API in the Laravel web framework. Laravel takes advantage of the popular SwiftMailer library, which is easy to use and comes with a variety of email drivers to choose from. In the latter stages of the article, we'll go through an in-depth demonstration of the concepts discussed in the first half of the article.
Setting Up the Prerequisites
Laravel implements a wrapper on top of the SwiftMailer library that makes email management very easy to configure and use at the same time. You can find the default mail settings at config/mail.php.
<?php return [ /* |-------------------------------------------------------------------------- | Mail Driver |-------------------------------------------------------------------------- | | Laravel supports both SMTP and PHP's "mail" function as drivers for the | sending of e-mail. You may specify which one you're using throughout | your application here. By default, Laravel is setup for SMTP mail. | | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses", | "sparkpost", "log", "array" | */ 'driver' => env('MAIL_DRIVER', 'sendmail'), /* |-------------------------------------------------------------------------- | SMTP Host Address |-------------------------------------------------------------------------- | | Here you may provide the host address of the SMTP server used by your | applications. A default option is provided that is compatible with | the Mailgun mail service which will provide reliable deliveries. | */ 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), /* |-------------------------------------------------------------------------- | SMTP Host Port |-------------------------------------------------------------------------- | | This is the SMTP port used by your application to deliver e-mails to | users of the application. Like the host we have set this value to | stay compatible with the Mailgun e-mail application by default. | */ 'port' => env('MAIL_PORT', 587), /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */ 'from' => [ 'address' => env('MAIL_FROM_ADDRESS', '[email protected]'), 'name' => env('MAIL_FROM_NAME', 'Example'), ], /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol |-------------------------------------------------------------------------- | | Here you may specify the encryption protocol that should be used when | the application send e-mail messages. A sensible default using the | transport layer security protocol should provide great security. | */ 'encryption' => env('MAIL_ENCRYPTION', 'tls'), /* |-------------------------------------------------------------------------- | SMTP Server Username |-------------------------------------------------------------------------- | | If your SMTP server requires a username for authentication, you should | set it here. This will get used to authenticate with your server on | connection. You may also set the "password" value below this one. | */ 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), /* |-------------------------------------------------------------------------- | Sendmail System Path |-------------------------------------------------------------------------- | | When using the "sendmail" driver to send e-mails, we will need to know | the path to where Sendmail lives on this server. A default path has | been provided here, which will work well on most of your systems. | */ 'sendmail' => '/usr/sbin/sendmail -bs', /* |-------------------------------------------------------------------------- | Markdown Mail Settings |-------------------------------------------------------------------------- | | If you are using Markdown based email rendering, you may configure your | theme and component paths here, allowing you to customize the design | of the emails. Or, you may simply stick with the Laravel defaults! | */ 'markdown' => [ 'theme' => 'default', 'paths' => [ resource_path('views/vendor/mail'), ], ], ];
When it comes to sending mails, Laravel supports different drivers to choose from. As you can see, the default MAIL_DRIVER is set to smtp.
If you are going to use the smtp driver to send mails then you're also required to set other related settings like MAIL_HOST, MAIL_PORT, MAIL_ENCRYPTION, MAIL_USERNAME, and MAIL_PASSWORD.
On the other hand, if you are going to use the sendmail driver, then you want to make sure that the sendmail system path is set to the correct value in the config/mail.php file.
You can also set the from address that will be used while sending mails under the from key. And finally, if you want to use Markdown-based email rendering, you can set those settings under the markdown key.
The cherry on the top is that you could also use third-party email service providers like Mailgun, Mandrill, SES, and SparkPost. If you are using one of those services, you need to make sure that you set the corresponding settings in the config/services.php file.
So that was a basic introduction to the mail API related settings in Laravel. From the next section onwards, we'll go through a custom example that shows you how to send emails.
Create the Mailable Class
In this section, we'll create the mailable class, which will be used to send emails. The mailable class is responsible for sending emails using a mailer that's configured in the config/mail.php file. In fact, Laravel already provides an artisan command that allows us to create a base template.
php artisan make:mail DemoEmail
That should create a blank email template at app/Mail/DemoEmail.php, as shown in the following snippet.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { return $this->view('view.name'); } }
Let's replace the contents of that file with the following.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * The demo object instance. * * @var Demo */ public $demo; /** * Create a new message instance. * * @return void */ public function __construct($demo) { $this->demo = $demo; } /** * Build the message. * * @return $this */ public function build() { return $this->from('[email protected]') ->view('mails.demo') ->text('mails.demo_plain') ->with( [ 'testVarOne' => '1', 'testVarTwo' => '2', ]) ->attach(public_path('/images').'/demo.jpg', [ 'as' => 'demo.jpg', 'mime' => 'image/jpeg', ]); } }
There are two important methods the mailable class generally implements—__construct and build. The __construct method is used to initialize objects that you're supposed to use in the email template. On the other hand, the build method is used to initialize more email-specific values like from, view template, attachments and similar.
In our case, we've passed the $demo object as a constructor argument, and it's assigned to the demo public property.
In the build method, we've initialized an email-specific configuration.
The from is used to set an email address that'll be used as a from address.
Using the view method, you can set the email template that will be used while sending an email using this mailable. In our case, we've set it to mails.demo, and it means that you need to create a view template file at resources/views/mails/demo.blade.php.
Next, the text method is used to set up the plain text version of an email template.
As we've just discussed, the __construct method is used to set up objects that'll be used in the email template, you can also use the with method that allows you to set the view data of a message.
Next, we've used the attach method to attach an image with a message.
Of course, we need to create email templates that we're supposed to use while sending emails. Go ahead and create a file resources/views/mails/demo.blade.php as shown in the following snippet.
Hello <i></i>, <p>This is a demo email for testing purposes! Also, it's the HTML version.</p> <p><u>Demo object values:</u></p> <div> <p><b>Demo One:</b> </p> <p><b>Demo Two:</b> </p> </div> <p><u>Values passed by With method:</u></p> <div> <p><b>testVarOne:</b> </p> <p><b>testVarTwo:</b> </p> </div> Thank You, <br/> <i></i>
Also, let's create the plain text version of that file at resources/views/mails/demo_plain.blade.php.
Hello , This is a demo email for testing purposes! Also, it's the HTML version. Demo object values: Demo One: Demo Two: Values passed by With method: testVarOne: testVarOne: Thank You,
So that was the mailable class at your disposal, and we've not done yet as we need to use the Mail facade to actually send mails. In the very next section, we'll explore how you can use the Mail Facade to send emails using the DemoEmail Mailable class that was just created in this section.
Wrapping Up
In this section, we'll create an example to demonstrate how you can use the Mailable class that was created in the last section.
Let's create a controller file at app/Http/Controllers/MailController.php with the following contents.
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Mail\DemoEmail; use Illuminate\Support\Facades\Mail; class MailController extends Controller { public function send() { $objDemo = new \stdClass(); $objDemo->demo_one = 'Demo One Value'; $objDemo->demo_two = 'Demo Two Value'; $objDemo->sender = 'SenderUserName'; $objDemo->receiver = 'ReceiverUserName'; Mail::to("[email protected]")->send(new DemoEmail($objDemo)); } }
It's important to note that we've included the Illuminate\Support\Facades\Mail Facade that will be used to send an email. In the send method, the following statement is responsible for sending an email by initialising the App\Mail\DemoEmail Mailable in the first place.
Mail::to("[email protected]")->send(new DemoEmail($objDemo));
The to method of the Illuminate\Support\Facades\Mail Facade returns an instance of the \Illuminate\Mail\PendingMail class, which already contains an appropriate mailer configured in the config/mail.php file.
And finally, we use the send method of the \Illuminate\Mail\PendingMail class that sends an actual email.
To test it, let's add an associated route in the routes/web.php file.
// Email related routes Route::get('mail/send', 'MailController@send');
And with that in place, you can run the http://ift.tt/2BSrKyg URL to see if it works as expected.
On the other hand, if you want to test your email templates quickly, without sending actual emails, there's a provision in Laravel that allows you to log all outgoing emails.
To achieve that, you need to set the value of MAIL_DRIVER to log in the config/mail.php file. Next, you could run the aforementioned URL and inspect the log file to check if the email template was logged there.
If everything goes fine, you should see an email being logged to the storage/logs/laravel.log file.
That's pretty much it as far as the mail feature is concerned in Laravel, and that concludes this article as well.
Conclusion
Today, we went through the mail API that comes built into Laravel, and it also supports a variety of drivers as well.
Starting with basic concepts, we implemented the mailable class that is an essential element in the mail API in Laravel as we moved on. At the end, we also tested the mailable class by creating a custom controller to see if it actually works.
If you're just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.
I would love to know your feedback in the form of queries and comments using the feed below!
by Sajal Soni via Envato Tuts+ Code http://ift.tt/2lqIYf4
0 notes