Simple Rest API Account creation - php

I am trying to build Simple Rest api for my php website but i am having issue on creating the account
create.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers,
Authorization, X-Requested-With");
include_once 'database.php';
include_once 'data.php';
$database = new Database();
$db = $database->getConnection();
$item = new emmanuel_api($db);
$item->user_name = $_GET['user_name'];
$item->user_pass = $_GET['user_pass'];
$item->user_email = $_GET['user_email'];
$item->full_name = $_GET['full_name'];
if($item->createUsers()){
echo 'Account created successfully.';
} else{
echo 'Account could not be created.';
}
?>
I think i am getting error on my Create.php please help me to resolve this issue
Also how i can convert this user_pass into MD5
Thanks

Related

Can't perform a PHP POST request on mysql database

I'm struggling into do my first API in php and I'm facing some problems with a simple POST request. I've searched almost everywhere for some alternatives to my code, but it seems to be ok. Can you guys check it for me the last time? Thank you!
method:
function create_msg(){
// query to insert record
$query = "INSERT INTO
" . $this->table_name . "
SET
msg_key=:msg_key, msg_id=:msg_id, msg_author=:msg_author, msg_txt=:msg_txt";
// prepare query
$stmt = $this->conn->prepare($query);
// sanitize
$this->msg_key=htmlspecialchars(strip_tags($this->msg_key));
$this->msg_id=htmlspecialchars(strip_tags($this->msg_id));
$this->msg_author=htmlspecialchars(strip_tags($this->msg_author));
$this->msg_txt=htmlspecialchars(strip_tags($this->msg_txt));
// bind values
$stmt->bindParam(":msg_key", $this->msg_key);
$stmt->bindParam(":msg_id", $this->msg_id);
$stmt->bindParam(":msg_author", $this->msg_author);
$stmt->bindParam(":msg_txt", $this->msg_txt);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
create.php:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
include_once '../config/database.php';
include_once '../models/msg.php';
$database = new Database();
$db = $database->getConnection();
$item = new msg($db);
$data = json_decode(file_get_contents("php://input"));
$item->msg_key = $data->msg_key;
$item->msg_id = $data->msg_id;
$item->msg_author = $data->msg_author;
$item->msg_txt = $data->msg_txt;
var_dump($data);
if($item->create_msg()){
echo 'OK';
} else{
echo 'Not OK';
}
?>
ok, so I managed to resolve with this code in the config/database.php
<?php
class Database{
private $host = 'mysql:host=localhost;dbname=my_touchy';
private $username = 'touchy';
private $password = '';
public function getConnection() {
$conn = new PDO($this->host, $this->username, $this->password);
$conn->setAttribute( PDO::ATTR_PERSISTENT, TRUE );
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
return $conn;
}
}
?>

Getting a http_response_code(404) when trying to pass a record id dynamically in phpmyadmin. Am trying to integrate MySQL on-pre with Salesforce

I am trying to update one particular record or row corresponding to a id passed dynamically. There is a record belonging to that id. When I give the URL followed with the "?id=3", I am getting a 404 error, saying no such record exists. Would like to know what error I have done. The following is my code.
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
include_once '../config/database.php';
include_once '../objects/constitute.php';
$database = new Database();
$db = $database->getConnection();
$constitute = new Constitute($db);
$data = json_decode(file_get_contents("php://input"));
$constitute->id = isset($_GET['id']) ? $_GET['id'] : die();
$constitute->name = $data->name;
$constitute->address = $data->address;
$constitute->constitution_type = $data->constitution_type;
$constitute->organisation_id = $data->organisation_id;
if($constitute->update()){
http_response_code(200);
echo json_encode(array("message" => "Constitute was updated."));
}
else{
http_response_code(503);
echo json_encode(array("message" => "Unable to update constitute."));
}
?>
The following is the update() method:
function update(){
$query = "UPDATE
" . $this->table_name . "
SET
name = :name,
address = :address,
constitution_type = :constitution_type,
organisation_id = :organisation_id
WHERE
id = ?";
$stmt = $this->conn->prepare($query);
$this->id=htmlspecialchars(strip_tags($this->id));
$this->name=htmlspecialchars(strip_tags($this->name));
$this->address=htmlspecialchars(strip_tags($this->address));
$this->constitution_type=htmlspecialchars(strip_tags($this->constitution_type));
$this->organisation_id=htmlspecialchars(strip_tags($this->organisation_id));
$stmt->bindParam(':id', $this->id);
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':address', $this->address);
$stmt->bindParam(':constitution_type', $this->constitution_type);
$stmt->bindParam(':organisation_id', $this->organisation_id);
if($stmt->execute()){
return true;
}
return false;
}
Also when i try to pass the updated record in postman, I am getting success code. But the record does not get saved.
Please let me know where I have done mistakes.

