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.


    require "conn.php";
    $str = file_get_contents($url ."?email=".$email);
    $json = json_decode($str, true);        
    header('Location: main.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));


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

$str = curl_exec($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:

Leave a Reply

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