I'm trying to create a simple to use API with php but I have run into multiple problems. I'm working on an user api that does basic CRUD stuff.
If I do a POST request with cURL to my user api (user.php), a new session id is used during the execution of user.php.
So in order to combat that I tried to send the current session id with the POST request to user.php. The problem I have right now is that after setting the id with session_id($_POST['session'])
and then starting my session with session_start()
my server will get stuck on executing that code and will eventually throw an Internal Server Error 500.
I tried to get my server to show me what the error is with ini_set('display_errors', 1);
and an .htaccess file (content: php_flag display_errors 1
) but to no avail, the server just gets stuck.
test.php
<?php
session_start();
// Check for available session
if (!isset($_SESSION['id'])) {
header('location: index.php');
} else {
// Initialize cURL
$curl = curl_init();
// Set parameters for POST request
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://localhost/api/user.php',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query([
'session' => session_id(),
'username' => 'testuser',
'password' => 'testalot',
'name' => 'testuser',
'isAdmin' => 0
])
]);
// Execute POST request
$response = curl_exec($curl);
/* <<< Doesn't get beyond this point. */
// Dump JSON
var_dump($response);
// Close cURL session
curl_close($curl);
}
?>
user.php
<?php
// Declare integer checking function
function isInteger($input) {
return ctype_digit(strval($input));
}
// Declare result object
$output = ['success' => false, 'data' => [], 'error' => ''];
// Action on POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Check if session id was sent
if (!empty($_POST['session'])) {
// Set session id
session_id($_POST['session']);
// Start session with received session id
session_start();
/* <<< Freezes at this point. */
// Check session for available user id
if (isset($_SESSION['id'])) {
// Only admins are allowed to execute POST requests
if ($_SESSION['isAdmin'] == 1) {
// ... more code ...
I'd of course also use a different method of accessing my API that does not require me to send the current session id, if there is any. Any ideas?
UPDATE:
Look @Neok's comment under my question. That is the solution. Just pointing it out for others that might have the same issue.