php – Return a JSON based on a sent variable via POST-ThrowExceptions

Exception or error:

I have the following code that builds a url with the email parameter.
After that, I receive the JSON values of id and username available on the json.php page and assign them to my $_SESSIONS.

login.php

    require "conn.php";
    $url=('http://example.com/json.php');
    $str = file_get_contents($url ."?email=".$email);
    $json = json_decode($str, true);        
    $_SESSION['id']=$json[0]['id'];
    $_SESSION['username']=$json[0]['username'];
    header('Location: main.php');

json.php

    require "conn.php";
    $email = $_GET['email'];
    $mysql_qry = "SELECT id, username FROM usertable WHERE email = '$email'";
    $result = ($conn->query($mysql_qry));
    $rows = array();
    while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
    }
    print json_encode($rows);

My system works well this way, but I would like to use POST methods instead of GET. I have tried in many ways but so far I have not succeeded.

If anyone can help me I appreciate it very much.

How to solve:

file_get_contents() isn’t suited for POST requests, and use GET requests by default, hence why all your data lands in $_GET instead of $_POST. (notably, it’s possible to, dare i say, trick file_get_contents() into doing a POST request, but, it’s a stupid idea, you shouldn’t do it.)

when you need POST requests, use curl.

while i’m at it, want to mention that $str = file_get_contents($url ."?email=".$email); needs urlencoding, it should be $str = file_get_contents($url ."?email=".urlencode($email));

but when you want to do a POST request, use curl, so instead of:

$str = file_get_contents($url ."?email=".urlencode($email));

do:

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => [
        "email" => $email
    ]
]);

$str = curl_exec($ch);
curl_close($ch);

Now it will land in $_POST[’email’] instead of $_GET[’email’]

another thing, you’re vulnerable to SQL injection here

    $mysql_qry = "SELECT id, username FROM usertable WHERE email = '$email'";

to fix that, you should port $conn to PDO, there’s a nice guide here for that: https://web.archive.org/web/20190330214051/http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

Leave a Reply

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