Force error message to Zend Form Element - php

// Process the forms
if (($this->getRequest()->isPost())
&& ($this->getRequest()->isXmlHttpRequest())) {
// Initiate response
$status = false;
$msg = '';
$zf = null;
// Error test
$form->getElement('no')->addError('This is the error message');
if ($form->isValid($this->getRequest()->getPost())) {
// Everything is good
$status = true;
} else {
// Get the error messages
$zf = $form->getMessages();
}
// Setup the response
$result = json_encode(array('status' => $status,
'msg' => $msg,
'zf' => $zf));
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout()->disableLayout();
$this->getResponse()->setHeader('Content-Type', 'application/json');
$this->getResponse()->setBody($result);
return;
} else {
// Populate the form
}
As you can see, I've used $form->getElement('no')->addError('This is the error message'); to force error on the form element, but $form->getMessages(); would still return NULL. So, what should I do to force error on the selected form element?

I think you've got the get the ErrorMessages()
$form->getErrorMessages()

I've opened a bug report for this issue: http://framework.zend.com/issues/browse/ZF-11088. I'll update this question if there's any new progress.

Related

Http failure during parsing for - angular http post to php

I am able to consume the php endpoint from postman. I try to do the same from angular post, I get this error - Http failure during parsing for. Even though everything looks perfect to me, the problem is surprising. Here is my snippet
php file
<?php
header('Access-Control-Allow-Origin: *');
// check for post
if ($_SERVER['REQUEST_METHOD']=='POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$conn = new db_CONNECT();
$cone=$conn->con;
//escpae the strings to be inserted to DB
$escapedname = mysqli_real_escape_string($cone, $name);
$escapedemail = mysqli_real_escape_string($cone, $email);
$escapedsubject= mysqli_real_escape_string($cone, $subject);
$escapedmessage = mysqli_real_escape_string($cone, $message);
// mysql inserting a new row
$sql = "INSERT INTO contacts(name, email, subject, message) VALUES ('$escapedname', '$escapedemail', '$escapedsubject', '$escapedmessage')";
// $result= $cone -> query($sql);
// $affected = $cone -> affected_rows;
if (mysqli_query($cone,$sql)) {
echo "Information saved successfully.";
} else {
echo "Not successful";
}
} else {
echo "Some field missing.";
}
?>
here is the angular snippet
saveContactDetails = function () {
this.proceed = true;
this.success = false;
const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
data.append('name', this.contactDeJson.name);
data.append('email', this.contactDeJson.email);
data.append('subject', this.contactDeJson.subject);
data.append('message', this.contactDeJson.message);
this.http
.post('http://localhost:80/'+'api/create_contact.php', data.toString(), {headers: myheader})
Please why am I getting this error
{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost/api/create_contact.php","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://localhost/api/create_contact.php",
I believe the issue is that your angular script is expecting a json response (the default responseType), but not receiving the correct headers or data. In stead of just echoing out your result in php, I would make a function that can handle sending the response. Something like this:
function sendJsonResponse(data, status = 200) {
header('Content-Type: application/json', true, status);
echo json_encode($data);
exit();
}
In stead of of doing this:
echo "Not successful";
You can now do this:
sendJsonResponse("Not successful", 500);
This should give you more valuable information in the frontend. And the response should now be formatted correctly, and no longer produce the parse error in angular that you are getting now.
I believe you are trying to send some query parameters using data variable. You could actually send a JS object as the parameters. Try the following
private saveContactDetails() {
this.proceed = true;
this.success = false;
const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
const data = {
'name': this.contactDeJson.name,
'email': this.contactDeJson.email,
'subject': this.contactDeJson.subject,
'message': this.contactDeJson.message
}
this.http.post('http://localhost:80/'+'api/create_contact.php', { params: data }, { headers: myheader })
}

Adding PHPMailer Without Composer

I have this contact form but I am confused as to how I can insert PHPMailer (without Composer) into the script?
I am not sure how to properly add it so that way, once it processes and sends the form it alerts the user. I do not have the ability to utilize composer, so I would need to upload PHPMailer into the directory.
<?php
function validateRecaptcha($secret, $clientResponse, $clientIp)
{
$data = http_build_query([
"secret" => $secret,
"response" => $clientResponse,
"remoteip" => $clientIp,
]);
$options = [
"http" => [
"header" =>
"Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($data)."\r\n",
"method" => "POST",
"content" => $data,
],
];
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify",
false,
stream_context_create($options)
);
if($response === false)
{
return false;
}
else if(($arr = json_decode($response, true)) === null)
{
return false;
}
else
{
return $arr["success"];
}
}
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['firstName']))
$errors['firstName'] = 'First Name is required.';
if (empty($_POST['lastName']))
$errors['lastName'] = 'Last Name is required.';
if (empty($_POST['companyName']))
$errors['companyName'] = 'Company Name is required.';
if (empty($_POST['companyAddress']))
$errors['companyAddress'] = 'Company Address is required.';
if (empty($_POST['city']))
$errors['city'] = 'City is required.';
if (empty($_POST['state']))
$errors['state'] = 'State is required.';
if (empty($_POST['emailAddress']))
$errors['emailAddress'] = 'Email Address is required.';
if (empty($_POST['comment']))
$errors['comment'] = 'Comment is required.';
if (empty($_POST['g-recaptcha-response']))
$errors['captcha'] = 'Captcha is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
{
$errors['recaptcha'] = 'Captcha is required.';
}
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
Without autoloader:
<?php
//You shall use the following exact namespaces no
//matter in whathever directory you upload your
//phpmailer files.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Now include the following following files based
//on the correct file path. Third file is required only if you want to enable SMTP.
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
?>
You shall add the following class to initiate the mailer after checking if your query or condition is executed.
<?php
$mail = new PHPMailer(true);
?>
You shall find a nice and simple example at https://github.com/PHPMailer/PHPMailer/blob/master/README.md to start with.
I hope it helps.

