Users view registration логин любое.

The wix-users module contains functionality for working with your site"s users from client-side code.

Note

onReady()

Table of Contents

Store values associated with an object.

Perform actions on an object.

Objects used when setting, getting, or calling the properties and methods listed above.

Related Content

FAQ

currentUser

Gets the current user viewing the site.

Description

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

The APIs in wix-users can only be used once the page has loaded. Therefore, you must use them in code that is contained in or is called from the onReady() event handler or any element event handler.

Syntax

get currentUser(): User

TYPE

The kind of data the property stores.

Examples

Get the current user"s information

Copy Code import wixUsers from "wix-users"; // ... let user = wixUsers.currentUser; let userId = user.id; // "r5cme-6fem-485j-djre-4844c49" let isLoggedIn = user.loggedIn; // true user.getEmail() .then((email) => { let userEmail = email; // "[email protected]" }); user.getRoles() .then((roles) => { let firstRole = roles; let roleName = firstRole.name; // "Role Name" let roleDescription = firstRole.description; // "Role Description" }); user.getPricingPlans() .then((pricingPlans) => { let firstPlan = pricingPlans; let planName = firstPlan.name; // "Gold" let startDate = firstPlan.startDate; // Wed Aug 29 2018 09:39:41 GMT-0500 (Eastern Standard Time) let expiryDate = firstPlan.expiryDate; // Thu Nov 29 2018 08:39:41 GMT-0400 (Eastern Daylight Time) });

applySessionToken()

Logs the current user into the site using the given session token.

Description

The applySessionToken() function returns a Promise that resolves when the given session token is applied and the current user is logged into the site.

You receive a session token from the following functions called from backend code:

  • approveByEmail()
  • approveByToken()
  • register()

Pass the returned session token to your client-side code and apply it by calling applySessionToken() to complete the process started by one of the above functions.

Syntax

function applySessionToken(sessionToken: string): Promise

PARAMETERS

sessionToken

The session token to apply.

RETURN VALUE

Promise

Fulfilled - When the token as been applied.

Examples

Log in the current user by applying a session token

Copy Code import wixUsers from "wix-users"; // ... wixUsers.applySessionToken(sessionToken) .then(() => { console.log("User logged in."); });

Register a user using a 3rd party for approval

This example demonstrates a common 3rd party approval flow. The backend code calls a 3rd party function that determines whether the user is approved or not. If approved, the register() function is called, the registration is approved programmatically, and a session token is returned to the calling client-side code. If rejected, the blockByEmail() function is called.

