1

I'm working on a php page that compare information received by a client with information in a database, but I'm not so good in php and I don't know what I did wrong, I always get response code 500, internal server error. Here is the code:

<?php
/**
 * @var object $payload The payload sent from the client
 */
$payload = json_decode(file_get_contents("php://input"), true);
/**
 * @var object $user_name The username sent by the client
 * @var object $user_name The password sent by the client
 */
$user_name = $payload['username'];
$user_password = $payload['password'];
$response = null;
$responseCode = 200;
$result_row = null;
/**
 * The form representing a positive response
 */
class Response {
    public $accessToken = "";
    public $availableProfiles = "";
    public $selectedProfile = "";
}
/**
 * The form representing a negative response
 */
class negativeResponse {
    public $error = "";
    public $errorMessage = "";
}
/**
 * @var object $db_connection The database connection
 */
$db_connection = null;
try {
    $db_connection = new PDO('mysql:host=localhost;dbname=launcher_login;charset=utf8', 'myUser', 'myPass');
} catch (PDOException $e) {
    //Catch exception
}

// user can login with his username or his email address.
// if user has not typed a valid email address, we try to identify him with his user_name
if (!filter_var($user_name, FILTER_VALIDATE_EMAIL)) {
    // database query, getting all the info of the selected user
    $query_user = $this->db_connection->prepare('SELECT * FROM users WHERE user_name = :user_name');
    $query_user->bindValue(':user_name', $user_name, PDO::PARAM_STR);
    $query_user->execute();
    // get result row (as an object)

    $result_row = $query_user->fetchObject();
// if user has typed a valid email address, we try to identify him with his user_email
} else  {
    // database query, getting all the info of the selected user
    $query_user = $db_connection->prepare('SELECT * FROM users WHERE user_email = :user_email');
    $query_user->bindValue(':user_email', trim($user_name), PDO::PARAM_STR);
    $query_user->execute();
    // get result row (as an object)
    $result_row = $query_user->fetchObject();
}

// if this user not exists
if (!isset($result_row->user_id)) {
    $response = new negativeResponse();
    $response->error = "Credenziali Invalide";
    $response->errorMessage = "Non esiste un account con questa combinazione nome utente/password";
    $responseCode=201;
// if the password isn't correct
} else if (!password_verify($user_password, $result_row->user_password_hash)) {
    $response = new negativeResponse();
    $response->error = "Credenziali Invalide";
    $response->errorMessage = "Non esiste un account con questa combinazione nome utente/password";
    $responseCode=201;
// if the account exists but it isn't activated
} else if ($result_row->user_active != 1) {
    $response = new negativeResponse();
    $response->error = "Account non attivo";
    $response->errorMessage = "Devi attivare l'account! Controlla l'email inserita";
    $responseCode=201;
} else {
    $response = new Response();
    $response->accessToken = hash('md5', $user_name);
    $response->availableProfiles = array(array('id' => hash('md5', $user_name), 'name' => $user_name, 'legacy' => true));
    $response->selectedProfile = array('id' => hash('md5', $user_name), 'name' => $user_name, 'legacy' => true);
}
echo json_encode($response);
http_response_code($responseCode);

My table is created with this query:

CREATE TABLE IF NOT EXISTS `launcher-login`.`users` (
 `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing user_id of each user, unique index',
 `user_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s name, unique',
 `user_password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s password in salted and hashed format',
 `user_email` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s email, unique',
 `user_active` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user''s activation status',
 `user_activation_hash` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s email verification hash string',
 `user_password_reset_hash` char(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s password reset code',
 `user_password_reset_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of the password reset request',
 `user_rememberme_token` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s remember-me cookie token',
 `user_failed_logins` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user''s failed login attemps',
 `user_last_failed_login` int(10) DEFAULT NULL COMMENT 'unix timestamp of last failed login attempt',
 `user_registration_datetime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
 `user_registration_ip` varchar(39) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0.0.0.0',
 PRIMARY KEY (`user_id`),
 UNIQUE KEY `user_name` (`user_name`),
 UNIQUE KEY `user_email` (`user_email`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='user data';

EDIT: I feel stupid, the error was $query_user = $this->db_connection->prepare('SELECT * FROM users WHERE user_name = :user_name');. I was using this outside of a class, now I'm working on the client part, thank you all for help

5
  • Start by writing the contents of $payload out so you know what is being sent to the script. Try file_put_contents('dump.txt', print_r($payload,true))' then look at dump.txt, maybe add it to the question Commented May 2, 2015 at 20:05
  • Could you output the respective error from logs? Commented May 2, 2015 at 20:05
  • this can be resolved extremely quick by looking at the error log as it'll tell you the exact line your code is blowing up on. Commented May 2, 2015 at 20:43
  • A few notes as well. 1) http_response_code() needs to come before you output anything to the browser otherwise it will not set the response code correctly. 2) http response code 201 isn't appropriate for invalid credentials, a 401 is appropriate. see this page for response code definitions. w3.org/Protocols/rfc2616/rfc2616-sec10.html Commented May 2, 2015 at 20:50
  • How can I see the log? In the Chrome Development Tool console I see only GET myurl 500 (Internal Server Error) authenticate.php:1 Commented May 3, 2015 at 15:33

1 Answer 1

1

I'm almost certain the issue is that $db_connection is null since the connection is failing. Based on what you provided your database name should be launcher-login instead of launcher_login as you've specified in your connection string. As such the following edit should fix your problem.

try {
    $db_connection = new PDO('mysql:host=localhost;dbname=launcher-login;charset=utf8', 'myUser', 'myPass');
} catch (PDOException $e) {
    echo 'Unable to connect to database'; exit;
}
Sign up to request clarification or add additional context in comments.

1 Comment

No, I tried and that's not a db problem, the correct table name is launcher_login and I only wrote it wrong in the creation query I pasted here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.