Home PHP Framework Laravel laravel HTTP request: get cookies and uploaded files

laravel HTTP request: get cookies and uploaded files

Dec 14, 2020 pm 09:44 PM
laravel

COOKIE

Laravel will encrypt the cookie value at the bottom layer and use the authorization code for signature. Therefore, if the client modifies the cookie value, it will become invalid. This way, we don't have to worry about cookie forgery.

Setting the cookie value

Setting the cookie value will use the knowledge of laravel response (Response), which is briefly mentioned here.

You can use the cookie function to create a cookie, and then return the cookie to the client through the response function:

// cookie($name, $value, $minutes, $path, $domain, false, ...);
$cookie = cookie('username', 'php.cn', 3600);
return response('hello laravel')->cookie($cookie);

In addition to using the cookie function, you can also use the cookie method of the response instance to set and return . The parameters of this method and cookie function are consistent.

return response('Hello World')->cookie(
    'name', 'php.cn', 3600
);

Get the cookie value

There are two ways to get the cookie value. These two methods are demonstrated below:

use Illuminate\Http\Request;
$value = $request->cookie('name');
// 或
use Illuminate\Support\Facades\Cookie;
$value = Cookie::get('name');

Get uploaded files

The laravel framework is very simple to get uploaded files and save files.

There are two ways to get the uploaded file, use the file method or the dynamic attribute method. This method returns an Illuminate\Http\UploadedFile instance.

$logo = $request->file('logo');
// or
$logo = $request->logo;

Of course, you can determine whether the file exists before getting it. Here, use the hasFile method:

if ($request->hasFile('logo')) {
    $logo = $request->file('logo');
}

The request request instance can also verify the uploaded file. We highly recommend that you verify the uploaded file before saving it. Do this:

if ($request->file('logo')->isValid()) {
    //
}

The uploadFile instance has many methods to obtain the temporary saving path, extension and other information of the uploaded file. The following demonstrates how to obtain the file type suffix

$logo = $request->file('logo');
$logo->path();  // png

Finally, how to save the file. Save the file using the store method. This method has two parameters. The first parameter fills in the path to save the file, and the second parameter fills in the file. In which home directory (or third-party platform) it is saved. Laravel will automatically generate a unique ID as the file name. This information is in the configuration file config/filesystems.php, as follows:

'disks' => [
    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
    ],
    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'url' => env('AWS_URL'),
        'endpoint' => env('AWS_ENDPOINT'),
    ],
],

If you want to set the file name for saving the price request file yourself, you need to use the storeAs method. The second parameter of this method is the file to be set. name.

$request->file('logo')->storeAs('img/logo', '1.png');

Finally, post a complete file upload code example:

html code is as follows:

<form method="post" action="/index?a=32" enctype="multipart/form-data">
    @csrf
    <input type="file" name="logo" >
    <input type="submit" value="sub" />
</form>

save file code as follows:

