search
HomePHP FrameworkLaravellaravel HTTP request: get cookies and uploaded files

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
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
What is the latest Laravel version?What is the latest Laravel version?May 09, 2025 am 12:09 AM

As of October 2023, Laravel's latest version is 10.x. 1.Laravel10.x supports PHP8.1, improving development efficiency. 2.Jetstream improves support for Livewire and Inertia.js, simplifies front-end development. 3.EloquentORM adds full-text search function to improve data processing performance. 4. Pay attention to dependency package compatibility when using it and apply cache optimization performance.

Laravel Migrations: A Beginner's Guide to Database ManagementLaravel Migrations: A Beginner's Guide to Database ManagementMay 09, 2025 am 12:07 AM

LaravelMigrationsstreamlinedatabasemanagementbyprovidingversioncontrolforyourdatabaseschema.1)Theyallowyoutodefineandsharethestructureofyourdatabase,makingiteasytomanagechangesovertime.2)Migrationscanbecreatedandrunusingsimplecommands,ensuringthateve

Laravel migration: Best coding guideLaravel migration: Best coding guideMay 09, 2025 am 12:03 AM

Laravel's migration system is a powerful tool for developers to design and manage databases. 1) Ensure that the migration file is named clearly and use verbs to describe the operation. 2) Consider data integrity and performance, such as adding unique constraints to fields. 3) Use transaction processing to ensure database consistency. 4) Create an index at the end of the migration to optimize performance. 5) Maintain the atomicity of migration, and each file contains only one logical operation. Through these practices, efficient and maintainable migration code can be written.

Latest Laravel Version: Stay Up-to-Date with the Newest FeaturesLatest Laravel Version: Stay Up-to-Date with the Newest FeaturesMay 09, 2025 am 12:03 AM

Laravel's latest version is 10.x, released in early 2023. This version brings enhanced EloquentORM functionality and a simplified routing system, improving development efficiency and performance, but it needs to be tested carefully during upgrades to prevent problems.

Mastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMay 08, 2025 am 12:25 AM

Laravelsoftdeletesallow"deletion"withoutremovingrecordsfromthedatabase.Toimplement:1)UsetheSoftDeletestraitinyourmodel.2)UsewithTrashed()toincludesoft-deletedrecordsinqueries.3)CreatecustomscopeslikeonlyTrashed()forstreamlinedcode.4)Impleme

Laravel Soft Deletes: Restoring and Permanently Deleting RecordsLaravel Soft Deletes: Restoring and Permanently Deleting RecordsMay 08, 2025 am 12:24 AM

In Laravel, restore the soft deleted records using the restore() method, and permanently delete the forceDelete() method. 1) Use withTrashed()->find()->restore() to restore a single record, and use onlyTrashed()->restore() to restore a single record. 2) Permanently delete a single record using withTrashed()->find()->forceDelete(), and multiple records use onlyTrashed()->forceDelete().

The Current Laravel Release: Download and Upgrade Today!The Current Laravel Release: Download and Upgrade Today!May 08, 2025 am 12:22 AM

You should download and upgrade to the latest Laravel version as it provides enhanced EloquentORM capabilities and new routing features, which can improve application efficiency and security. To upgrade, follow these steps: 1. Back up the current application, 2. Update the composer.json file to the latest version, 3. Run the update command. While some common problems may be encountered, such as discarded functions and package compatibility, these issues can be solved through reference documentation and community support.

Laravel: When should I update to the last version?Laravel: When should I update to the last version?May 08, 2025 am 12:18 AM

YoushouldupdatetothelatestLaravelversionwhenthebenefitsclearlyoutweighthecosts.1)Newfeaturesandimprovementscanenhanceyourapplication.2)Securityupdatesarecrucialifvulnerabilitiesareaddressed.3)Performancegainsmayjustifyanupdateifyourappstruggles.4)Ens

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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 Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version