I cannot get the value i send using http post in Angular2 to my PHP backend

The below code is angular2 form submission code,i am sending a test username and password
logForm(formData){
console.log('Form data is ', formData.title);
var link = 'http://test/index.php/api/userAuth';
var headers = new Headers();
headers.append("Content Type","application/json");
var data = JSON.stringify({
username:'user',
password:'user123'
});
this.http.post(link,data,headers)
.subscribe(data => {
console.log(data.json());
});
}
The PHP side is in codeigniter using REST architecture, php code is given below
function userAuth_post() {
if (($this->post('username') == '') || ($this->post('password') == '')) {
$this->response(array('message' => 'Network Error! Try Again!!!'), 200);
}else{
$this->response(array('message' => 'Success'), 200);
}
}
Now i am receiving "Network Error! Try Again!!!", i should be getting "Success".
Edit: I missed the point that it's input stream
Try this instead:
$this->input->input_stream('field');
if ( ! $this->input->input_stream('username') || ! $this->input->input_stream('password')) {
$this->response(array('message' => 'Network Error! Try Again!!!'), 200);
}else{
$this->response(array('message' => 'Success'), 200);
}
this is how you can get php://input in CodeIgniter:
$this->input->raw_input_stream;
Read more: Here
I got it working by using
function userAuth_post() {
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$userName = $request->username;
$userPass = $request->password;
}
if (($userName == '') || ($userPass == '')) {
$this->response(array('message' => 'Network Error! Try Again!!!'), 200);
}else{
$this->response(array('message' => 'Success'), 200);
}
}
In Codeigniter we can use
$postdata = $this->input->raw_input_stream;
Don't know whether this is the best answer, but i am going with it now, would be good if someone can correct it if there is an better solution.

Cloudant and Php-on-Couch not working well due to continue