if ($request->hasFile(&#39;logo&#39;)) {
    $logo = $request->file(&#39;logo&#39;);
    if ($logo->isValid()) {
        $ext = $logo->extension();
        $fileName = date(&#39;YmdHis&#39;) . mt_rand(10000,99999);
        $path = $logo->storeAs(&#39;img/logo&#39;, $fileName . &#39;.&#39; . $ext);
        dump($path); //"img/logo/2020121413351718218.png"
    }
}

The above is the detailed content of laravel HTTP request: get cookies and uploaded files. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Peak: How To Revive Players
1 months ago By DDD
PEAK How to Emote
3 weeks ago By Jack chen

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with pivot tables in Laravel Many-to-Many relationships Working with pivot tables in Laravel Many-to-Many relationships Jul 07, 2025 am 01:06 AM

ToworkeffectivelywithpivottablesinLaravel,firstaccesspivotdatausingwithPivot()orwithTimestamps(),thenupdateentrieswithupdateExistingPivot(),managerelationshipsviadetach()andsync(),andusecustompivotmodelswhenneeded.1.UsewithPivot()toincludespecificcol

Adding multilingual support to a Laravel application Adding multilingual support to a Laravel application Jul 03, 2025 am 01:17 AM

The core methods for Laravel applications to implement multilingual support include: setting language files, dynamic language switching, translation URL routing, and managing translation keys in Blade templates. First, organize the strings of each language in the corresponding folders (such as en, es, fr) in the /resources/lang directory, and define the translation content by returning the associative array; 2. Translate the key value through the \_\_() helper function call, and use App::setLocale() to combine session or routing parameters to realize language switching; 3. For translation URLs, paths can be defined for different languages ​​through prefixed routing groups, or route alias in language files dynamically mapped; 4. Keep the translation keys concise and

Sending different types of notifications with Laravel Sending different types of notifications with Laravel Jul 06, 2025 am 12:52 AM

Laravelprovidesacleanandflexiblewaytosendnotificationsviamultiplechannelslikeemail,SMS,in-appalerts,andpushnotifications.Youdefinenotificationchannelsinthevia()methodofanotificationclass,andimplementspecificmethodsliketoMail(),toDatabase(),ortoVonage

Laravel MVC: real code samples Laravel MVC: real code samples Jul 03, 2025 am 12:35 AM

Laravel's MVC architecture consists of a model, a view and a controller, which are responsible for data logic, user interface and request processing respectively. 1) Create a User model to define data structures and relationships. 2) UserController processes user requests, including listing, displaying and creating users. 3) The view uses the Blade template to display user data. This architecture improves code clarity and maintainability.

Understanding and creating custom Service Providers in Laravel Understanding and creating custom Service Providers in Laravel Jul 03, 2025 am 01:35 AM

ServiceProvider is the core mechanism used in the Laravel framework for registering services and initializing logic. You can create a custom ServiceProvider through the Artisan command; 1. The register method is used to bind services, register singletons, set aliases, etc., and other services that have not yet been loaded cannot be called; 2. The boot method runs after all services are registered and is used to register event listeners, view synthesizers, middleware and other logic that depends on other services; common uses include binding interfaces and implementations, registering Facades, loading configurations, registering command-line instructions and view components; it is recommended to centralize relevant bindings to a ServiceProvider to manage, and pay attention to registration

Handling exceptions and logging errors in a Laravel application Handling exceptions and logging errors in a Laravel application Jul 02, 2025 pm 03:24 PM

The core methods for handling exceptions and recording errors in Laravel applications include: 1. Use the App\Exceptions\Handler class to centrally manage unhandled exceptions, and record or notify exception information through the report() method, such as sending Slack notifications; 2. Use Monolog to configure the log system, set the log level and output method in config/logging.php, and enable error and above level logs in production environment. At the same time, detailed exception information can be manually recorded in report() in combination with the context; 3. Customize the render() method to return a unified JSON format error response, improving the collaboration efficiency of the front and back end of the API. These steps are

Configuring and sending email notifications in Laravel Configuring and sending email notifications in Laravel Jul 05, 2025 am 01:26 AM

TosetupemailnotificationsinLaravel,firstconfiguremailsettingsinthe.envfilewithSMTPorservice-specificdetailslikeMAIL\_MAILER,MAIL\_HOST,MAIL\_PORT,MAIL\_USERNAME,MAIL\_PASSWORD,andMAIL\_FROM\_ADDRESS.Next,testtheconfigurationusingMail::raw()tosendasam

Managing database state for testing in Laravel Managing database state for testing in Laravel Jul 13, 2025 am 03:08 AM

Methods to manage database state in Laravel tests include using RefreshDatabase, selective seeding of data, careful use of transactions, and manual cleaning if necessary. 1. Use RefreshDatabasetrait to automatically migrate the database structure to ensure that each test is based on a clean database; 2. Use specific seeds to fill the necessary data and generate dynamic data in combination with the model factory; 3. Use DatabaseTransactionstrait to roll back the test changes, but pay attention to its limitations; 4. Manually truncate the table or reseed the database when it cannot be automatically cleaned. These methods are flexibly selected according to the type of test and environment to ensure the reliability and efficiency of the test.

See all articles