0

new result of the consolein my login page of my web application, when the user enters his email and password correctly, any session is opening. In the console>application, I don't have a PHPSESSID. However, when I use my PHP file with a simple HTML code, it works properly and I have a PHPSESSID. I don't understand what's the problem, if someone can help me please?

ReactJS file:

import React from 'react';
import { Redirect} from 'react-router';
import './connexion.css';
import axios from 'axios';

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      password: null,
      email: null,
      loggedIn: false, 
      error: '',

    };
  }

  change = async e => {
    await this.setState({
      [e.target.id]: e.target.value,
    });
  }

  handleSubmitLogIn = e => {
    const { email, password } = this.state;

    if (password && email) {

      console.log(this.state);
      let formData = new FormData();
      formData.append("email",this.state.email);
      formData.append("password",this.state.password);
      const url = "http://localhost:8888/API/Connexion/login.php";
      axios.post(url, formData)

      .then(function(response) {  
        this.setState({loggedIn: true});
        console.log("success");
      }.bind(this))

      .catch((error) => {
        if(error.response && error.response.status === 403){
          this.setState({
            error: error.response.data,
            });
        }
      });

    } else {
      this.setState({
        error: 'please fill in everything',
      });
    }

    setTimeout(() => {
      this.setState({
        error: '',
      });
    }, 2000);

    e.preventDefault();    
  }


  render() {
    const { error } = this.state;
    const {loggedIn } = this.state;

    if(loggedIn){
      //redirect to the home page
      return <Redirect to="/accueil"/>;
    }

    return (
      <div>
                <form onSubmit={this.handleSubmitLogIn}>
                  <div className="text-center">
                    <h2 className="dark-grey-text mb-5">
                      Log In
                    </h2>
                  </div>
                  <label htmlFor="email" className="grey-text">
                    email
                    <input
                      type="email"
                      id="email"
                      name="email"
                      className="form-control"
                      onChange={this.change}
                    />
                  </label>

                  <br />
                  <label htmlFor="password" className="grey-text">
                    password
                    <input
                      type="password"
                      id="password"
                      name="password"
                      className="form-control"
                      onChange={this.change}
                    />
                  </label>

                  <div className="text-center mb-3">
                    <button type="submit" className="btn btn-primary" onClick={this.handleSubmitLogIn}>validate</button>
                    {
                     error && (
                     <p className="error">{error}</p>
                     )
                    }
                  </div>
                </form>
      </div>
    );
  }
}

export default Login;

PHP file login.php :

<?php
    session_start();        

    $con=mysqli_connect('localhost', 'root', 'root', 'mybibli');

    if(!$con) {                                                 
        die('erreur de connexion avec la base de donnée'.mysql_error());    
    }

        $email = $_POST['email'];
        $password = $_POST['password'];

        $email = strip_tags(mysqli_real_escape_string($con, trim($email)));
        $password = strip_tags(mysqli_real_escape_string($con, trim($password)));       

        $query = "SELECT * FROM user where email='".$email."'"; 
        $hi = mysqli_query($con, $query);
        if(mysqli_num_rows($hi) > 0) {

            $row = mysqli_fetch_array($hi);
            $password_hash = $row['password'];

            if(password_verify($password, $password_hash)) {
                $_SESSION['User']=$_POST['email'];      
                http_response_code(200);            
            } else {
                echo"invalid password";
                http_response_code(403);            
            }
        } else{
            echo"No user account linked to this email address";
            http_response_code(403);            
        }
?>
chiche
  • 25
  • 1
  • 6
  • Did you check that - https://stackoverflow.com/questions/54874686/php-session-in-api-changes-when-called-by-axios-in-react ? – kamil.w May 08 '20 at 15:49
  • I still cannot do it – chiche May 08 '20 at 16:08
  • I would advise: (1) edit your question to state the problem at the top and be more specific - what is exactly the problem. (2) only post specific details that relate directly to your question (e.g. anything that concerns to creation of session) and not the entire code - to help people who read this to focus on the problem and be able to give you an answer. – Yuval May 09 '20 at 07:38

1 Answers1

1

Read advices from here carefully Make Axios send cookies in its requests automatically. I don't want to duplicated this but you have to add withCredentials: true to your axios request and you have to add header to your response Access-Control-Allow-Origin: http://localhost:8888 in your case. That's all what you need.

kamil.w
  • 134
  • 1
  • 5
  • I add this to my request: `axios.post(url, FormData, {withCredentials: true, header: 'Access-Control-Allow-Origin: http://localhost:8888' })` but I still haven't succeeded, should I change something else ? – chiche May 08 '20 at 17:54
  • axios.post(url, FormData, {withCredentials: true}) - that's for axios, header('Access-Control-Allow-Origin: http://localhost:8888'); should be added in the first line into your php script - login.php – kamil.w May 08 '20 at 18:09
  • I added the console result even if I change this, if you can see it please – chiche May 08 '20 at 18:20
  • Did you add header into php script ? If yes please try with ```http://localhost:3003``` domain should be the same one from which you run your application request. – kamil.w May 08 '20 at 18:31
  • Try with ```withCredentials: false``` – kamil.w May 08 '20 at 18:38
  • I tried also with adding these headers: `header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: *"); header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Methods: POST");` but always the same error, I don't know if that would have changed something. – chiche May 08 '20 at 18:38
  • Wildcards for sure will not work if you're using ```withCredentials: true``` – kamil.w May 08 '20 at 18:40
  • I had the picture with all these changes. The login works but I didn't have a session opened (no PHPSESSID). – chiche May 08 '20 at 18:43
  • Request to session.php dont exists so how do you want create a session? – kamil.w May 08 '20 at 18:45
  • And one more thing session will start only when you're doing request to php script from the same domain from which you run yuor react app. Thats all how i can help. – kamil.w May 08 '20 at 18:49
  • Read this https://create-react-app.dev/docs/proxying-api-requests-in-development/. You need to setup proxy sine you're react app is running from npm on 3003 port and your php server on 8888 port. That's way this dosent work. – kamil.w May 08 '20 at 18:58