I believe Cloudant has recently changed some of their code. Recently, if you do a storedoc operation, in a try/catch statement. Cloudant will return an 'error' to the framework:
Uncaught exception 'couchException' with message 'Continue
Of course you can handle it in the catch statement, but it should really be coming back as 'successful' in the Try statement of the PHP-on-Couch library.
Anyone come across this or know how to handle it? The biggest issues is that you cannot grab the ID and Rev in the catch statement because it's coming up as an error:
try { // does not return here, goes to catch
$response = $client->storeDoc($doc);
$response_json['status'] = 'success';
$response_json['id'] = $response->id;
$response_json['rev'] = $response->rev;
} catch (Exception $e) { // even though the doc is successfully storing
// check for accepted BEG
$error = '';
$error = $e->getMessage();
$err_pos = strpos($error,"Accepted");
$err_pos_2 = strpos($error,"Continue");
if($err_pos !== false OR $err_pos_2 !== false){ // success
$response_json['status'] = 'success';
$response_json['id'] = $response->id; // returns null
$response_json['rev'] = $response->rev; // returns null
} else { // truely an error
$response_json['status'] = 'fail';
$response_json['message'] = $e->getMessage();
$response_json['code'] = $e->getCode();
}
// check for accepted END
}
I tested in both CouchDB and Cloudant and the behavior is the same. This is what I believe is happening. When you create a new couchDocument:
$doc = new couchDocument($client);
By default the document is set to autocommit. You can see this in couchDocument.php:
function __construct(couchClient $client) {
$this->__couch_data = new stdClass();
$this->__couch_data->client = $client;
$this->__couch_data->fields = new stdClass();
$this->__couch_data->autocommit = true;
}
As soon as you set a property on the document:
$doc->set( array('name'=>'Smith','firstname'=>'John') );
storeDoc is immediately called. You are then trying to call storeDoc a second time and couchDB returns an error.
There are 2 ways to fix this:
Turn off autocommit:
$doc = new couchDocument($client);
$doc->setAutocommit(false);
$doc->set( array('name'=>'Smith','firstname'=>'John') );
try {
$response = $client->storeDoc($doc);
$response_json['status'] = 'success';
$response_json['id'] = $response->id;
$response_json['rev'] = $response->rev;
Keep autocommit on and get the id and rev from the $doc after you set a property:
$doc = new couchDocument($client);
try {
$doc->set( array('name'=>'Smith','firstname'=>'John') );
$response_json['status'] = 'success';
$response_json['id'] = $doc->_id;
$response_json['rev'] = $doc->_rev;

Slim v2 to Slim v3 Upgrade

I have been using Slim v2 for my APIs and am thinking about upgrading to v3.
Unfortunately I have limited experience and could use your help on a code example below.
This is the login code:
$app->post('/register', function() use ($app) {
// check for required params
verifyRequiredParams(array('name', 'email', 'password'));
$response = array();
// reading post params
$name = $app->request->post('name');
$email = $app->request->post('email');
$password = $app->request->post('password');
// validating email address
validateEmail($email);
$db = new DbHandler();
$res = $db->createUser($name, $email, $password);
if ($res == USER_CREATED_SUCCESSFULLY) {
$response["error"] = false;
$response["message"] = "You are successfully registered";
} else if ($res == USER_CREATE_FAILED) {
$response["error"] = true;
$response["message"] = "Oops! An error occurred while registereing";
} else if ($res == USER_ALREADY_EXISTED) {
$response["error"] = true;
$response["message"] = "Sorry, this email already existed";
}
// echo json response
echoRespnse(201, $response);
});
Here is the validateEmail function:
function validateEmail($email) {
$app = \Slim\Slim::getInstance();
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$response["error"] = true;
$response["message"] = 'Email address is not valid';
echoRespnse(400, $response);
$app->stop();
}
}
How do I get an Instance of app in Slim v3 to actually stop the app when input criteria are not met?
I would appreciate it if you could give me an example with the help of my code.
Thanks for the help!
EDIT
The above issue was solved. Unfortunately, a new issue arose after checking my code.
I have a middle layer to authenticate the user:
function authenticate(\Slim\Route $route) {
// Getting request headers
$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
// Verifying Authorization Header
if (isset($headers['Authorization'])) {
//omitted code
} else {
// api key is missing in header
$response["error"] = true;
$response["message"] = "Api key is misssing";
echoRespnse(400, $response);
$app->stop();
}
In my main code i implement function authenticate as follows:
$app->get('/tasks', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
//ommit some code
echoRespnse(200, $response);
});
Would you know how to do this in Slim v3?
I would really appreciate your help.
In Slim3, return $response (return Response object) is a better way to stop app.
So how is the below?
$app->post('/register', function($request, $response, $args) {
// omit some codes
if(!validateEmail($request->getParsedBodyParam('email'))){
return $response->withJson(['message' => 'Email address is not valid', 'error' => true], 400);
}
// omit some codes
}
validateEmail function is changed to like below.
function validateEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false
}
return true;
}
Hope it will help you.

Categories