Uncategorized

Submitting Form Data to an API Using POST Method with Bearer Token in PHP

In modern web development, it’s common to interact with APIs by sending data via the POST method. When dealing with secure APIs, authentication is often required using a Bearer Token — a security mechanism to ensure only authorized requests are processed.

This guide will demonstrate how to:

  • Capture data from a form.

  • Send the data securely via POST using PHP cURL.

  • Include a Bearer Token for authentication.

  • Parse the API response and redirect the user based on success or failure.

  • Handle the request on the server-side (insert.php) with token validation.


✅ Use Case Overview

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 (insert.php) that stores the information securely.


🔐 What is a Bearer Token?

A Bearer Token is a security token included in the Authorization header of HTTP requests. It acts like a password that identifies the requester and gives access to protected resources.

Example:

Authorization: Bearer YOUR_SECRET_TOKEN

🖥️ Step 1: Client-Side Code to Send POST Request with Bearer Token

<?php
if (isset($_POST[‘ins_stu’])) {
$name=$_POST[‘stu_name’];
$class=$_POST[‘stu_class’];
$roll=$_POST[‘stu_roll’];
$bearer_token=’123345′;
// Basic validation
if(empty($name)){
echo”<script> window.alert(‘Student name cannot be blank’) </script>”;
exit;
}
if(empty($class)){
echo”<script> window.alert(‘Student class cannot be blank’) </script>”;
exit;
}
if(empty($roll)){
echo”<script> window.alert(‘Student roll cannot be blank’) </script>”;
exit;
}
// Data to send
$data=[
‘student_name’=>$name,
‘student_class’=>$class,
‘student_roll’=>$roll,
];
// CHANGE THIS TO YOUR ACTUAL API URL
$api_url=’https://yourdomain.com/your-api-file.php’;// Replace with your actual API URL
$ch=curl_init($api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
curl_setopt($ch, CURLOPT_TIMEOUT,30);
// SSL Fix – Skip SSL verification (TEMPORARY SOLUTION)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// Add Bearer Token to header
curl_setopt($ch, CURLOPT_HTTPHEADER,[
“Authorization: Bearer $bearer_token”,
“Content-Type: application/x-www-form-urlencoded”
]);
// Execute and capture response
$response=curl_exec($ch);
$httpCode=curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Check for curl errors
if(curl_error($ch)){
echo”CURL Error: “.curl_error($ch);
curl_close($ch);
exit;
}
curl_close($ch);
// Display response
echo”<h3>API Response (HTTP Code: $httpCode):</h3>”;
echo”<pre>”;
// Try to decode JSON response
$result=json_decode($response, true);
if($result){
print_r($result);
}else{
// If not JSON, show raw response
echohtmlspecialchars($response);
}
echo”</pre>”;
}
?>

🛠️ Step 2: Server-Side API Code (insert.php) to Handle Bearer Token and Insert Data

Here’s a sample version of insert.php that receives POST data, validates the Bearer Token, and returns a JSON response:

<?php
// Define your valid Bearer token
$valid_token = “YOUR_SECRET_TOKEN”;

// Check Authorization Header
$headers = apache_request_headers();
if (!isset($headers[‘Authorization’])) {
http_response_code(401);
echo json_encode([‘status’ => ‘error’, ‘message’ => ‘Authorization header missing’]);
exit();
}

// Extract and verify Bearer Token
$auth_header = $headers[‘Authorization’];
if (strpos($auth_header, ‘Bearer ‘) !== 0) {
http_response_code(401);
echo json_encode([‘status’ => ‘error’, ‘message’ => ‘Invalid Authorization format’]);
exit();
}

$received_token = trim(str_replace(‘Bearer’, ”, $auth_header));
if ($received_token !== $valid_token) {
http_response_code(403);
echo json_encode([‘status’ => ‘error’, ‘message’ => ‘Invalid token’]);
exit();
}

// Get POST Data
$parent_name = $_POST[‘parent_name’] ?? ”;
$parent_student = $_POST[‘parent_student’] ?? ”;
$parent_mobile = $_POST[‘parent_mobile’] ?? ”;

// Validation (simplified)
if (empty($parent_name) || empty($parent_student) || empty($parent_mobile)) {
http_response_code(400);
echo json_encode([‘status’ => ‘error’, ‘message’ => ‘Missing required fields’]);
exit();
}

// You can insert this data into your database here
// For example purposes, assume insertion is successful

http_response_code(200);
echo json_encode([
‘status’ => ‘success’,
‘message’ => ‘Parent data inserted successfully’
]);
?>


📌 Points to Remember

  • Always sanitize and validate input on both client and server sides to prevent malicious data injection.

  • Use HTTPS for all API calls to protect sensitive information like tokens and user data.

  • Never expose your Bearer Token in frontend (HTML/JS) code.

  • Log all failed attempts for auditing if you’re building a secure system.


✅ Sample API Response

{
"status": "success",
"message": "Parent data inserted successfully"
}

In case of error:

{
"status": "error",
"message": "Invalid token"
}

🔚 Conclusion

By implementing Bearer Token authentication and using cURL to securely send POST 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.

Let me know if you want the database insert code as well or need token expiration handling.

Leave a Reply

Your email address will not be published. Required fields are marked *