Copy Code /******************************* * backend code - register.jsw * *******************************/ import wixUsers from "wix-users-backend"; import {approveBy3rdParty} from "some-backend-module"; export function doRegistration(email, password, firstName, lastName) { // call a 3rd party API to check if the user is approved return approveBy3rdParty(email, password) .then((isApproved) => { // if approved by 3rd party if (isApproved) { // register the user return wixUsers.register(email, password, { "contactInfo": { "firstName": firstName, "lastName": lastName } }) // user is now registered and pending approval // approve the user .then((result) => wixUsers.approveByToken(result.approvalToken)) // user is now active, but not logged in // return the session token to log in the user client-side .then((sessionToken) => { return {sessionToken, "approved": true}; }); } // if not approved by 3rd party else { return {"approved": false}; } }) } /******************** * client-side code * ********************/ import wixUsers from "wix-users"; import {doRegistration} from "backend/register"; // ... let email = // the user"s email addresses let password = // the user"s password let firstName = // the user"s first name let lastName = // the user"s last name doRegistration(email, password, firstName, lastName) .then((result) => { if (result.approved) // log the user in wixUsers.applySessionToken(result.sessionToken); else { console.log("Not approved!"); } });

Log a user in after 3rd party authentication

This example contains a backend function which uses a 3rd party authentication service to authenticate a user. If the authentication is successful, a session session token is returned to the client-side and used to log in the authenticated user.

Copy Code /******************************* * backend code - login.jsw * *******************************/ import wixUsers from "wix-users-backend"; import {authBy3rdParty} from "backend/authentications"; export function getLoginToken(email, password) { // authenticate using 3rd party return authBy3rdParty(email, password) .then((isAuthenticated) => { // if authenticated generate and return session token if(isAuthenticated){ return wixUsers.generateSessionToken(email) .then((sessionToken) => { return {"sessionToken": sessionToken, "approved": true}; }); } // if not authenticated return non-approval return {"approved": false}; }); } /********************************* * client-side login code * *********************************/ import {getLoginToken} from "backend/login"; import wixUsers from "wix-users"; export async function button_onClick(event) { // call backend function getLoginToken($w("#email").value, $w("#password").value) .then((loginResult) => { // if approved log the user in with the session token if (loginResult.approved) { wixUsers.applySessionToken(loginResult.sessionToken); } // if not approved log a message else { console.log("User not approved."); } }); }

Register a user sending an email for confirmation

This example demonstrates a common email verification flow. A user is initially registered but not yet approved. At registration, a verification email is sent with a link to a verification page. When a user goes to the verification page, the approval is granted and the user is logged into the site.

The code is split between three locations:

  • A backend web module named register.jsw .
  • The page code for the page where users register.
  • The page code for the page where users confirm their registration.

Copy Code /******************************* * backend code - register.jsw * *******************************/ import wixUsers from "wix-users-backend"; export function doRegistration(email, password, firstName, lastName) { // register the user return wixUsers.register(email, password, { "contactInfo": { "firstName": firstName, "lastName": lastName } }) .then((results) => { // user is now registered and pending approval // send a registration verification email wixUsers.emailUser("verifyRegistration", results.user.id, { "variables": { "name": firstName, "verifyLink": `http://yourdomain.com/post-register?token=${results.approvalToken}` } }); }); } export function doApproval(token) { // approve the user return wixUsers.approveByToken(token) // user is now active, but not logged in // return the session token to log in the user client-side .then((sessionToken) => { return {sessionToken, "approved": true}; }) .catch((error) => { return {"approved": false, "reason": error}; }); } /********************************* * client-side registration code * *********************************/ import wixUsers from "wix-users"; import {doRegistration} from "backend/register"; export function button_click(event) { let email = // the user"s email address let password = // the user"s password let firstName = // the user"s first name let lastName = // the user"s last name doRegistration(email, password, firstName, lastName) .then(() => { console.log("Confirmation email sent."); }); } /************************************** * client-side post-registration code * **************************************/ import wixLocation from "wix-location"; import wixUsers from "wix-users"; import {doApproval} from "backend/register"; $w.onReady(() => { // get the token from the URL let token = wixLocation.query.token; doApproval(token) .then((result) => { if (result.approved){ // log the user in wixUsers.applySessionToken(result.sessionToken); console.log("Approved"); } else { console.log("Not approved!"); } }); });

emailUser()

Sends a Triggered Email to the currently logged-in site member.

Description

To learn more about Triggered Emails, see:

  • About Triggered Emails
  • Creating a Triggered Email
  • How to Send a Triggered Email to Members with Code

Before using the emailUser() function, you need to set up at least one Triggered Email.

Specify which email to send by passing the email"s ID in the emailId parameter.

Specify which member the email is sent to by passing the member"s user ID in the toUser parameter. You can only send the email to the currently logged-in member. You can get that member"s ID using the property of the .

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

Syntax

function emailUser(emailId: string, toUser: string, ): Promise

PARAMETERS

Values that you pass to a function.

emailId

The Email ID of the Triggered Email to send.

toUser

The User ID of the currently signed-in member.

RETURN VALUE

Value that a function evaluates to when it is finished running.

Promise

Fulfilled - When the email is sent. Rejected - Error message.

Examples

Send a Triggered Email to the currently logged-in member

Copy Code import wixUsers from "wix-users"; // ... let userId = wixUsers.currentUser.id; wixUsers.emailUser("emailID", userId) .then(() => { console.log("Triggered email sent"); }) .catch((err) => { console.log(err); });

Send a Triggered Email to the currently logged-in member with variable values

Copy Code import wixUsers from "wix-users"; // ... let userId = wixUsers.currentUser.id; let value1 = // value for variable1 wixUsers.emailUser("emailID", userId, { "variables": { "variable1": value1, "variable2": "value for variable2" } }) .then(() => { console.log("Triggered email sent"); }) .catch((err) => { console.log(err); });

login()

Logs a user in based on email and password.

Description

The login() function returns a Promise that resolves when the user with the specified email address and password is logged in.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

Syntax

function login(email: string, password: string): Promise

PARAMETERS

Values that you pass to a function.

email

The email address to use when logging the user.

password

The password to use when logging the user.

RETURN VALUE

Value that a function evaluates to when it is finished running.

Promise

Fulfilled - When the user has been logged in. Rejected - Error message.

Examples

Logs a user in

Copy Code import wixUsers from "wix-users"; let email = // email address of user to log in let password = // password of user to log in wixUsers.login(email, password) .then(() => { console.log("User is logged in"); }) .catch((err) => { console.log(err); });

Logs a user in using data from input elements

Copy Code import wixUsers from "wix-users"; let email = $w("#email"); let password = $w("#password"); wixUsers.login(email, password) .then(() => { console.log("User is logged in"); }) .catch((err) => { console.log(err); });

logout()

Logs the current user out of the site.

Description

The logout() function logs the current user out of the site.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

The APIs in wix-users can only be used once the page has loaded. Therefore, you must use them in code that is contained in or is called from the onReady() event handler or any element event handler.

Syntax

function logout(): void

Examples

Log out the current user

Copy Code import wixUsers from "wix-users"; // ... wixUsers.logout();

onLogin()

Sets the function that runs when a user logs in.

Description

Use the onLogin() function for code you want to run after a user successfully logs into your site.

Usually, you want to call the onLogin() function in the Site tab of the code panel so that the onLogin() event handler runs no matter which page on your site a user uses to log in.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

The APIs in wix-users can only be used once the page has loaded. Therefore, you must use them in code that is contained in or is called from the onReady() event handler or any element event handler.

Syntax

function onLogin(handler: LoginHandler): void callback LoginHandler(user: User): void

PARAMETERS

Values that you pass to a function.

Examples

Run code when a user logs in

Copy Code import wixUsers from "wix-users"; // ... wixUsers.onLogin((user) => { let userId = user.id; // "r5cme-6fem-485j-djre-4844c49" let isLoggedIn = user.loggedIn; // true let userRole = user.role; // "Member" });

promptForgotPassword()

Prompts the current site visitor with a password reset.

Description

The promptForgotPassword() function returns a Promise that resolves when the user has sumbitted the forgot password form.

The promptForgotPassword() function cannot be called before the page is ready.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

The APIs in wix-users can only be used once the page has loaded. Therefore, you must use them in code that is contained in or is called from the onReady() event handler or any element event handler.

See Also

Syntax

function promptForgotPassword(): Promise

PARAMETERS

Values that you pass to a function.

language (Optional)

The language of the reset password form. Defaults to "English" if not passed or the given language is not one of the languages found in the Permissions tab of the Page Settings panel in the Editor.

RETURN VALUE

Value that a function evaluates to when it is finished running.

Promise

Rejected - Message that the dialog was canceled, user is already logged in, or any other reason the password reset failed.

Examples

Prompt the user with a password reset

Copy Code import wixUsers from "wix-users"; // ... wixUsers.promptForgotPassword();

Prompt the current user to login with given language

Copy Code import wixUsers from "wix-users"; // ... wixUsers.promptForgotPassword() .then(() => { console.log("Password reset submitted"); }) .catch((err) => { let errorMsg = err; // "The user closed the forgot password dialog" });

promptLogin()

Prompts the current site visitor to log in as a site member.

Description

The promptLogin() function returns a Promise that resolves to the newly logged in user when the login has completed.

The promptLogin() function cannot be called before the page is ready.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

The APIs in wix-users can only be used once the page has loaded. Therefore, you must use them in code that is contained in or is called from the onReady() event handler or any element event handler.

See Also

Syntax

function promptLogin(options: LoginOptions): Promise

PARAMETERS

Values that you pass to a function.

RETURN VALUE

Value that a function evaluates to when it is finished running.

Examples

Prompt the current user to login

Copy Code import wixUsers from "wix-users"; // ... wixUsers.promptLogin() .then((user) => { let userId = user.id; // "r5me-6fem-45jf-djhe-484349" let isLoggedIn = user.loggedIn; // true let userRole = user.role; // "member" return user.getEmail(); }) .then((email) => { let userEmail = email; // "[email protected]" }) .catch((err) => { let errorMsg = err; // "The user closed the login dialog" });

Prompt the current user to login with given options

Copy Code import wixUsers from "wix-users"; // ... let options = {"mode": "login", "lang": "es"}; wixUsers.promptLogin(options) .then((user) => { let userId = user.id; // "r5me-6fem-45jf-djhe-484349" let isLoggedIn = user.loggedIn; // true let userRole = user.role; // "member" return user.getEmail(); }) .then((email) => { let userEmail = email; // "[email protected]" }) .catch((err) => { let errorMsg = err; // "The user closed the login dialog" });

Сегoдня мы рассмотрим эксплуатацию критической 1day-уязвимости в популярной CMS Joomla, которая прогремела на просторах интернета в конце октября. Речь пойдет об уязвимостях с номерами CVE-2016-8869 , CVE-2016-8870 и CVE-2016-9081 . Все три происходят из одного кусочка кода, который пять долгих лет томился в недрах фреймворка в ожидании своего часа, чтобы затем вырваться на свободу и принести с собой хаос, взломанные сайты и слезы ни в чем не повинных пользователей этой Joomla. Лишь самые доблестные и смелые разработчики, чьи глаза красны от света мониторов, а клавиатуры завалены хлебными крошками, смогли бросить вызов разбушевавшейся нечисти и возложить ее голову на алтарь фиксов.

WARNING

Вся информация предоставлена исключительно в ознакомительных целях. Ни редакция, ни автор не несут ответственности за любой возможный вред, причиненный материалами данной статьи.

С чего все началось

6 октября 2016 года Дэмис Пальма (Demis Palma) создал топик на Stack Exchange , в котором поинтересовался: а почему, собственно, в Joomla версии 3.6 существуют два метода регистрации пользователей с одинаковым названием register() ? Первый находится в контроллере UsersControllerRegistration , а второй - в UsersControllerUser . Дэмис хотел узнать, используется ли где-то метод UsersControllerUser::register() , или это лишь эволюционный анахронизм, оставшийся от старой логики. Его беспокоил тот факт, что, даже если этот метод не используется никаким представлением, он может быть вызван при помощи сформированного запроса. На что получил ответ от девелопера под ником itoctopus, подтвердившего: проблема действительно существует. И направил отчет разработчикам Joomla.

Далее события развивались самым стремительным образом. 18 октября разработчики Joomla принимают репорт Дэмиса, который к тому времени набросал PoC, позволяющий регистрировать пользователя. Он опубликовал заметку на своем сайте , где в общих чертах рассказал о найденной проблеме и мыслях по этому поводу. В этот же день выходит новая версия Joomla 3.6.3, которая все еще содержит уязвимый код.

После этого Давиде Тампеллини (Davide Tampellini) раскручивает баг до состояния регистрации не простого пользователя, а администратора. И уже 21 октября команде безопасности Joomla прилетает новый кейс. В нем речь уже идет о повышении привилегий . В этот же день на сайте Joomla появляется анонс о том, что во вторник, 25 октября, будет выпущена очередная версия с порядковым номером 3.6.3, которая исправляет критическую уязвимость в ядре системы.

25 октября Joomla Security Strike Team находит последнюю проблему, которую создает обнаруженный Дэмисом кусок кода. Затем в главную ветку официального репозитория Joomla пушится коммит от 21 октября с неприметным названием Prepare 3.6.4 Stable Release , который фиксит злосчастный баг.

После этого камин-аута к междусобойчику разработчиков подключаются многочисленные заинтересованные личности - начинают раскручивать уязвимость и готовить сплоиты.

27 октября исследователь Гарри Робертс (Harry Roberts) выкладывает в репозиторий Xiphos Research готовый эксплоит , который может загружать PHP-файл на сервер с уязвимой CMS.

Детали

Что ж, с предысторией покончено, переходим к самому интересному - разбору уязвимости. В качестве подопытной версии я установил Joomla 3.6.3, поэтому все номера строк будут актуальны именно для этой версии. А все пути до файлов, которые ты увидишь далее, будут указываться относительно корня установленной CMS.

Благодаря находке Дэмиса Пальмы мы знаем, что есть два метода, которые выполняют регистрацию пользователя в системе. Первый используется CMS и находится в файле /components/com_users/controllers/registration.php:108 . Второй (тот, что нам и нужно будет вызвать), обитает в /components/com_users/controllers/user.php:293 . Посмотрим на него поближе.

286: /** 287: * Method to register a user. 288: * 289: * @return boolean 290: * 291: * @since 1.6 292: */ 293: public function register() 294: { 295: JSession::checkToken("post") or jexit(JText::_("JINVALID_TOKEN")); ... 300: // Get the form data. 301: $data = $this->input->post->get("user", array(), "array"); ... 315: $return = $model->validate($form, $data); 316: 317: // Check for errors. 318: if ($return === false) 319: { ... 345: // Finish the registration. 346: $return = $model->register($data);

Здесь я оставил только интересные строки. Полную версию уязвимого метода можно посмотреть в репозитории Joomla.

Разберемся, что происходит при обычной регистрации пользователя: какие данные отправляются и как они обрабатываются. Если регистрация пользователей включена в настройках, то форму можно найти по адресу http://joomla.local/index.php/component/users/?view=registration .


Легитимный запрос на регистрацию пользователя выглядит как на следующем скриншоте.


За работу с пользователями отвечает компонент com_users . Обрати внимание на параметр task в запросе. Он имеет формат $controller.$method . Посмотрим на структуру файлов.

Имена скриптов в папке controllers соответствуют названиям вызываемых контроллеров. Так как в нашем запросе сейчас $controller = "registration" , то вызовется файл registration.php и его метод register() .

Внимание, вопрос: как передать обработку регистрации в уязвимое место в коде? Ты наверняка уже догадался. Имена уязвимого и настоящего методов совпадают (register), поэтому нам достаточно поменять название вызываемого контроллера. А где у нас находится уязвимый контроллер? Правильно, в файле user.php . Получается $controller = "user" . Собираем все вместе и получаем task = user.register . Теперь запрос на регистрацию обрабатывается нужным нам методом.


Второе, что нам нужно сделать, - это отправить данные в правильном формате. Тут все просто. Легитимный register() ждет от нас массив под названием jform , в котором мы передаем данные для регистрации - имя, логин, пароль, почту (см. скриншот с запросом).

  • /components/com_users/controllers/registration.php: 124: // Get the user data. 125: $requestData = $this->input->post->get("jform", array(), "array");

Наш подопечный получает эти данные из массива с именем user .

  • /components/com_users/controllers/user.php: 301: // Get the form data. 302: $data = $this->input->post->get("user", array(), "array");

Поэтому меняем в запросе имена всех параметров с jfrom на user .

Третий наш шаг - это нахождение валидного токена CSRF, так как без него никакой регистрации не будет.

  • /components/com_users/controllers/user.php: 296: JSession::checkToken("post") or jexit(JText::_("JINVALID_TOKEN"));

Он выглядит как хеш MD5, а взять его можно, например, из формы авторизации на сайте /index.php/component/users/?view=login .


Теперь можно создавать пользователей через нужный метод. Если все получилось, то поздравляю - ты только что проэксплуатировал уязвимость CVE-2016-8870 «отсутствующая проверка разрешений на регистрацию новых пользователей».

Вот как она выглядит в «рабочем» методе register() из контроллера UsersControllerRegistration:

  • /components/com_users/controllers/registration.php: 113: // If registration is disabled - Redirect to login page. 114: if (JComponentHelper::getParams("com_users")->get("allowUserRegistration") == 0) 115: { 116: $this->setRedirect(JRoute::_("index.php?option=com_users&view=login", false)); 117: 118: return false; 119: }

А так в уязвимом:

  • /components/com_users/controllers/user.php:

Ага, никак.

Чтобы понять вторую, гораздо более серьезную проблему, отправим сформированный нами запрос и проследим, как он выполняется на различных участках кода. Вот кусок, который отвечает за проверку отправленных пользователем данных в рабочем методе:

Продолжение доступно только подписчикам

Вариант 1. Оформи подписку на «Хакер», чтобы читать все материалы на сайте

Подписка позволит тебе в течение указанного срока читать ВСЕ платные материалы сайта. Мы принимаем оплату банковскими картами, электронными деньгами и переводами со счетов мобильных операторов.

Laravel provides built-in user registration and login system. Most of the developers are not aware of this built-in system (We also didn’t know this feature). When we come to know about this feature, we got surprised. It saves us a lot of time from building a login and registration system starting from scratch.

In this article, we study user registration and login system in Laravel – the feature provided by Laravel itself.

For getting started, we are assuming you have a fresh installation of a Laravel. If you don’t have it then create it by running the command:

Composer create-project --prefer-dist laravel/laravel laravel-dev

Here ‘laravel-dev’ is the name of your Laravel project. Of course, you can change the name as you wish.

Head over to the project root directory in the terminal and run the command:

php artisan make:auth

This command will create authentication controllers like LoginController.php , RegisterController.php , etc which you will find the app/Http/Controllers/Auth directory. It also creates a views login.blade.php , register.blade.php under resources/view/auth directory.

This make:auth command also creates a app.blade.php file under resources/views/layouts directory. This view is a base layout for your application. It uses Bootstrap CSS framework but user can customize it and change the design.

Email Verification

While building a registration system, normally on signup we send an activation link to users. This activation link will use to verify the user account. Once, the user clicks on an activation link then we make that user active for our system. In other words, after verifying account user can browse the pages to our system.

Laravel provides a built-in system for email verification of a newly registered user. Using this, on registration user will get an email with activation link. Once he activated account then he would able to browse the system. Here, we can apply middleware("verified") for protecting routes. Doing so, these protected routes can be accessible only by verified accounts.

Open the App\User.php file and make sure this model implements Illuminate\Contracts\Auth\MustVerifyEmail contract.

How does it work? If you check the migration file, user table must contain email_verified_at column. This column will use to verify whether the user activated their account. If activated, then this column will store date and time at the time of activation.

When we run the make:auth command, it also creates a Auth\VerificationController class which has logic written to send verification links and verify emails. To register the necessary routes for this controller, write the below routes in the routes/web.php file.

Auth::routes(["verify" => true]);

Next, to protect our routes from unverified account add middleware to it as follows:

Route::get("profile", function () { return "

This is profile page

"; })->middleware("verified");

You will have control of where to redirect the user after verification. If you open the Auth\VerificationController file you will find the variable $redirectTo which will use for redirection. Change this route as per your requirement.

Protected $redirectTo = "/home";

Finally, run the migration command:

Php artisan migrate

User Login and Registration

At this stage, we are ready to test the user login and registration system. For this to work, your application should able to send emails. You can use the Gmail SMTP server to send emails. For more details, please read our article .

Start the local development server using the command:

Php artisan serve

Now, you should able to see your registration page at http://localhost:8000/register

Fill the form and you will get the verification link on your account as follows:

Please note, Laravel allows us to login to our account even if we did not verify account yet. But we can’t access protected route. Remember we have added middleware for one of our route profile . Now without verifying your account if you try to visit the http://localhost:8000/profile , it will redirect to the http://localhost:8000/email/verify URL.

Go ahead and verify your account. You will see email_verified_at column in the users table has DateTime added. It means you have verified your account successfully. Now you should able to access even protected routes.

We hope you understand how to use user registration And login system in Laravel. You may also like to read our article .

Laravel requires Composer to manage the project dependencies. So before installing Laravel, make sure you have Composer installed on your system. In case you are hearing about Composer for the first time, it"s a dependency management tool for php similar to node"s npm.

To install Composer on your machine, check this post:

Installing Laravel on Windows:

Follow the below steps to install laravel on windows machine. No matter you have xampp/wamp stack, it works for both. On WAMP, make sure to install laravel on "www" folder and on XAMPP, obviously the "htdocs".

STEP-1) Open "htdocs" folder on XAMPP, hold SHIFT key and right click on the folder, and choose "open command window here". Alternatively, you can open command window and change directory to "xampp/htdocs".

STEP-2) Enter the following command.

Composer create-project laravel/laravel my_laravel_site --prefer-dist

Here "my_laravel_site" is the folder name where laravel files will be installed. Change this to your liking.

STEP-3) Now it"s time to be patient as laravel installation is going to take some time.

STEP-4) Once installed, change directory to "my_laravel_site" (cd "my_laravel_site") on the command prompt and enter the below command.

Php artisan serve

STEP-5) This will show a message something like, "Laravel development server started:" along with an url.

STEP-6) Copy and paste the url on the browser. If things go right, you"d see the laravel welcome screen.

STEP-7) Done! You have successfully installed laravel on windows machine and ready to go with.

Setting Application Key:

Laravel requires little configuration after installation. It requires you to set the application key. This is a random string of 32 characters long used for encrypting session and other sensitive data. Usually this will be set automatically when you install laravel via composer or laravel installer.

In case it"s not set, you have to do it manually. First make sure to rename the ".env.example" file to ".env" on your application root. Then open command prompt and change to the laravel project folder. Now run the below command to generate the key.

Php artisan key:generate

Copy this generated key to the APP_KEY variable on ".env" file. Save and you are done.

Installing Specific Laravel Version:

The above given method will make composer to download and install the latest version of laravel. If you want to install earlier versions of laravel on your machine, make sure to include the respective version number on create-project command.

Composer create-project laravel/laravel=5.4 your-project-name --prefer-dist Read Also:

Likewise you can easily install laravel using composer on windows . I hope you find this tutorial useful. Please share it on your social circle if you like it.