Submitting Form Data to an API Using POST Method with Bearer Token in PHP
By Webotapp Academyโข
<p data-start=\"462\" data-end=\"723\">In modern web development, it's common to interact with APIs by sending data via the <code data-start=\"547\" data-end=\"553\">POST</code> method. When dealing with secure APIs, authentication is often required using a <strong data-start=\"634\" data-end=\"650\">Bearer Token</strong> โ a security mechanism to ensure only authorized requests are processed.</p>\n<p data-start=\"725\" data-end=\"760\">This guide will demonstrate how to:</p>\n\n<ul data-start=\"762\" data-end=\"1046\">\n <li data-start=\"762\" data-end=\"789\">\n<p data-start=\"764\" data-end=\"789\">Capture data from a form.</p>\n</li>\n <li data-start=\"790\" data-end=\"843\">\n<p data-start=\"792\" data-end=\"843\">Send the data securely via <code data-start=\"819\" data-end=\"825\">POST</code> using PHP <code data-start=\"836\" data-end=\"842\">cURL</code>.</p>\n</li>\n <li data-start=\"844\" data-end=\"888\">\n<p data-start=\"846\" data-end=\"888\">Include a Bearer Token for authentication.</p>\n</li>\n <li data-start=\"889\" data-end=\"964\">\n<p data-start=\"891\" data-end=\"964\">Parse the API response and redirect the user based on success or failure.</p>\n</li>\n <li data-start=\"965\" data-end=\"1046\">\n<p data-start=\"967\" data-end=\"1046\">Handle the request on the <strong data-start=\"993\" data-end=\"1008\">server-side</strong> (<code data-start=\"1010\" data-end=\"1022\">insert.php</code>) with token validation.</p>\n</li>\n</ul>\n\n<hr data-start=\"1048\" data-end=\"1051\" />\n\n<h2 data-start=\"1053\" data-end=\"1075\">โ
Use Case Overview</h2>\n<p data-start=\"1077\" data-end=\"1280\">Imagine you have a form where a parent submits their name, associated student, and mobile number. Upon submission, the data is sent to an API endpoint (<code data-start=\"1229\" data-end=\"1241\">insert.php</code>) that stores the information securely.</p>\n\n\n<hr data-start=\"1282\" data-end=\"1285\" />\n\n<h2 data-start=\"1287\" data-end=\"1316\">๐ What is a Bearer Token?</h2>\n<p data-start=\"1318\" data-end=\"1508\">A <strong data-start=\"1320\" data-end=\"1336\">Bearer Token</strong> is a security token included in the <code data-start=\"1373\" data-end=\"1388\">Authorization</code> header of HTTP requests. It acts like a password that identifies the requester and gives access to protected resources.</p>\n<p data-start=\"1510\" data-end=\"1518\">Example:</p>\n\n<div class=\"contain-inline-size rounded-2xl relative bg-token-sidebar-surface-primary\">\n<div class=\"overflow-y-auto p-4\" dir=\"ltr\"><code class=\"whitespace-pre!\"><span class=\"hljs-section\">Authorization: Bearer YOUR_SECRET_TOKEN</span>\n</code></div>\n</div>\n\n<hr data-start=\"1568\" data-end=\"1571\" />\n\n<h2 data-start=\"1573\" data-end=\"1643\">๐ฅ๏ธ Step 1: Client-Side Code to Send POST Request with Bearer Token</h2>\n<div class=\"contain-inline-size rounded-2xl relative bg-token-sidebar-surface-primary\">\n<div class=\"overflow-y-auto p-4\" dir=\"ltr\">\n<div>\n<div><?php</div>\n<div>if (isset($_POST['ins_stu'])) {</div>\n<div>$name=$_POST['stu_name'];</div>\n<div>$class=$_POST['stu_class'];</div>\n<div>$roll=$_POST['stu_roll'];</div>\n<div>$bearer_token='123345';</div>\n<div>// Basic validation</div>\n<div>if(empty($name)){</div>\n<div>echo\"<script> window.alert('Student name cannot be blank') </script>\";</div>\n<div>exit;</div>\n<div>}</div>\n<div>if(empty($class)){</div>\n<div>echo\"<script> window.alert('Student class cannot be blank') </script>\";</div>\n<div>exit;</div>\n<div>}</div>\n<div>if(empty($roll)){</div>\n<div>echo\"<script> window.alert('Student roll cannot be blank') </script>\";</div>\n<div>exit;</div>\n<div>}</div>\n<div>// Data to send</div>\n<div>$data=[</div>\n<div>'student_name'=>$name,</div>\n<div>'student_class'=>$class,</div>\n<div>'student_roll'=>$roll,</div>\n<div>];</div>\n<div>// CHANGE THIS TO YOUR ACTUAL API URL</div>\n<div>$api_url='https://yourdomain.com/your-api-file.php';// Replace with your actual API URL</div>\n<div></div>\n<div>$ch=curl_init($api_url);</div>\n<div>curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);</div>\n<div>curl_setopt($ch, CURLOPT_POST, true);</div>\n<div>curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));</div>\n<div>curl_setopt($ch, CURLOPT_TIMEOUT,30);</div>\n<div></div>\n<div>// SSL Fix - Skip SSL verification (TEMPORARY SOLUTION)</div>\n<div>curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);</div>\n<div>curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);</div>\n<div>// Add Bearer Token to header</div>\n<div>curl_setopt($ch, CURLOPT_HTTPHEADER,[</div>\n<div>\"Authorization: Bearer $bearer_token\",</div>\n<div>\"Content-Type: application/x-www-form-urlencoded\"</div>\n<div>]);</div>\n<div>// Execute and capture response</div>\n<div>$response=curl_exec($ch);</div>\n<div>$httpCode=curl_getinfo($ch, CURLINFO_HTTP_CODE);</div>\n<div></div>\n<div>// Check for curl errors</div>\n<div>if(curl_error($ch)){</div>\n<div>echo\"CURL Error: \".curl_error($ch);</div>\n<div>curl_close($ch);</div>\n<div>exit;</div>\n<div>}</div>\n<div></div>\n<div>curl_close($ch);</div>\n<div>// Display response</div>\n<div>echo\"<h3>API Response (HTTP Code: $httpCode):</h3>\";</div>\n<div>echo\"<pre>\";</div>\n<div></div>\n<div>// Try to decode JSON response</div>\n<div>$result=json_decode($response, true);</div>\n<div>if($result){</div>\n<div>print_r($result);</div>\n<div>}else{</div>\n<div>// If not JSON, show raw response</div>\n<div>echohtmlspecialchars($response);</div>\n<div>}</div>\n<div>echo\"</pre>\";</div>\n<div>}</div>\n<div>?></div>\n</div>\n</div>\n</div>\n\n<hr data-start=\"2879\" data-end=\"2882\" />\n\n<h2 data-start=\"2884\" data-end=\"2973\">๐ ๏ธ Step 2: Server-Side API Code (<code data-start=\"2921\" data-end=\"2933\">insert.php</code>) to Handle Bearer Token and Insert Data</h2>\n<p data-start=\"2975\" data-end=\"3096\">Hereโs a sample version of <code data-start=\"3002\" data-end=\"3014\">insert.php</code> that receives POST data, validates the Bearer Token, and returns a JSON response:</p>\n\n<div class=\"contain-inline-size rounded-2xl relative bg-token-sidebar-surface-primary\">\n<div class=\"overflow-y-auto p-4\" dir=\"ltr\">\n\n<?php\n// Define your valid Bearer token\n$valid_token = \"YOUR_SECRET_TOKEN\";\n\n// Check Authorization Header\n$headers = apache_request_headers();\nif (!isset($headers['Authorization'])) {\nhttp_response_code(401);\necho json_encode(['status' => 'error', 'message' => 'Authorization header missing']);\nexit();\n}\n\n// Extract and verify Bearer Token\n$auth_header = $headers['Authorization'];\nif (strpos($auth_header, 'Bearer ') !== 0) {\nhttp_response_code(401);\necho json_encode(['status' => 'error', 'message' => 'Invalid Authorization format']);\nexit();\n}\n\n$received_token = trim(str_replace('Bearer', '', $auth_header));\nif ($received_token !== $valid_token) {\nhttp_response_code(403);\necho json_encode(['status' => 'error', 'message' => 'Invalid token']);\nexit();\n}\n\n// Get POST Data\n$parent_name = $_POST['parent_name'] ?? '';\n$parent_student = $_POST['parent_student'] ?? '';\n$parent_mobile = $_POST['parent_mobile'] ?? '';\n\n// Validation (simplified)\nif (empty($parent_name) || empty($parent_student) || empty($parent_mobile)) {\nhttp_response_code(400);\necho json_encode(['status' => 'error', 'message' => 'Missing required fields']);\nexit();\n}\n\n// You can insert this data into your database here\n// For example purposes, assume insertion is successful\n\nhttp_response_code(200);\necho json_encode([\n'status' => 'success',\n'message' => 'Parent data inserted successfully'\n]);\n?>\n\n</div>\n</div>\n\n<hr data-start=\"4543\" data-end=\"4546\" />\n\n<h2 data-start=\"4548\" data-end=\"4572\">๐ Points to Remember</h2>\n<ul data-start=\"4574\" data-end=\"4913\">\n <li data-start=\"4574\" data-end=\"4683\">\n<p data-start=\"4576\" data-end=\"4683\">Always <strong data-start=\"4583\" data-end=\"4614\">sanitize and validate input</strong> on both client and server sides to prevent malicious data injection.</p>\n</li>\n <li data-start=\"4684\" data-end=\"4777\">\n<p data-start=\"4686\" data-end=\"4777\">Use <strong data-start=\"4690\" data-end=\"4699\">HTTPS</strong> for all API calls to protect sensitive information like tokens and user data.</p>\n</li>\n <li data-start=\"4778\" data-end=\"4838\">\n<p data-start=\"4780\" data-end=\"4838\">Never expose your Bearer Token in frontend (HTML/JS) code.</p>\n</li>\n <li data-start=\"4839\" data-end=\"4913\">\n<p data-start=\"4841\" data-end=\"4913\">Log all failed attempts for auditing if you're building a secure system.</p>\n</li>\n</ul>\n\n<hr data-start=\"4915\" data-end=\"4918\" />\n\n<h2 data-start=\"4920\" data-end=\"4944\">โ
Sample API Response</h2>\n<div class=\"contain-inline-size rounded-2xl relative bg-token-sidebar-surface-primary\">\n<div class=\"flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between h-9 bg-token-sidebar-surface-primary select-none rounded-t-2xl\"></div>\n<div class=\"overflow-y-auto p-4\" dir=\"ltr\"><code class=\"whitespace-pre! language-json\"><span class=\"hljs-punctuation\">{</span>\n<span class=\"hljs-attr\">\"status\"</span><span class=\"hljs-punctuation\">:</span> <span class=\"hljs-string\">\"success\"</span><span class=\"hljs-punctuation\">,</span>\n<span class=\"hljs-attr\">\"message\"</span><span class=\"hljs-punctuation\">:</span> <span class=\"hljs-string\">\"Parent data inserted successfully\"</span>\n<span class=\"hljs-punctuation\">}</span>\n</code></div>\n</div>\n<p data-start=\"5035\" data-end=\"5052\">In case of error:</p>\n\n<div class=\"contain-inline-size rounded-2xl relative bg-token-sidebar-surface-primary\">\n<div class=\"flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between h-9 bg-token-sidebar-surface-primary select-none rounded-t-2xl\"></div>\n<div class=\"overflow-y-auto p-4\" dir=\"ltr\"><code class=\"whitespace-pre! language-json\"><span class=\"hljs-punctuation\">{</span>\n<span class=\"hljs-attr\">\"status\"</span><span class=\"hljs-punctuation\">:</span> <span class=\"hljs-string\">\"error\"</span><span class=\"hljs-punctuation\">,</span>\n<span class=\"hljs-attr\">\"message\"</span><span class=\"hljs-punctuation\">:</span> <span class=\"hljs-string\">\"Invalid token\"</span>\n<span class=\"hljs-punctuation\">}</span>\n</code></div>\n</div>\n\n<hr data-start=\"5120\" data-end=\"5123\" />\n\n<h2 data-start=\"5125\" data-end=\"5141\">๐ Conclusion</h2>\n<p data-start=\"5143\" data-end=\"5458\">By implementing Bearer Token authentication and using <code data-start=\"5197\" data-end=\"5203\">cURL</code> to securely send <code data-start=\"5221\" data-end=\"5227\">POST</code> data, you can build secure and responsive backend services. This is a vital skill for API integration in any web-based application. The example above demonstrates both sending and receiving sides to get you up and running quickly.</p>\n<p data-start=\"5460\" data-end=\"5551\" data-is-last-node=\"\" data-is-only-node=\"\">Let me know if you want the database insert code as well or need token expiration handling.</p>