<?php
if(isset($_POST['submit']))
{
$file = 'entries.json';
$json_file = file_get_contents($file);
$parsed_json = json_decode($json_file, true);
$email = $_POST['email'];
$flag = false;
foreach ($parsed_json as $key => $value)
{
if ($value['email'] == $email)
{
$flag = true;
break;
}
}
if ($flag)
{
$arr = array(
"centre" => $_POST['centre'],
"name" => $_POST['name'],
"email" => $_POST['email'],
"phone" => $_POST['phone'],
"city" => $_POST['city'],
"course" => $_POST['course']
);
$json_string = json_encode($arr);
$success = file_put_contents($file, $json_string);
if($success == true)
{
echo "<p class='text-success'>Thank you for showing interest. Please contact your counsellor for Unique Registration Number (URN)<p>";
}
}
else
{
echo "<p class='text-danger'>Email already exist.<p>";
}
}
?>
In the above code I am trying to validate with email id already exist when we post form data in json format. Here, Json format working perfectly but it always show thank you message. If email exist or not.
When I click on submit then all data post and convert in json successfully and I am fetching this data in other website but I want to show here that email id already exist. So, How can I do this? Please help me.
Thank You
Related
I am experiencing some strange behavior when using json_encode.
This is my code:
if($_POST["action"] == 'profile')
{
sleep(2);
$error = '';
$success = '';
$admin_name = '';
$admin_contact_no = '';
$admin_email = '';
$admin_profile = '';
$data = array(
':admin_email' => $_POST["admin_email"],
':admin_id' => $_POST['hidden_id']
);
$visitor->query = "
SELECT * FROM admin_table
WHERE admin_email = :admin_email
AND admin_id != :admin_id
";
$visitor->execute($data);
if($visitor->row_count() > 0)
{
$error = '<div class="alert alert-danger">User Email Already Exists</div>';
}
else
{
$user_image = $_POST["hidden_user_image"];
if($_FILES["user_image"]["name"] != '')
{
$user_image = upload_image();
}
$admin_name = $visitor->clean_input($_POST["admin_name"]);
$admin_contact_no = $_POST["admin_contact_no"];
$admin_email = $_POST["admin_email"];
$admin_profile = $user_image;
$data = array(
':admin_name' => $admin_name,
':admin_contact_no' => $admin_contact_no,
':admin_email' => $admin_email,
':admin_profile' => $admin_profile
);
$visitor->query = "
UPDATE admin_table
SET admin_name = :admin_name,
admin_contact_no = :admin_contact_no,
admin_email = :admin_email,
admin_profile = :admin_profile
WHERE admin_id = '".$_POST['hidden_id']."'
";
$visitor->execute($data);
$success = '<div class="alert alert-success">User Details Updated</div>';
}
$output = array(
'error' => $error,
'success' => $success,
'admin_name' => $admin_name,
'admin_contact_no' => $admin_contact_no,
'admin_email' => $admin_email,
'admin_profile' => $admin_profile
);
echo json_encode($output);
}
Alert message for $error displays accordingly while alert message for $success does not.
If I swap positions between $error = '<div class="alert alert-danger">User Email Already Exists</div>'; and $success = '<div class="alert alert-success">User Details Updated</div>';, $error still works while $success still does not, which deeply confuses me.
I know I can avoid all this trouble by using echo, but I really want to find out what the issue is here.
Thank you for your help.
It was just a spelling error, wrote "succes" instead of "success".
I apologize for the trouble and thank you for your help.
I'm trying to edit a JSON file using php, I've set up a little ReactJS app has form elements.
My JSON is as follows
[
{
"id": 1,
"Client": "client 1",
"Project": "project 1",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-1"
},
{
"id": 2,
"Client": "client 2",
"Project": "project 2",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-2"
},
{
"id": 3,
"Client": "client 3",
"Project": "project 3",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-3"
}
]
So far i have code to create a new "project" at the end of the file. My PHP is as follows
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$clientName = $_POST['clientName'];
$ProjectName = $_POST['projectName'];
$url = strtolower($_POST['url']);
$date = date('Y/m/d H:i:s');
$message = "";
$url = '../json/projects.json';
if( file_exists($url) )
if(file_exists('../json/projects.json'))
{
$current_data = file_get_contents('../json/projects.json');
$array_data = json_decode($current_data, true);
$extra = array(
'id' => count($array_data) + 1,
'Client' => $clientName,
'Project' => $ProjectName,
'StartDate' => $date,
'CompletedDate' => "",
'projectUrl' => $projectFileName + ".json"
);
$array_data[] = $extra;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents('../json/projects.json', $final_data))
{
$message = "sent";
}
else
{
$message = "notSent";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
What i can figure out is how to edit lets say "CompletedDate" value to todays date with a click of the button.
I have an hidden input field on my page that has the project ID in, so what I'm after is helping getting that id, matching it to the JSON, then editing the completed date that matches the ID.
This PHP will fire using ajax so i can pass the ID pretty easy.
Using similar code to what you already use, you can update the relevant data by using the ID as the index into the decoded JSON file. As ID 1 will be the [0] element of the array, update the [$id-1] element with the date...
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$id = 2; // Fetch as appropriate
$date = date('Y/m/d H:i:s');
$url = '../json/projects.json';
if( file_exists($url) )
{
$current_data = file_get_contents($url);
$array_data = json_decode($current_data, true);
$array_data[$id-1]['CompletedDate'] = $date;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents($url, $final_data))
{
$message = "updated";
}
else
{
$message = "notUpdated";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
You may need to tweak some of the bits - especially how the ID is picked up ($_GET?) and any messages you want.
I've also updated the code to make more consistent use of $url as opposed to hard coding it in a few places.
I wasn't entirely sure how to search for this question, so if it has been asked before please send me in the right direction.
I have a validation function with an array. Inside my array I have set up errors to be displayed if one of the form fields doesn't validate. If the user fills a field out wrong, they should get an error of which field was wrong and the form should be still present. However, they get a blank page with only the generic error (the one I echo when I called the function) and not the field-specific error. Can someone please tell me where I went wrong?
$output_form = 1; //control if form displays - yes
$error_text = '';
//declare form elements (empty first load)
$fname = '';
$valid_fname = 0;
$fname_regex = '/^([A-Z]|[a-z]){2,15}$/';
$fname_error_message = 'First name must be 2-15 alphabetic characters only.<br>';
$lname = '';
$valid_lname = 0;
$lname_regex = '/^([A-Z]|[a-z]){2,15}$/';
$lname_error_message = 'Last name must be 2-15 alphabetic characters only.<br>';
$phone = '';
$valid_phone = 0;
$phone_regex = '/^\(\d{3}\)\d{3}-\d{4}$/';
$phone_error_message = 'Phone number must be in (xxx)xxx-xxxx format.<br>';
$city = '';
$valid_city = 0;
$city_regex = '/^([A-Z]|[a-z]){2,15}$/';
$city_error_message = 'City must be 2-15 alphabetic characters only.<br>';
$state = '';
$valid_state = 0;
$state_regex = '/^([A-Z]|[a-z]){2}$/';
$state_error_message = 'State must be 2 alphabetic characters only.<br>';
//data posted
if (isset($_POST['submit'])) {
if ($debug) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
}//end debug
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$phone = trim($_POST['phone']);
$city = trim($_POST['city']);
$state = trim($_POST['state']);
$phone_replace = preg_replace('/[\(\)\-\s]/', '', $phone);
function validate_form($fields, &$errors = []) {
$errors = [];
foreach ($fields as $name => $field) {
if (!preg_match ($field['regex'], $field['value'])) {
$errors[$name] = $field['error'];
$output_form = 1;
}
}
return empty($errors); //returns true/false
}
$fields = [
'fname' => ['regex' => $fname_regex, 'value' => $fname, 'error' => $fname_error_message],
'lname' => ['regex' => $lname_regex, 'value' => $lname, 'error' => $lname_error_message],
'phone' => ['regex' => $phone_regex, 'value' => $phone, 'error' => $fname_error_message],
'city' => ['regex' => $city_regex, 'value' => $city, 'error' => $city_error_message],
'state' => ['regex' => $state_regex, 'value' => $state, 'error' => $state_error_message],
];
$errors = [];
if (!validate_form($fields, $errors)) {
echo "<p>One of your fields is invalid. Please check and re-submit.</p>";
$output_form = 1;
return (false);
}
else {
$output_form = 0;
}
foreach($errors as $error) echo "<p>$error</p>";
Actually outputting stuff usually helps ;)
I am using Instamojo for my laravel app.
I have a form with input name like vtype, vname, name, phone, date, price.
My instamojo index.php looks like this --
<?php
use App\Vname;
$vname = Vname::find($request->vname);
$api = new Instamojo\Instamojo(config('instamojo.api_key'), config('instamojo.auth_token'), 'https://test.instamojo.com/api/1.1/');
try {
$response = $api->paymentRequestCreate(array(
"purpose" => "Online Vazhipad",
"amount" => $vname->price,
"buyer_name" => $request->name,
"phone" => $request->phone,
"send_email" => true,
"email" => Auth::user()->email,
"allow_repeated_payments" => false,
"redirect_url" => url('/online_vazhipad/thankyou')
"webhook" => url('/online_vazhipad/webhook')
));
$pay_ulr = $response['longurl'];
header("Location: $pay_ulr");
exit();
}
catch (Exception $e) {
print('Error: ' . $e->getMessage());
}
?>
and my webhook file looks like this -
<?php
$data = $_POST;
$mac_provided = $data['mac'];
unset($data['mac']);
$ver = explode('.', phpversion());
$major = (int) $ver[0];
$minor = (int) $ver[1];
if($major >= 5 and $minor >= 4){
ksort($data, SORT_STRING | SORT_FLAG_CASE);
}
else{
uksort($data, 'strcasecmp');
}
$mac_calculated = hash_hmac("sha1", implode("|", $data), config('instamojo.private_salt'));
if($mac_provided == $mac_calculated){
echo "MAC is fine";
if($data['status'] == "Credit"){
// Payment was successful my database code will be placed here
}
else{
return 'failed';
}
}
else{
echo "Invalid MAC passed";
}
?>
I wanted to add more information to my database like vtype and vname, but I dont know how to get the data from the form to here.
From the documentation i came to know that, the post request we get from instamojo only contains this much.
Please help me.
I have Yii radio button list as follows.
forgotpassword1.php
<?php echo $form->radioButtonList($model, 'send_option', $email_exist); ?>
This is the action for forgotpassword1.
public function actionForgotpwd2() {
$model = new User;
$email_exist = array('mobile' => 'Send SMS to Mobile');
$model -> setScenario('forgotpwd2');
$model -> send_option='mobile';
$postvars = array('conn' => Yii::app()->session['mobile']);
$postRes = SCAppUtils::getInstance()->post_request('accounts', 'CheckAccount', $postvars);
$out_arr = json_decode($postRes, true);
//print_r($out_arr);
if ($out_arr['success'] == true && $out_arr['email'] == true) {
$email_exist['email'] = 'Send an E-mail';// = array('mobile' => 'Send SMS to Mobile', 'email' => '');
} else if ($out_arr['success'] == false) {
Yii::app()->user->setFlash('error', $out_arr['error']);
$this->redirect(array('forgotpwd1'));
}
if (!empty($_POST['User'])) {
$model->attributes = $_POST['User'];
echo Yii::app()->session['mobile'];
//print_r($_POST);
if(isset($_POST['User']['send_option'])) {
//Yii::app()->session['send_option'] = $model->send_option;
echo Yii::app()->session['send_option'];
$postvars = array('conn' => Yii::app()->session['mobile'], 'send_type' => $model->send_option);
$postRes = SCAppUtils::getInstance()->post_request('accounts', 'ChangePassword', $postvars);
$out_arr = json_decode($postRes, true);
// print_r($out_arr);
if ($out_arr['success'] == true) {
$this->redirect(array('forgotpwd3'));
} else {
Yii::app()->user->setFlash('error', $out_arr['error']);
}
}
}
$this->render('forgotpwd2', array(
'model' => $model, 'email_exist' => $email_exist
));
}
Here I call a function named "ChangePassword()" from my backend application. One of the parameters passed to the backend is send_type: mobile or email. The problem is it will always takes mobile as the send_type.
I've used
$model -> send_option='mobile';
to set the default value as mobile.
Why it always takes mobile as the send type.
Any suggestions are appreciated.
Thank you in advance
Try with this :
<?=$form->radioButtonList($model,'send_option',array(1=>'Mobile',2=>'Email'))?>
In your Acion :
To set the default value :
$model -> send_option=1;
To get the checked value (check whether it's 1 or 2) :
$_POST['send_option']