How to delete record from table using Angular http.delete with PHP backend?

I am trying to delete a record from the database table using Angular on frontend and PHP on the backend. I am passing the id through URL and trying to get it back with $_GET['id'] but it doesn't work (no error in console).
PHP API:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
require_once("includes/initialize.php");
$db = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbdatabase) or die('Could not connect to database');
$data = json_decode(file_get_contents("php://input"));
$id;
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
// update the ECD
if(ECD::deleteECD($id)){
echo '{';
echo '"message": "The center was deleted."';
echo '}';
}
// if unable to update the ECD, tell the user
else{
echo '{';
echo '"message": "Unable to delete the center."';
echo '}';
}
And Angular http.delete:
deleteCenter (id: number): Observable<{}> {
const url = `${this.D_ROOT_URL}${id}`;
return this.http.delete(url);
}
I tested the URL to make sure it's passing the correct URL.
The delete() method returns a cold observable, which means that the HTTP request is not sent until someone subscribes to the observable. You should write this:
return this.http.delete(url).subscribe();

$_SESSION exists, but is empty. Why?

I have logged mu user (in login.php) and start session, before redirect to another page (accueil.php)/
In login.php : My Session exists, my cookies exists.
In accueil.php : My Session exists, my cookies doesn't exists.
==> I started my Session at the top of my second page./
==> I tried different way to use Location in vain :
header('Location: http://localhost/monsite/accueil.php');/
OR
header('Location: accueil.php');
==>Anyway : it returns "undefined index username".
I don't understand. Have you any ideas please?!
Here is my code :
Login.php :
$username = $_GET['username'];
$password = $_GET['password'];
$sql = $connection->query("SELECT username, password FROM login WHERE username = '$username' && `password`= '$password';");
while ($result = $sql->fetch()){
$data = array('username' => $result['username'],
'password' => $result['password']);
}
try{
if($data['username'] !== $username && $data['password'] !== $password ) {
throw new Exception('Login incorrect', 500);
}
else{
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
setcookie('maSession', $_SESSION['username'], time()+3600 , '/');
header('Location: http://localhost/monsite/accueil.php');
}
}
catch(Exception $e){
header("HTTP/1.1 500 Internal Server Error");
echo 'error: '.$e->getMessage();
}
Accueil.php :
``
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
include_once('accueil.php');
require_once('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$connection = new PDO("mysql:host=$HOST;dbname=$DBNAME", $USER, $PASS);
if(isset($_SESSION)) {
$username = $_SESSION['username'];
echo $username;
}
else{
echo 'no session';
}
}
->var_dump($_SESSION) : returns empty array.
->$_SESSION['username'] : returns undefined index undername.
Thank you !
Try
<?php
//Check session if not already started, then start it.
if(session_id() == '')
{
session_start();
}
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
include_once('accueil.php');
require_once('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$connection = new PDO("mysql:host=$HOST;dbname=$DBNAME", $USER, $PASS);
// Check session 'username' it was not empty
if(!empty($_SESSION['username'])) {
$username = $_SESSION['username'];
echo $username;
}
else{
echo 'no session';
}
}
?>

Getting Blank record for this code

Look at this code, i am getting empty record in database.
$firstname=isset($_POST['firstname'])?mysql_real_escape_string($_POST['firstname']):"";
this line not giving first name but it gives blank value not the value that i am trying to insert into the database.
whats wrong in this code?
create.php
<?php
include_once('confi.php');
if($_SERVER['REQUEST_METHOD']=='POST')
{
$firstname=isset($_POST['firstname'])?mysql_real_escape_string($_POST['firstname']):"";
$lastname=isset($_POST['lastname'])?mysql_real_escape_string($_POST['lastname']):"";
$email=isset($_POST['email'])?mysql_real_escape_string($_POST['email']):"";
$password=isset($_POST['password'])?mysql_real_escape_string($_POST['password']):"";
$status=0;
$query = "INSERT INTO users (firstname,lastname,email,password,status) VALUES ('$firstname','$lastname','$email','$password','$status')";
$insert = mysql_query($query);
if($insert)
{
$data=array("result"=>1,"message"=>"successfully added!");
}
else
{
$data=array("result"=>0,"message"=>"Error!");
}
}
else
{
$data=array("result"=>0,"message"=>"Request Method is Wrong!");
}
mysql_close($conn);
/* JSON Response */
header('Content-type: application/json');
echo json_encode($data);
?>
confi.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('tuts_rest', $conn);
?>
Add the following lines in your php file and remove header access you have already added
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')
{
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:
{
$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}

Categories