this is my addproject.php code:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
die();
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') :
http_response_code(405);
echo json_encode([
'success' => 0,
'message' => 'Bad Request!.Only POST method is allowed',
]);
exit;
endif;
require 'connect.php';
$database = new config();
$conn = $database->getConnection();
$data = json_decode(file_get_contents("php://input"));
var_dump($data);
if (!isset($data->id) || !isset($data->description) || !isset($data->name) || !isset($data->start_date) || !isset($data->end_date)) :
echo json_encode([
'success' => 0,
'message' => 'Please enter compulsory fileds | id, description and name',
]);
exit;
elseif (empty(trim($data->id)) || empty(trim($data->description)) || empty(trim($data->name))) :
echo json_encode([
'success' => 0,
'message' => 'Field cannot be empty. Please fill all the fields.',
]);
exit;
endif;
try {
$id = htmlspecialchars(trim($data->id));
$description = htmlspecialchars(trim($data->description));
$start_date = htmlspecialchars(trim($data->start_date));
$end_date = htmlspecialchars(trim($data->end_date));
$name = htmlspecialchars(trim($data->name));
$query = "INSERT INTO `projects`(
id,
description,
start_date,
end_date,
name,
)
VALUES(
:id,
:description,
:start_date,
:end_date,
:name
)";
$stmt = $conn->prepare($query);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->bindValue(':description', $description, PDO::PARAM_STR);
$stmt->bindValue(':start_date', $start_date, PDO::PARAM_STR);
$stmt->bindValue(':end_date', $end_date, PDO::PARAM_STR);
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
if ($stmt->execute()) {
http_response_code(201);
echo json_encode([
'success' => 1,
'message' => 'Data Inserted Successfully.'
]);
exit;
}
echo json_encode([
'success' => 0,
'message' => 'There is some problem in data inserting'
]);
exit;
} catch (PDOException $e) {
http_response_code(500);
echo json_encode([
'success' => 0,
'message' => $e->getMessage()
]);
exit;
}
and this is my angular request POST:
`createProjects(project:any) {
console.log(project);
return this.http.post(this.baseUrl+'addprojects.php', project);
}`
keep in mind the that the delete project and viewprojects works and the angular is sending data but the server is not reading it right i get this error :POST http://localhost/backend/addprojects.php 500 (Internal Server Error)
im trying to send data from a POST REQUEST IN ANGULAR TO MY API THAT I SET UP IN THE SERVICE COMPONONET but there is something wrong with the serveryour text
Related
Currently using Stripe to process payments however I would like to perform an SQL statement which will ban a user lets say when the Stripe risk evaluation is highest.
My current charge code using stripe's PHP library contains a basic error exception message:
<?php
require 'lib/Stripe.php';
if ($_POST) {
Stripe::setApiKey($stripeSecretKey);
$error = '';
$success = '';
try {
if (empty($_POST['street']) || empty($_POST['city']) || empty($_POST['zip']))
throw new Exception("Fill out all required fields.");
if (!isset($_POST['stripeToken']))
throw new Exception("The Stripe Token was not generated correctly");
Stripe_Charge::create(array("amount" => $price * 100,
"currency" => "gbp",
"card" => $_POST['stripeToken'],
"description" => "User: " . $userUsername . " - " . $userEmail,
"receipt_email" => $userEmail));
$success = '<div class="alert alert-success">
<strong>Success!</strong> Your payment was successful, Redirecting...
</div>';
header('Refresh: 3; URL=https://urlhere');
}
catch (Exception $e) {
$error = '<div class="alert alert-danger">
<strong>Error!</strong> '.$e->getMessage().'
</div>';
}
}
if(!(empty($success)))
$txid = generateTxid();
{
$SQL = $odb -> prepare("INSERT INTO `payments` VALUES(NULL, :price, :planid, :userid, :payer, :transactionid, UNIX_TIMESTAMP())");
$SQL -> execute(array(':price' => $price, ':planid' => $planID, ':userid' => $userID, ':payer' => $userEmail, ':transactionid' => $txid));
$unit = $plan['unit'];
$length = $plan['length'];
$newExpire = strtotime("+{$length} {$unit}");
$updateSQL = $odb -> prepare("UPDATE `users` SET `expire` = :expire, `membership` = :plan WHERE `ID` = :id");
$updateSQL -> execute(array(':expire' => $newExpire, ':plan' => (int)$planID, ':id' => (int)$userID));
}
?>
With reference to https://stripe.com/docs/api#charge_object I can see that under the PHP tab it has the outcome object which could be used in my cas ehowever not sure how to implement it.
Check the response from your charge creation. Look at the risk_level attribute and write a condition that does something when the condition is met.
$response = Stripe_Charge::create(...
To get the risk_level attribute:
print $response->outcome->risk_level
P.S. you should be checking the charge response to verify it succeeded and not just assuming it succeeded if an Exception was not thrown. It could be Pending, which is not an Exception but it's also not a success, for example.
I have created a simple html form to test, how I can insert data in wpdb. I know how to do it in PHP but in wordpress I am getting confused!
global $wpdb;
if (isset($_POST['submit'])) {
$name = $_POST['r1s1']; //Here r1s1 is name of the form control
$email = $_POST['r2s1'];
$contact = $_POST['r3s1'];
$address = $_POST['r5s1'];
if ($name != '' || $email != '') {
$post = $wpdb->insert(
'table', array(
'feild' => $name,
'dev' => $email,
'tenant' => $contact,
'mod' => $address,
), array(
'%s',
'%s',
'%s',
'%s'
)
);
echo $post;
if ($post) {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
} else {
echo "<br/><br/><span>Insertion Failed...!!</span>";
}
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
When I click on submit button then it shows message insertion failed...!! ( Message that I am printing via echo). This code is written in template. What I am doing wrong?
global $wpdb;
$wpdb->insert( 'table_name', array( 'field_name' => $_POST['r1s1'], 'field_name' => $_POST['r2s1'],'field_name' => $_POST['r3s1'],'field_name' => $_POST['r4s1']) );
Try This one
You can try below code?
global $wpdb;
$table_name = $wpdb->prefix . "your_table_name";
if (isset($_POST['submit'])) {
$name = $_POST['r1s1']; //Here r1s1 is name of the form control
$email = $_POST['r2s1'];
$contact = $_POST['r3s1'];
$address = $_POST['r5s1'];
$data = array(
'feild' => $name,
'dev' => $email,
'tenant' => $contact,
'mod' => $address
);
if ($name != '' || $email != '') {
$result = $wpdb->insert($table_name, $data);
if ($result) {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
} else {
echo "<br/><br/><span>Insertion Failed...!!</span>";
}
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
I am using the following slim session manager(https://github.com/bryanjhv/slim-session). I have separate functions for login, logout and user_data.
$app->post("/login", function() use ($app)
{
$input = $app->request()->getBody();
$input = json_decode($input);
try
{
if ($input->username && $input->password)
{
$user = Model::factory('Users')->where("username",$input->username)->where("password",md5($input->password))->find_one();
$session = new \SlimSession\Helper;
//set session
$session->set('userid', $user->id);
$status = 'success';
$message = 'Logged in successfully.';
}
else
{
$status = 'danger';
$message = 'Could not log you in. Please try again.';
}
}
catch (Exception $e)
{
$status = 'danger';
$message = $e->getMessage();
}
$response = array(
'status' => $status,
'message' => $message,
);
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
$app->post("/logout",function() use ($app)
{
try {
$session = new \SlimSession\Helper;
$session::destroy();
$status = 'success';
$message = 'You have been logged out successfully';
}
catch (Exception $e)
{
$status = 'danger';
$message = $e->getMessage();
}
$response = array(
'status' => $status,
'message' => $message
);
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
$app->get("/user_data", function() use ($app)
{
try
{
$session = new \SlimSession\Helper;
//get session
$userid = $session->get('userid');
$_SESSION['userid'] = $userid;
if ($_SESSION['userid'])
{
$users = Model::factory('Users')->where('id',$_SESSION['userid'])->find_one();
$response = array(
'id'=>$users->id,
'username'=>$users->username,
'email'=>$users->email,
'phone_number'=>$users->phone_number,
'password'=>$users->password,
'type'=>$users->type,
'credits'=>$users->credits,
'profile_picture'=>$users->profile_picture,
);
}
else
{
$status = "danger";
$message = 'You need to be logged in to do that.';
$response = array(
'status' => $status,
'message' => $message
);
}
}
catch (Exception $e)
{
$status = "danger";
$message = $e->getMessage();
$response = array(
'status' => $status,
'message' => $message
);
}
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
The problem I am having is that when the user logs in I set a session variable in the /login function. But when the session variable i set in login function isn't being retrieved in the /user_data function.
Anyone knows whats going on?
Have you started session with session_start() ?
Correct logic to check session is as follows:
if (isset($_SESSION['userid']))
{
// session exists
// do further work
}
I have this code that is used to process user inputs from a from with the parameters email and password.
$app->post('/login', function() use ($app) {
// check for required params
verifyRequiredParams(array('email', 'password'));
// reading post params
$email = $app->request()->post('email');
$password = $app->request()->post('password');
$response = array();
$db = new DbHandler();
// check for correct email and password
if ($db->checkLogin($email, $password)) {
// get the user by email
$user = $db->getUserByEmail($email);
if ($user != NULL) {
$response["response_status"] =array('status_code'=>0, 'status_message' => 'Login Successfuly');
$response["customer_creds"] =array(array('customer_names'=>$user['name'], 'customer_email' => $user['email'], 'customer_id' => $user['customer_id'], 'customer_type' => $user['customer_type'], 'rating' => $user['rating']));
$response["customer_payment_instruments"] =array(array('payment_method'=>$user['payment_method1'], 'account_number' => $user['account_number1']),array('payment_method'=>$user['payment_method2'], 'account_number' => $user['account_number2']),array('payment_method'=>$user['payment_method3'], 'account_number' => $user['account_number3']));
$response["customer_vehicle_details"] =array(array('vehicle_plate'=>$user['vehicle_plate1'], 'vehicle_make' => $user['vehicle_make1'], 'vehicle_model' => $user['vehicle_model1'], 'vehicle_colour' => $user['vehicle_colour1'], 'vehicle_id' => $user['vehicle_id1']), array('vehicle_plate'=>$user['vehicle_plate2'], 'vehicle_make' => $user['vehicle_make2'], 'vehicle_model' => $user['vehicle_model2'], 'vehicle_colour' => $user['vehicle_colour2'], 'vehicle_id' => $user['vehicle_id2']));
} else {
// unknown error occurred
$response["response_status"] =array('status_code'=>1, 'status_message' => 'An unknown error occurred. Please try again');
//$response['error'] = true;
//$response['message'] = "An error occurred. Please try again";
}
} else {
// user credentials are wrong
$response["response_status"] =array('status_code'=>1, 'status_message' => 'Login failed. Incorrect credentials');
}
echoRespnse(200, $response);
});
This script checks if the email and password exist in the database and give a json response.
public function checkLogin ($email, $password) {
// fetching user by email
$stmt = $this->conn->prepare("SELECT password_hash FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result ($password_hash);
$stmt->store_result();
if ($stmt->num_rows > 0) {
// Found user with the email
// Now verify the password
$stmt->fetch();
$stmt->close();
if (PassHash::check_password($password_hash, $password)) {
// User password is correct
return TRUE;
} else {
// user password is incorrect
return FALSE;
}
} else {
$stmt->close();
// user not existed with the email
return FALSE;
}
}
/**
* Fetching user by email
* #param String $email User email id
*/
public function getUserByEmail($email) {
$stmt = $this->conn->prepare("SELECT name, email, customer_id, customer_type, rating, payment_method1, account_number1, payment_method2, account_number2, payment_method3, account_number3, vehicle_plate1, vehicle_make1, vehicle_model1, vehicle_colour1, vehicle_id1, vehicle_plate2, vehicle_make2, vehicle_model2, vehicle_colour2, vehicle_id2, api_key, status, created_at FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return NULL;
}
}
I am now trying to figure out a way of allowing folks to parse json data. Any workarouds in doing this? For now script only accepts data from a form. Is there a way of allowing raw data in the format
{
"email":"",
"password":""
}
Here is the code that you can use in your current code:
Replace this code:
// reading post params
$email = $app->request()->post('email');
$password = $app->request()->post('password');
With
// reading request body
$requestBody = $app->request->getBody();
// parsing json data to php
$requestData = json_decode($requestBody, 1);
// checking if email or password is set, if not the return response
if(empty($requestData['email']) || empty($requestData['password'])) {
echoRespnse(400, ['message' => 'username/password cannot be empty']);
}
$email = $requestData['email'];
$password = $requestData['password'];
Hope this should work!!
I have written the following in my reginsert.php. The goal is to take the variables from index.php and insert into my regdata table. After successful insert is completed, I want the user redirected to thank_you.html. Where/how would I incorporate that in the following code block?
<?php
$Database = array(
"Host" => 'myhost',
"User" => 'myuser',
"Password" => 'mypass',
"Name" => 'mydb'
);
if ($mysqli->connect_error)
{
$error = true;
echo $mysqli->connect_error;
}
else
$mysqli = new mysqli($Database['Host'], $Database['User'], $Database['Password'], $Database['Name']);
$stmt=mysqli->prepare("INSERT into regdata (Username,Password,Confpassword,Status,Salutation,Firstname,Lastname,Jobtitle,Telephone,Companyname,industry,Address,City,Country,State,PostalCode,Regtype,Interests,Hdsprovider,PasswordRemindQuestion,PasswordRemindAnswer)
VALUES(
$_POST['email_address'],
$_POST['create_password'],
$_POST['confirm_password'],
'0',
$_POST['salutation2'],
$_POST['first_naem'],
$_POST['last_name'],
$_POST['job_title'],
$_POST['telephone'],
$_POST['company_name'],
$_POST['industry'],
$_POST['address'],
$_POST['city'],
$_POST['state'],
$_POST['country'],
$_POST['state'],
$_POST['postal_code'],
$_POST['partner_customer_other'],
$_POST['interests'],
$_POST['provider_partner'],
$_POST['password_reminder_question'],
$_POST['password_reminder_answer']
)");
$stmt->execute();
$stmt->close();
?>
Also, note that my table field regid is a primary key and status is default to 0. Do I need to add regid as part of my insert statement?
Thanks,
Sid
if ($stmt->execute()) {
header("Location: /path/to/thank_you.html");
}
if(mysql_affected_rows($stmt)>0)
{
header("Location: /path_of_page.html");
}
if($stmt=mysqli->prepare("INSERT into regdata ...."))
{
//Above code ....
} else
{
header ('Location: http://www.example.com/';
}