frontend (ReactJS) and backend (PHP) parts of your project, including login and register functionality.
File Structure
Frontend (ReactJS)
ecommerce-app/
├── public/
├── src/
│ ├── api/
│ │ ├── index.js
│ │ └── auth.js
│ ├── components/
│ │ ├── ProductList.js
│ │ ├── AdminPanel.js
│ │ ├── Login.js
│ │ └── Register.js
│ ├── pages/
│ │ ├── Home.js
│ │ ├── Admin.js
│ │ ├── Login.js
│ │ └── Register.js
│ ├── App.js
│ ├── index.js
│ └── styles/
│ └── App.css
└── package.json
Backend (PHP)
ecommerce-backend/
├── api/
│ ├── db.php
│ ├── get-products.php
│ ├── create-product.php
│ ├── login.php
│ └── register.php
├── .htaccess
└── index.php
Frontend (ReactJS)
src/api/index.js
import axios from 'axios';
const API_URL = 'http://localhost/ecommerce-backend/api';
export const getProducts = async () => {
const response = await axios.get(`${API_URL}/get-products.php`);
return response.data;
}
export const createProduct = async (product) => {
const response = await axios.post(`${API_URL}/create-product.php`, product);
return response.data;
}
src/api/auth.js
import axios from 'axios';
const API_URL = 'http://localhost/ecommerce-backend/api';
export const login = async (credentials) => {
const response = await axios.post(`${API_URL}/login.php`, credentials);
return response.data;
}
export const register = async (user) => {
const response = await axios.post(`${API_URL}/register.php`, user);
return response.data;
}
src/components/Login.js
import React, { useState } from 'react';
import { login } from '../api/auth';
const Login = () => {
const [credentials, setCredentials] = useState({
email: '',
password: ''
});
const handleChange = (e) => {
const { name, value } = e.target;
setCredentials(prevState => ({
...prevState,
[name]: value
}));
};
const handleSubmit = async (e) => {
e.preventDefault();
const response = await login(credentials);
if (response.success) {
alert('Login successful');
// Save token and redirect to home or admin page
} else {
alert('Login failed: ' + response.message);
}
};
return (
<form onSubmit={handleSubmit}>
<h2>Login</h2>
<input type="email" name="email" placeholder="Email" onChange={handleChange} />
<input type="password" name="password" placeholder="Password" onChange={handleChange} />
<button type="submit">Login</button>
</form>
);
};
export default Login;
src/components/Register.js
import React, { useState } from 'react';
import { register } from '../api/auth';
const Register = () => {
const [user, setUser] = useState({
name: '',
email: '',
password: ''
});
const handleChange = (e) => {
const { name, value } = e.target;
setUser(prevState => ({
...prevState,
[name]: value
}));
};
const handleSubmit = async (e) => {
e.preventDefault();
const response = await register(user);
if (response.success) {
alert('Registration successful');
// Redirect to login page or home page
} else {
alert('Registration failed: ' + response.message);
}
};
return (
<form onSubmit={handleSubmit}>
<h2>Register</h2>
<input type="text" name="name" placeholder="Name" onChange={handleChange} />
<input type="email" name="email" placeholder="Email" onChange={handleChange} />
<input type="password" name="password" placeholder="Password" onChange={handleChange} />
<button type="submit">Register</button>
</form>
);
};
export default Register;
src/pages/Home.js
import React from 'react';
import ProductList from '../components/ProductList';
const Home = () => {
return (
<div>
<h1>Welcome to E-commerce App</h1>
<ProductList />
</div>
);
};
export default Home;
src/pages/Admin.js
import React from 'react';
import AdminPanel from '../components/AdminPanel';
const Admin = () => {
return (
<div>
<h1>Admin Panel</h1>
<AdminPanel />
</div>
);
};
export default Admin;
src/pages/Login.js
import React from 'react';
import LoginComponent from '../components/Login';
const Login = () => {
return (
<div>
<h1>Login</h1>
<LoginComponent />
</div>
);
};
export default Login;
src/pages/Register.js
import React from 'react';
import RegisterComponent from '../components/Register';
const Register = () => {
return (
<div>
<h1>Register</h1>
<RegisterComponent />
</div>
);
};
export default Register;
src/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './pages/Home';
import Admin from './pages/Admin';
import Login from './pages/Login';
import Register from './pages/Register';
import './styles/App.css';
const App = () => {
return (
<Router>
<div className="App">
<Switch>
<Route path="/" exact component={Home} />
<Route path="/admin" component={Admin} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
</Switch>
</div>
</Router>
);
};
export default App;
Backend (PHP)
api/db.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ecommerce";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
api/register.php
<?php
include 'db.php';
$data = json_decode(file_get_contents("php://input"));
$name = $data->name;
$email = $data->email;
$password = password_hash($data->password, PASSWORD_BCRYPT);
$sql = "INSERT INTO users (name, email, password) VALUES ('$name', '$email', '$password')";
$response = array();
if ($conn->query($sql) === TRUE) {
$response['success'] = true;
$response['message'] = "User registered successfully";
} else {
$response['success'] = false;
$response['message'] = "Error: " . $conn->error;
}
echo json_encode($response);
$conn->close();
?>
api/login.php
<?php
include 'db.php';
$data = json_decode(file_get_contents("php://input"));
$email = $data->email;
$password = $data->password;
$sql = "SELECT * FROM users WHERE email='$email'";
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
$user = $result->fetch_assoc();
if (password_verify($password, $user['password'])) {
$response['success'] = true;
$response['message'] = "Login successful";
// Ideally, you would generate and return a token here
} else {
$response['success'] = false;
$response['message'] = "Incorrect password";
}
} else {
$response['success'] = false;
$response['message'] = "User not found";
}
echo json_encode($response);
$conn->close();
?>
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
index.php
<?php
echo "E-commerce Backend";
?>
Database Schema for Users
Add a users table to your database:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Additional Notes
- Security: Consider implementing more
advanced security measures such as token-based authentication (JWT) for better security.
- Validation: Add form validation on both frontend and backend to ensure data integrity.
- Error Handling: Improve error handling and provide user-friendly error messages.
This setup should give you a good starting point for your e-commerce web application with login and registration functionality. Let me know if you need more detailed guidance on any specific part!
Top comments (0)