-3

I'm developing a basic web site with react and php. React is running on port 3000. php mysql inserting two times empty and full row, when i inserting a new user with a request.

I try a test record a session_id instead of user_name, i saw record different session_id same request. Could this be because I made the react requests over port 3000?

enter image description here

How can i solve this problem.

save_user.php:

<?php
include "settings.php";
include "connectdb.php";

//for coming payload json data.
$comingPayload = file_get_contents('php://input');

$comingPayloadJson = json_decode($comingPayload);

$user_name = $comingPayloadJson->userName;
$password = $comingPayloadJson->password;

$session_id = session_id();

//fix: 2 tane oturum açık olduğundan ya da  connectdb, settings.php den ya da php://input 'tan ya da başka bir şeyden dolayı ikili kaydediyor. bu sorunu düzelteceğim.
$user_insert_query = mysqli_query($link, "insert into users (user_name, password) values('$session_id', '$password')");

if($user_insert_query){
    echo "Başarıyla kaydedildi.";
}else{
    echo "kaydedilemedi, tekrar deneyiniz.";
}

?>

settings.php:

<?php
//cors error hatasının çözümü için bu ikisi kesinlikle gerekli: 
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, origin");
header('Content-Type: application/json');
?>

connectdb.php:

<?php
session_start();

$link = mysqli_connect('localhost', 'root', '1299');

if (!$link) {
    die('Could not connect: ' . mysqli_error());
}

//echo 'Connected successfully';
$select_db = mysqli_select_db($link, "hooningtuning");

if (!$select_db) {
    die ('Can\'t select database : ' . mysqli_error());
}else{
    mysqli_query($link,"SET NAMES UTF8");
    mysqli_query($link,"SET LC_TIME_NAMES = 'tr_TR'");
}
    
    //mysqli_close($link);

?>

Panel.js:

import React,{useState, useEffect} from "react"
//import Bootstrap from "bootstrap"
import axios from "axios"
import Swal from 'sweetalert2'
import UsersList from "./UsersList"

function Panel() {
    
    const [link,setLink] = useState("")
    const [userName,setUserName] = useState("")
    const [password,setPassword] = useState("")
    const [users, setUsers] = useState([])

    useEffect(()=>getLink(),[0])
    useEffect(()=>getUsers(),[0])

    function saveLink () {

        console.log("link:", link)
        
        axios.post('http://localhost/hooningtuning-eren/api/save_link.php',
          {
            link: link
          }
        )
        .then(function (response) {
            var message = response.data

            Swal.fire({
                text: message,
                confirmButtonText: 'TAMAM'
            })

            console.log("response",response);
        })
        .catch(function (error) {
            console.log(error);
        });
    }

    function saveUser () {

        console.log("saveUser:", userName)
        console.log("password:", password)
        
        if(userName!="" && password!=""){
            axios.post('http://localhost/hooningtuning-eren/api/save_user.php',
                {
                userName: userName,
                password: password
                }
            )
            .then(function (response) {
                var message = response.data
    
                Swal.fire({
                    text: message,
                    confirmButtonText: 'TAMAM'
                })
    
                getUsers()
    
                console.log("response",response);
            })
            .catch(function (error) {
                console.log(error);
            })
        }
    }

    function getLink () {
        
        console.log("get link çalıştı")

        axios.post('http://localhost/hooningtuning-eren/api/get_link.php')
        .then(function (response) {

            var message = response.data

            if(message!=""){
                setLink(message)
            }

            console.log("response",response);
        })
        .catch(function (error) {
            console.log(error);
        })
    }

    function getUsers() {
        
        console.log("get users çalıştı")

        axios.post('http://localhost/hooningtuning-eren/api/get_users.php')
        .then(function (response) {

            var users = response.data

            if(users!=""){
                console.log("users set edildi: ",users)
                setUsers(users)
            }

            console.log("response",response);
        })
        .catch(function (error) {
            console.log(error);
        })
    }

    return(
        <div className="container mt-3">
            <div className="row">
                <div className="col-lg-3">
                    <label>Yeni Kişi Kaydedin:</label>
                    <input type="text" placeholder="Kullanıcı adı" className="form-control mb-2" onChange={(input)=>{setUserName(input.target.value)}}/>
                    <input type="text" placeholder="Kullanıcı şifresi" className="form-control mb-2" onChange={(input)=>{setPassword(input.target.value)}}/>
                    
                    <div className="d-grid gap-2 mb-2">
                        <button className="btn btn-success" onClick={()=>saveUser()}>Kaydet</button>
                    </div>

                    <label className="mt-2">Kullanıcılar: </label>
                    <div className="users">
                        <div class="list-group">
                            {users.map(function(user, i){
                                return <UsersList userName={user.user_name} password={user.password} key={i} />;
                            })}
                        </div>
                    </div>
                </div>
                <div className="col-lg-5 gap-2">
                    <label>Yönlendirilecek link:</label>
                    <div className="input-group">
                        <input type="text" placeholder="örnek: https://falancasite.com" className="form-control" value={link} onChange={(input)=>{setLink(input.target.value)}} />
                        <button className="btn btn-success" onClick={()=>saveLink()}>Kaydet</button>
                    </div>

                </div>
            </div>
        </div>
    )
}

export default Panel
Orhan Gazi
  • 73
  • 1
  • 3
  • 9
  • 1
    When you do a CORS request, your browser'll do a HEAD request followed by a POST request. Is the "empty" row caused by a request where `$_SERVER['REQUEST_METHOD'] === 'HEAD'` ? – RickN May 12 '21 at 18:40
  • 3
    Please note that the way you're writing your query is unsafe, as it's open to [SQL injection](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work). You should switch to [prepared statements](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) to prevent it. – El_Vanja May 12 '21 at 18:41
  • @ADyson I added relevant react code. – Orhan Gazi May 12 '21 at 19:03
  • @RickN Thank you. How can fix it? – Orhan Gazi May 12 '21 at 19:05
  • @RickN it'is $_SERVER['REQUEST_METHOD'] is OPTIONS when empty. how to refuse OPTIONS request? – Orhan Gazi May 12 '21 at 19:22
  • @RickN I find but if i disable options method, appearing cors error. I understand solution thank you. – Orhan Gazi May 12 '21 at 19:49
  • 1
    **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman May 12 '21 at 20:09
  • 1
    The fact it's is a simple website doesn't prevent it from being hacked by bots or whatever. Heed the warnings. And also, if you learn to do things securely now, you won't have to re-learn when you have to work on something more serious. – ADyson May 12 '21 at 20:24
  • Thank you all. I will consider what you have said. – Orhan Gazi May 12 '21 at 21:50

1 Answers1

0

Attention to those with similar problems:

I couldn't figure it out but I understood the reason. Running an automatic request with OPTION method and inserting an empty record when I request with post method. This is caused by the headers I added to resolve the Cors error. (Thank you @RickN)

Orhan Gazi
  • 73
  • 1
  • 3
  • 9