1"use strict";(globalThis.webpackChunksimple_jwt_login_website=globalThis.webpackChunksimple_jwt_login_website||[]).push([[4355],{99814(e,n,t){t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>d,frontMatter:()=>a,metadata:()=>s,toc:()=>l});const s=JSON.parse('{"id":"code_examples/php/Register_and_get_token","title":"Register a WordPress user with PHP and get the jwt","description":"Introduction","source":"@site/versioned_docs/version-3.0.0/code_examples/php/Register_and_get_token.md","sourceDirName":"code_examples/php","slug":"/code_examples/php/register_and_get_jwt","permalink":"/docs/3.0.0/code_examples/php/register_and_get_jwt","draft":false,"unlisted":false,"editUrl":"https://github.com/simple-jwt-login/website/tree/main/versioned_docs/version-3.0.0/code_examples/php/Register_and_get_token.md","tags":[],"version":"3.0.0","sidebarPosition":1,"frontMatter":{"slug":"/code_examples/php/register_and_get_jwt","title":"Register a WordPress user with PHP and get the jwt","sidebar_position":1,"author":"Nicu Micle","author_url":"https://github.com/nicumicle"},"sidebar":"tutorialSidebar","previous":{"title":"Code Examples","permalink":"/docs/3.0.0/code-examples/"}}');var r=t(74848),o=t(28453);const a={slug:"/code_examples/php/register_and_get_jwt",title:"Register a WordPress user with PHP and get the jwt",sidebar_position:1,author:"Nicu Micle",author_url:"https://github.com/nicumicle"},i=void 0,c={},l=[{value:"Introduction",id:"introduction",level:2},{value:"Step 1: Register a WordPress user",id:"step-1-register-a-wordpress-user",level:2},{value:"Step 2: Obtain a JWT",id:"step-2-obtain-a-jwt",level:2},{value:"Step 3: Use the JWT to create a WordPress post",id:"step-3-use-the-jwt-to-create-a-wordpress-post",level:2},{value:"Full example",id:"full-example",level:2}];function p(e){const n={admonition:"admonition",code:"code",h2:"h2",li:"li",ol:"ol",p:"p",pre:"pre",strong:"strong",...(0,o.R)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(n.h2,{id:"introduction",children:"Introduction"}),"\n",(0,r.jsx)(n.p,{children:"This example walks through a complete PHP integration with Simple-JWT-Login: registering a new WordPress user, obtaining a JWT for that user, and using the token to create a WordPress post via the REST API."}),"\n",(0,r.jsx)(n.p,{children:"It covers the three most common steps in a headless WordPress workflow:"}),"\n",(0,r.jsxs)(n.ol,{children:["\n",(0,r.jsxs)(n.li,{children:[(0,r.jsx)(n.strong,{children:"Register"})," - create a new user account"]}),"\n",(0,r.jsxs)(n.li,{children:[(0,r.jsx)(n.strong,{children:"Authenticate"})," - exchange credentials for a JWT"]}),"\n",(0,r.jsxs)(n.li,{children:[(0,r.jsx)(n.strong,{children:"Use the JWT"})," - call a protected endpoint"]}),"\n"]}),"\n",(0,r.jsx)(n.p,{children:"For this example, we can create a helper function, that will do the actual call:"}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{className:"language-php",children:"<?php\n\n/**\n * @param $method string Can be one of the following: GET, POST, PUT, DELETE\n * @param $endpoint string Endpoint where we will do the call\n * @param $data array Parameters that needs to be sent to the endpoint\n * @param $headers array Request headers\n * @return string\n * @throws \\Exception\n *\n */\nfunction call($method, $endpoint, $data = array(), $headers = array())\n{\n // Initialize cURL session\n $ch = curl_init();\n\n // Set the cURL options\n curl_setopt($ch, CURLOPT_URL, $endpoint);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));\n curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));\n curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);\n\n // Execute cURL session and get the result\n $result = curl_exec($ch);\n\n // Check for cURL errors\n if (curl_errno($ch)) {\n throw new \\Exception(curl_error($ch));\n }\n\n // Close cURL session\n curl_close($ch);\n\n return $result;\n}\n"})}),"\n",(0,r.jsx)(n.h2,{id:"step-1-register-a-wordpress-user",children:"Step 1: Register a WordPress user"}),"\n",(0,r.jsx)(n.admonition,{type:"note",children:(0,r.jsx)(n.p,{children:'Please note that, in order to be able to register a new user, you need have "Allow Register: yes" in the plugin settings.'})}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{className:"language-php",children:'<?php\n$domain = "http://localhost:88";
1\n$headers = array(\n "Content-Type: application/json"\n);\n$data = array(\n "email" => "test". random_int(0, 10000). "@localhost.com",\n "password" => "my secret password",\n "first_name" => "my firstname",\n "last_name" => "my last name",\n);\n\ntry{\n // Step 1: Register User\n $result = call("POST", $domain . "?rest_route=/simple-jwt-login/v1/users", $data, $headers);\n $responseJSON = json_decode($result, true);\n if ($responseJSON === false) {\n throw new \\Exception("Response is not a JSON:", $result);\n }\n\n // In case of error, success will be false\n if (!$responseJSON[\'success\']) {\n throw new \\Exception($responseJSON[\'data\'][\'message\']);\n }\n\n $userID = $responseJSON[\'id\'];\n echo "Your new user ID is: " . $userID . PHP_EOL;\n} catch (\\Exception $exception) {\n // Unable to do the call\n echo "Error while registering the user: ". $exception->getMessage() . PHP_EOL;\n}\n'})}),"\n",(0,r.jsx)(n.h2,{id:"step-2-obtain-a-jwt",children:"Step 2: Obtain a JWT"}),"\n",(0,r.jsx)(n.admonition,{type:"note",children:(0,r.jsx)(n.p,{children:'Please note that, in order to use the Authentication endpoint, you need have "Allow Authentication: yes" in the plugin settings.'})}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{className:"language-php",children:'<?php\n$domain = "http://localhost:88";\n$headers = array(\n "Content-Type: application/json"\n);\n$data = array (\n "email" => "[email protected]",\n "password" => "my secret password",\n);\n\ntry{\n $result = call("POST", $domain . "?rest_route=/simple-jwt-login/v1/auth", $data, $headers);\n $responseJSON = json_decode($result, true);\n if ($responseJSON === false) {\n throw new \\Exception("Auth response is not a JSON:", $result);\n }\n // In case of error, success will be false\n if (!isset($responseJSON[\'success\']) || !$responseJSON[\'success\']) {\n $error = isset($responseJSON[\'data\'][\'message\'])\n ? $responseJSON[\'data\'][\'message\']\n : "Error while getting the JWT";\n throw new \\Exception($error);\n }\n\n if (!isset($responseJSON[\'data\'][\'jwt\'])) {\n throw new \\Exception("The JWT is missing from API Response.");\n }\n // Your new JWT that you can use in other endpoints\n $jwt = $responseJSON[\'data\'][\'jwt\'];\n echo "Your new token is: ". $jwt;\n}catch (\\Exception $exception) {\n echo "Error while trying to get the token: ". $exception->getMessage(). PHP_EOL;\n}\n'})}),"\n",(0,r.jsx)(n.h2,{id:"step-3-use-the-jwt-to-create-a-wordpress-post",children:"Step 3: Use the JWT to create a WordPress post"}),"\n",(0,r.jsx)(n.admonition,{type:"note",children:(0,r.jsx)(n.p,{children:'In order to use the JWT on all endpoint, you need to enable "All WordPress endpoints checks for JWT authentication" from the plugin General Settings.'})}),"\n",(0,r.jsx)(n.p,{children:"In this example, we will create a new WordPress post:"}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{className:"language-php",children:'<?php\n$domain = "http://localhost:88"; \n$jwt = "..."; // Replace with the JWT you obtained in the previous step\n$headers = array(\n "Content-type: application/json",\n "Authorization: " . $jwt\n);\n// New Post parameters\n$data = array(\n "title" => "Post Title",\n "excerpt" => "test",\n);\ntry {\n $result = call("POST", $domain . "?rest_route=/wp/v2/posts", $data, $headers);\n $responseJSON = json_decode($result, true);\n\n // Final Step: Post create response\n echo "Post create Response: " . print_r($responseJSON, true) . PHP_EOL;\n} catch (\\Exception $exception){\n echo "Unable to create post:" . $exception->getMessage();\n}\n'})}),"\n",(0,r.jsx)(n.h2,{id:"full-example",children:"Full example"}),"\n",(0,r.jsx)(n.p,{children:"The script below combines all three steps: register, authenticate, and create a post."}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{className:"language-php",children:'<?php\n\n/**\n * @param $method string Can be one of the following: GET, PO
1ST, PUT, DELETE\n * @param $endpoint string Endpoint where we will do the call\n * @param $data array Parameters that needs to be sent to the endpoint\n * @param $headers array Request headers\n * @return string\n * @throws \\Exception\n *\n */\nfunction call($method, $endpoint, $data = array(), $headers = array())\n{\n // Initialize cURL session\n $ch = curl_init();\n\n // Set the cURL options\n curl_setopt($ch, CURLOPT_URL, $endpoint);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));\n curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));\n curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);\n\n // Execute cURL session and get the result\n $result = curl_exec($ch);\n\n // Check for cURL errors\n if (curl_errno($ch)) {\n throw new \\Exception(curl_error($ch));\n }\n\n // Close cURL session\n curl_close($ch);\n\n return $result;\n}\n\n$domain = "http://localhost:88";\n$headers = array(\n "Content-Type: application/json"\n);\n$data = array(\n "email" => "test". random_int(0, 10000). "@localhost.com",\n "password" => "my secret password",\n "first_name" => "my firstname",\n "last_name" => "my last name",\n);\n\ntry {\n // Step 1: Register User\n $result = call("POST", $domain . "?rest_route=/simple-jwt-login/v1/users", $data, $headers);\n $responseJSON = json_decode($result, true);\n if ($responseJSON === false) {\n throw new \\Exception("Response is not a JSON:", $result);\n }\n\n // In case of error, success will be false\n if (!$responseJSON[\'success\']) {\n throw new \\Exception($responseJSON[\'data\'][\'message\']);\n }\n\n $userID = $responseJSON[\'id\'];\n\n // Step 2: Get a JWT\n $result = call("POST", $domain . "?rest_route=/simple-jwt-login/v1/auth", $data, $headers);\n $responseJSON = json_decode($result, true);\n if ($responseJSON === false) {\n throw new \\Exception("Auth response is not a JSON:", $result);\n }\n // In case of error, success will be false\n if (!isset($responseJSON[\'success\']) || !$responseJSON[\'success\']) {\n $error = isset($responseJSON[\'data\'][\'message\'])\n ? $responseJSON[\'data\'][\'message\']\n : "Error while getting the JWT";\n throw new \\Exception($error);\n }\n\n if (!isset($responseJSON[\'data\'][\'jwt\'])) {\n throw new \\Exception("The JWT is missing from API Response.");\n }\n // Your new JWT that you can use in other endpoints\n $jwt = $responseJSON[\'data\'][\'jwt\'];\n\n // Step 3: Create a new WordPress post\n $headers = array(\n "Content-type: application/json",\n "Authorization: " . $jwt\n );\n $data = array(\n "title" => "Post Title",\n "excerpt" => "test",\n );\n\n $result = call("POST", $domain . "?rest_route=/wp/v2/posts", $data, $headers);\n $responseJSON = json_decode($result, true);\n\n // Final Step: Post have been created\n echo "Post have been created: " . print_r($responseJSON, true) . PHP_EOL;\n\n} catch (\\Exception $exception) {\n echo "There was an error: " . $exception->getMessage() . PHP_EOL;\n}\n'})})]})}function d(e={}){const{wrapper:n}={...(0,o.R)(),...e.components};return n?(0,r.jsx)(n,{...e,children:(0,r.jsx)(p,{...e})}):p(e)}},28453(e,n,t){t.d(n,{R:()=>a,x:()=>i});var s=t(96540);const r={},o=s.createContext(r);function a(e){const n=s.useContext(o);return s.useMemo(function(){return"function"==typeof e?e(n):{...n,...e}},[n,e])}function i(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(r):e.components||r:a(e.components),s.createElement(o.Provider,{value:n},e.children)}}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.