In my Yii web application I want to write a web service for mobile application. I create a url for access student details with GET method. That I want to change GET method to POST method or PUT method. My url is,
url/index.php/user/login/studentdetails/?username=demo
I am getting this username from client side and giving the response from server side to client side in json format.
My code is,
public function actionStudentdetails() {
if (isset($_GET['username'])) {
$user = Users::model()->findByAttributes(array('username' => $_GET['username']));
$usertypeid = $user->usertypeid;
if ($usertypeid === '1') {
$studentid = $user->userid;
} else if ($usertypeid === '3') {
$guardianid = $user->userid;
$studentid = $_GET['studentid'];
} else {
$employeemasterid = $user->userid;
}
$student = Student::model()->findByPk($studentid);
header('Content-type: application/json');
$response["student_admissionno"] = $student->student_admissionno;
$response["student_firstname"] = $student->student_firstname;
$response["student_middlename"] = $student->student_middlename;
$response["student_lastname"] = $student->student_lastname;
$response["student_admissiondate"] = $student->student_admissiondate;
$response["student_dob"] = $student->student_dob;
$response["student_gender"] = $student->student_gender;
$response["student_religion"] = $student->student_religion;
$response["student_caste"] = $student->student_caste;
$response["student_address1"] = $student->student_address1;
$response["student_address2"] = $student->student_address2;
$response["student_city"] = $student->student_city;
$response["student_state"] = $student->student_state;
$response["success"] = 1;
$response["message"] = "success";
echo json_encode($response);
}
}
}
Please help me.
you can try this code for webserivce. you can used any method GET or POST Method of data posting in server side.
StudentController.php
public function actionStudentdetails() {
$json_data = array();
$params = isset($_REQUEST) ? $_REQUEST: "";
if (!empty($params)) {
$username = $params['username'];
if($username == "") {
$json_data['success'] = false;
$json_data['message'] = 'Username are required.';
} else {
$user = Users::model()->findByAttributes(array('username' => $params['username']));
$usertypeid = $user->usertypeid;
if ($usertypeid === '1') {
$studentid = $user->userid;
} else if ($usertypeid === '3') {
$guardianid = $user->userid;
$studentid = $_GET['studentid'];
} else {
$employeemasterid = $user->userid;
}
$student = Student::model()->findByPk($studentid);
header('Content-type: application/json');
$json_data["student_admissionno"] = $student->student_admissionno;
$json_data["student_firstname"] = $student->student_firstname;
$json_data["student_middlename"] = $student->student_middlename;
$json_data["student_lastname"] = $student->student_lastname;
$json_data["student_admissiondate"] = $student->student_admissiondate;
$json_data["student_dob"] = $student->student_dob;
$json_data["student_gender"] = $student->student_gender;
$json_data["student_religion"] = $student->student_religion;
$json_data["student_caste"] = $student->student_caste;
$json_data["student_address1"] = $student->student_address1;
$json_data["student_address2"] = $student->student_address2;
$json_data["student_city"] = $student->student_city;
$json_data["student_state"] = $student->student_state;
$json_data['success'] = true;
$json_data['message'] = "Data found Successful.";
}
} else {
$json_data['success'] = false;
$json_data['message'] = "Please try again.";
}
echo json_encode($response);
}
Related
Let’s get detailed…cause I’m stumped.
Server File structure:
/home/name/public_html/CryptlexApi.php
/home/name/public_html/generate-license.php see below
/home/name/public_html/generate-license-IPN_combined.php
/home/name/public_html/paypalIPN.php
source
generate-license.php:
<?php
require('CryptlexApi.php');
// pass this secret as query param in the url e.g. https://yourserver.com/generate-license.php?cryptlex_secret=SOME_RANDOM_STRING
$CRYPTLEX_SECRET = "SOME_RANDOM_STRING";
// access token must have following permissions (scope): license:write, user:read, user:write
$PERSONAL_ACCESS_TOKEN = "Yes, I have my PAT here";
// utility functions
function IsNullOrEmptyString($str){
return (!isset($str) || trim($str) === '');
}
function ForbiddenRequest() {
http_response_code(403);
$message['error'] = 'You are not authorized to perform this action!';
echo json_encode($message);
}
function BadRequest($error) {
http_response_code(400);
$message['error'] = $error;
echo json_encode($message);
}
function VerifySecret($secret) {
if($secret == $GLOBALS['CRYPTLEX_SECRET']) {
return true;
}
return false;
}
function parsePayPalPostData() {
$postBody['company'] = $_POST['payer_email'];
if(IsNullOrEmptyString($postBody['email'])) {
$postBody['company'] = "";
}
$postBody['quantity'] = $_POST['quantity'];
if(IsNullOrEmptyString($postBody['quantity'])) {
$postBody['quantity'] = NULL;
}
$postBody['email'] = $_POST['payer_email'];
if(IsNullOrEmptyString($postBody['email'])) {
BadRequest('email is missing!');
return NULL;
}
$postBody['last_name'] = $_POST['last_name'];
if(IsNullOrEmptyString($_POST['last_name'])) {
BadRequest('last name is missing!');
return NULL;
}
$postBody['first_name'] = $_POST['first_name'];
if(IsNullOrEmptyString($_POST['first_name'])) {
BadRequest('first name is missing!');
return NULL;
}
$postBody['order_id'] = $_POST['txn_id'];
if(IsNullOrEmptyString($postBody['order_id'])) {
BadRequest('reference is missing!');
return NULL;
}
return $postBody;
}
try {
if(VerifySecret($_GET['cryptlex_secret']) == false) {
return ForbiddenRequest();
}
CryptlexApi::SetAccessToken($GLOBALS['PERSONAL_ACCESS_TOKEN']);
$product_id = "this is my product id";
$postBody = parsePayPalPostData();
if($postBody == NULL) {
echo "no data \n";
return;
}
$email = $postBody['email'];
$first_name = $postBody['first_name'];
$last_name = $postBody['last_name'];
$quantity = $postBody['quantity'];
// required for renewing the license subscription
$order_id = $postBody['order_id'];
// creating user is optional
$user_exists = false;
$user = CryptlexApi::GetUser($email);
if($user == NULL) {
$user_body["email"] = $email;
$user_body["firstName"] = $first_name;
$user_body["lastName"] = $last_name;
$user_body["company"] = $last_name;
// generate a random 8 character password
$user_body["password"] = substr(md5(uniqid()), 0, 8);
$user_body["role"] = "user";
$user = CryptlexApi::CreateUser($user_body);
} else {
$user_exists = true;
}
echo "Quantity = $quantity \n";
// creating license
if($quantity != NULL) {
$license_body["allowedActivations"] = (int)$quantity;
}
$license_body["productId"] = $product_id;
$license_body["userId"] = $user->id;
$metadata["key"] = "order_id";
$metadata["value"] = $order_id;
$metadata["visible"] = false;
$license_body["metadata"] = array($metadata);
$license = CryptlexApi::CreateLicense($license_body);
http_response_code(200);
echo $license->key;
} catch(Exception $e) {
http_response_code(500);
echo 'message: ' .$e->getMessage();
}
Ok, So if I do the following in the terminal, I will successfully create a user/license
curl -d "payer_email=emailaddress%40gmail.com&quantity=1&last_name=smith&first_name=bob&txn_id=ordernumber" -X POST https://mywebsite.com/generate-license.php?cryptlex_secret=SOME_RANDOM_STRING
So, I take that code and put it in paypalIPN.php and renamed to generate-license-IPN_combined.php
In the paypalIPN.php file, I inserted the above code here:
// Check if PayPal verifies the IPN data, and if so, return true.
if ($res == self::VALID) {
######## I put all of my code above right here #########
return true;
} else {
return false;
}
The IPN code seems to work since the Paypal IPN simulator says it does. Nothing happens on the database side though. I’ve removed checks and even went as far as putting this code before the IPN but it’s not working. Please help.
A quick way to generate test IPNs in sandbox is to pay with a link of the form:
https://www.sandbox.paypal.com/webscr?cmd=_xclick&item_name=test&amount=100¤cy_code=USD&business=sandboxbusinessemail#domain.com¬ify_url={URL_ENCODE_YOUR_IPN_LISTENER_URL}
(Reference: HTML Variables for PayPal Payments Standard )
Get a sandbox business account to sub into the above, and a sandbox personal account to pay with, via: https://www.paypal.com/signin?intent=developer&returnUri=https%3A%2F%2Fdeveloper.paypal.com%2Fdeveloper%2Faccounts%2F
Review the business account's IPN history via: https://www.sandbox.paypal.com/webscr?cmd=_display-ipns-history
I need to return a URL that opens a support chat window on a mobile app from my PHP function after validating the user is correctly logged in via the mobile app and provide them with the URL. Below is my code sample.
<?php
if((isset($_POST['key']) && $_POST['key'] != "") && isset($_POST['userName']) && $_POST['userName'] != "")
{
$acc = new userAccount();
//if($acc->clientloginIntoAccount($_POST['userName'],$_POST['passWord'],$_POST['key']) == 1)
$Response = array();
if($acc->ClientLoginEncryptionUpgrade($_POST['userName'], $_POST['passWord'], $_POST['key'], $Response))
{
$_SESSION['clientloggedin'] = $Response['details']['session_data'];
$_SESSION['clientloggedin']['cost_centre'] = $Response['details']['company'];
$_SESSION['clientloggedin']['time'] = $_POST['time'];
$_SESSION['primary_color_1'] = $Response['details']['primary_color_1'];
$_SESSION['primary_color_2']= $Response['details']['primary_color_2'];
$_SESSION['footer_colour']= $Response['details']['footer_colour'];
$_SESSION['email_color'] = $Response['details']['email_color'];
$_SESSION['client_logo'] = $Response['details']['client_logo'];
$_SESSION['link_color'] = $Response['details']['link_color'];
$_SESSION['menu_items'] = $Response['details']['menu_items'];
$_SESSION['menu_items_icons'] = $Response['details']['menu_items_icons'];
$employee = getTableValue("personnel","id","employee_number='{$_POST['key']}'");
$_SESSION['loggedin']['personnelID'] = $employee;
echo "<script>window.location.href='home';</script>";
return "<script>javascript:void($zopim.livechat.window.openPopout())</script>";
}
else
{
echo "<div class = 'bg-danger'> Incorrect username / password. Please try again. </div>";
?>
i have code like this
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage']))
{
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
if(!preg_match("/^(?=.*[0-9])(?=.*[a-z])(\S+)$/i", $_POST['password']))
{
$errorMessage="don't allow spaces";
}
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage='Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username'])) )
{
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret)) )
{
if ( $chk_secret->used >= $chk_secret->number ) {
$errorMessage = "your access code limit completed..";
}
else
{
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if($result = $DB->insert_record('user', $insert_record))
{
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
}
else
$errorMessage = "error! can you please try again";
}
}
else
$errorMessage = "your access code is wrong..";
}
}
?>
so i want to write condition like another if condition
if ( $chk_secret->status='0' ) {
$errorMessage = "your access code deactivated..";
}
if not they can register
i tried..but i didn't get idea where i have to add that if..
before i have condition like if number>used it will show some error message like your accesscode limit completed
can anyone help me..
thanks in advance..
= is for value assignment
== is compare two operands
so you need to change
if ( $chk_secret->status='0' ) {
to
if ( $chk_secret->status=='0' ) {
UPDATE:
your query SELECT * FROM {accesscode} WHERE random_no= ? and status=1
which means it going to return only status == 1
you can check with number of rows returned is ZERO then through status zero error message.
Or else
Get rows only based on random_no exists and then check status key
Good Evening,
I'm using CodeIgniter 2 on IIS 8.5 and MSSQL Server,
When i tried to send an email in the process, it shows the error:
Severity: Notice
Message: A non well formed numeric value encountered
Filename: libraries/Email.php
Line Number: 1689
I've been using this code for some projects in the same server, and it's working properly. But when i tried to implement on this one it always shows this error everytime there's sending email process.
And here's my controller:
function reset_pass() {
if (!IS_AJAX) {
display_nonajax_stop();
exit;
} else {
$settings = $this->m_setting->get_setting_array();
$min_pass_length = (int) $settings["acc_pass_min_length"];
$data = $this->input->post();
$id = $data['id'];
$hasil = array();
$kondisi = array(
"usr_id" => $id
);
$current_time = waktu_sekarang();
$baris = $this->m_ess->get_user_employee_row($kondisi);
$user = $baris;
if ($user->usr_email === NULL) {
$hasil['pesan'] = "User does not have valid email associated . Please contact Administrator.";
$hasil['status'] = 0;
} else {
$this->load->helper('email');
if (!valid_email($user->usr_email)) {
$hasil['pesan'] = "User does not have valid email associated . Please contact Administrator.";
$hasil['status'] = 0;
} else {
$hasil['pesan'] = "Username and email is ok";
$hasil['status'] = 0;
$this->load->library('rndconditionpass');
$tmppass = $this->rndconditionpass->get_random_string($min_pass_length);
$new_password = $this->bcrypt->do_hash($tmppass);
$mail_data['random'] = $tmppass;
$mail_data['username'] = $user->usr_name;
$mail_data['full_name'] = $user->emp_name;
$mail_data['password'] = $tmppass;
//prepare data to be used in leo_mail library
$param = array();
$param['recipient'] = $user->usr_email;
$param['content'] = $this->load->view("template/mail/mail_reset_pass", $mail_data, TRUE);
$param['subject'] = "Reset Password";
$this->load->library('leo_mail');
$kirim = $this->leo_mail->kirim($param);
if ($kirim['status'] == 1) {
#password history
$insert_pass = array(
"pas_usr_name" => $user->usr_name,
"pas_password" => $new_password,
"pas_date" => $current_time,
"pas_opid" => $this->session->userdata("usr_name"),
"pas_update" => $current_time
);
$this->m_pass->insert_pass($insert_pass);
$hasil['pesan'] = "Password has been reset and user has been notified via email. ";
$hasil['status'] = 1;
//update the database, store the reset code
$update = array();
$update['usr_last_cpass'] = date("Y-m-d H:i:s");
$update['usr_needchgpwd'] = "Y";
$update["usr_password"] = $new_password;
$kondisi = array("usr_name" => $user->usr_name);
$q = $this->m_ess->update_user($update, $kondisi);
} else {
$hasil['pesan'] = "Fail to send email your password reset code.";
$hasil['status'] = 0;
}
}
}
echo json_encode($hasil);
}
}
and here's the '$this->leo_mail->kirim function
function kirim($param) {
$q=$this->ci->m_smtp->get_mail_konfig();
$hasil=array();
if($q->num_rows()<1) {
$hasil['pesan']="Your SMTP configuration has not been set up properly";
$hasil['status']=0;
} else {
if(valid_email($param['recipient'])) {
$config=array();
$config_data= $q->row();
$config['protocol'] = "smtp";
$config['useragent'] = "HRISSMTPLIB";
$config['smtp_port'] = $config_data->smt_smtp_port;
$config['smtp_host'] = $config_data->smt_smtp_host;
$config['smtp_user']= $config_data->smt_smtp_user;
$config['smtp_pass']= $this->ci->leo_enkripsi->decrypt($config_data->smt_smtp_pass,$this->key);
$config['newline']="\r\n";
$config['wordwrap'] = FALSE;
$config['starttls']=($config_data->smt_encrypt_type==3)?TRUE:FALSE;
$config['mailtype'] = "html";
$this->ci->email->initialize($config);
$this->ci->email->from($config_data->smt_email,$config_data->smt_name);
$this->ci->email->to($param['recipient']);
$this->ci->email->subject($param['subject']);
$this->ci->email->message($param['content']);
if($this->ci->email->send()) {
$hasil['pesan']="Email sent";
$hasil['status']=1;
} else {
$hasil['pesan']= $this->ci->email->print_debugger();
$hasil['status']=0;
}
} else {
$hasil['pesan']="Recipient email is not valid";
$hasil['status']=0;
}
}
return $hasil;
}
Sorry for my bad english.
Thank you in advance.
I am creating a API for android developer in PHP in which he want to delete some values from database and want to show a message after that.
Now the problem is this data is deleting successfully but this API always shows else part message after complete the process. If I remove the else part its return the null which crash the android app. So I just want to give a proper json message to the android developer
Here is the code which I am trying
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1)
{
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_count as $table_count)
{
$user_count = mysql_query("select * from $table_count where user_name = '$user_name'");
$total_user_count = mysql_num_rows($user_count);
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
}
}
I know there is something wrong with this logic. But I need expert advise where my logic is wrong and what I have to do make it success
Problem with your original code, is that you are setting success/failure inside the loop. One of the four table may/may not contain the username. And if the last table don't have that, then as per your logic you are getting "record not found" even if previous iteration of the loop deleted data from the tables where username exists.
<?php
$conn = mysqli_connect(.....);
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1) {
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
$userHistoryDeleted = 0;
foreach($tables_count as $table_count) {
//if history is found, then it will be deleted otherwise not
mysql_query("delete from $table_count where user_name = '$user_name'");
if(mysqli_affected_rows($conn)) {
$userHistoryDeleted = 1;
}
}
$msg = 'Record Not Found!';
if($userHistoryDeleted) {
$msg = 'Clear Successfully All History!';
}
$response['success'] = $userHistoryDeleted;
$response['user']['error_msg'] = $msg;
}
Change your code :
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
to this one
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
}
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}