Form Post Data As Array Value - php

I'm trying to integrate an API builder to my control panel through a form or post data. I can't figure out how to put the post data as the value for the array.
I tried using print_r($_POST['VALUE']) with and without quotes.
I tried using just $_POST['VALUE'] with and without quotes.
I also tried to set $value = $_POST['VALUE'] then using $value with and without quotes but that caused an error 500.
Here is the code I am trying to use:
$res = $api->remoteCall('requestLogin', array(
'type' => 'external',
'domain' => 'print_r($_POST['domain'])',
'lang' => 'en',
'username' => 'print_r($_POST['uname'])',
'password' => 'print_r($_POST['pass'])',
'apiUrl' => '127.0.0.1',
'uploadDir' => '/web/'.print_r($_POST['domain']).'/public_html',
I apologize as I am new to PHP, but thank you in advance.

I'm not sure what other logic is being done there, how the post variables are being sent to the script your sample code is running on, or any of the other details which might point towards a more complete solution but here are some basic tips to help you troubleshoot.
The post variables should be formatted like this:
$res = $api->remoteCall('requestLogin', array(
'domain' => $_POST['domain'],
You can dump the entire post array to the screen by doing
print_r($_POST);
This should output your array to the screen so you can verify that you're receiving the post data in the code and should help you fix any typos or misnamed post variables. If the array has the key as $_POST['domainName'] and you're echoing $_POST['domain']
You're calling code (the "form or post data") should have the post fields in place and named correctly in order for them to be sent to the script
<input type="text" name="domain">
You should be performing some basic validation on your post fields before adding them to something that's going to be stored anywhere or sent off to a third-party. At the most minimal you'll want to check that there is a value being set for the essential fields (required fields) and I'd look to make sure the values are matching requirements of the API you're passing them off to.

Several things may go wrong when using api. POST values, input values, API call or connection or maybe api response. So not only at the time of implementation and coding but also when integrating api call script with the application there should be some sort of testing and error handling in place. A simple script can be like this
$error = array();
$request = array();
$request['type'] = 'external';
if (isset($_POST['domain']) && !empty($_POST['domain'])) {
$request['domain'] = $_POST['domain'];
$request['uploadDir'] = "/web/{$_POST['domain']}/public_html";
} else {
$error[] = "Domain is empty";
}
if (isset($_POST['uname']) && !empty($_POST['uname'])) {
$request['username'] = $_POST['uname'];
} else {
$error[] = "Username is empty";
}
if (isset($_POST['pass']) && !empty($_POST['pass'])) {
$request['password'] = $_POST['pass'];
} else {
$error[] = "Username is empty";
}
$request['lang'] = 'en';
$request['apiUrl'] = '127.0.0.1';
if (count($error) > 0) {
echo implode( "<br>" , $error );
} else {
try{
$res = $api->remoteCall('requestLogin',$request);
} catch ( Exception $e ) {
print_r($e);
exit();
}
}

Related

using $_GET['VALUE'] from a FORM using method POST

I am troubleshooting CAPTCHA problem in someone Else's code, where the form method is "POST"
But in the action.php file the code is like this:
$key=substr($_SESSION['key'],0,5);
$number = $_GET['img_code'];
if($_GET['img_code']){
if($number==$key)
{
echo "done";
exit();
}
else
{
echo false;
exit();
}
}
I have tried to var_dump($_GET['img_code']) and as expected I am getting null value.
but if I am doing it var_dump($_POST['img_code']) I am getting the correct value.
but once I am setting it to POST, I start getting error "captcha not entered correctly.
Any help will be greatly appreciated.
UPDATE:
FORM METHO
<form action="{$Site_Root}signup.php" method="post" class="frmRegister tutor-registration" name="frmRegister" id="frmRegister" enctype="multipart/form-data" >
Further Update:
If I am using $_REQUEST['img_code'] and then doing a var_dump I am getting the matching string for $key and $number like
string(5) "f065a" string(5) "f065a"
but problem is when I am applying this as a condition for example:
I am getting - "captcha not entered correctly."
if(isset($_POST['email'])){
if ($key==$number){ // condition line is added by me
if(!empty($_FILES['photo']['name']))
{
$_POST['photo'] = fileUpload($_FILES['photo'],TUTOR);
$thumb->image($physical_path['Tutor'].$_POST['photo']);
$thumb->size_width(120);
$thumb->jpeg_quality(100);
$filename = $thumb->get2(); //small_thumb_
}
else
{
$_POST['photo'] = "";
}
$tutor_id = $tut->Insert($_POST);
$to_email = $_POST['email'];
global $mail;
$mail = '';
$mail = new htmlMimeMail();
$mail->setFrom($config[WC_CONTACT_US]);
//Set Cc
// $mail->setCc(array($config[WC_CONTACT_US]));
$mail->setSubject('Welcome to TuitionJobsPortal.com!');
$tpl2 = new Smarty;
$tpl2->template_dir = $physical_path['EmailTemplate'];
$tpl2->compile_dir = $physical_path['Site_Root']. 'templates_c/';
$tpl2->debugging = DEBUG;
$tpl2->assign(array("membername" => $_POST['tutor_name'],
"vcode" => $_POST['verification_code'],
"tutor_id" => $tutor_id,
"Templates_Image" => $virtual_path['Site_Root'].'templates/images/',
"Site_Root" => $virtual_path['Site_Root'],
));
$content = $tpl2->fetch('registration'. $config['tplEx']);
$mail->setHtml($content);
$result = $mail->send(array($to_email));
header("location: signup.php?signup=true");
exit();
}
} //this is added.
I don't think you can access $_POST data from $_GET , so either change form method to GET or access posted data using $_POST['img_code'] .
You can use the $_REQUEST global variable, it can do the work of both GET and POST,

php: receive json from POST and save to file

I want to receive a POST request from a JS client with a json body (i.e. this is not form data), and save the .gigs (javascript) array to a file, after checking the .password field. This is all my code (based on Receive JSON POST with PHP)
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params)){
/* json_decode(..., true) returns an 'array', not an 'object'
* Working combination: json_decode($json_params) WITH $inp->password
*/
$inp = json_decode($json_params);
} else {
echo "could not decode POST body";
return;
}
$password = $inp->password;
// echo $password;
if ($password == "****") {
$gigs = $inp['gigs'];
// WAS $res = file_put_contents('gigs.json', json_encode($gigs), TEXT_FILE);
$res = file_put_contents('gigs.json', json_encode($gigs));
if ($res > 0) {
echo "Success";
return;
} else {
if (!$res) {
http_response_code(500);
echo "file_put_contents error:".$res;
return;
} else {
http_response_code(500);
echo "Error: saved zero data!";
return;
}
}
}
else {
// http_response_code(403); // (2)
echo "Password invalid";
return;
}
What I find is that
if I comment out the if statement and uncomment echo $password; then the right password is there
if I uncomment line 2, which I want to do, then I get back a 500 and the error logs refer an Illegal string offset 'password' in line (1) above. Without that I get back a "Success" (all for the same password).
I don't understand what is happening, nor how to get 200, 403 and 500 error messages safely.
Note
$json_params = file_get_contents("php://input");
If your scripts are running upon regular HTTP requests, passing data like it comes from HTML form, them you should consider using $_POST for your content, not php://input. If you expect JSON in request body, then I'd be fine, yet I'd also check content type for application/json.
Next:
$inp = "I never got set";
if (strlen($json_params) > 0 && isValidJSON($json_params)){
$inp = json_decode($json_params, true);
}
$password = $inp->password;
$password = $inp['password'];
This is pretty broken. First, see json_decode() arguments (2nd) -> you are decoding to array (true), not object (false), so only $password = $inp['password']; will work in your case. Also the whole code will fail when your input data is invalid as in that case $np is rubbish string, not the array you try to read later on. Use null as default value and check for that prior further use.
Next:
$res = file_put_contents('gigs.json', json_encode($gigs), FILE_TEXT);
there's no FILE_TEXT option for file_put_contents(). Nor you'd need one.
Once you correct these you'd be fine. Also print_r() and var_dump() may be the functions you wish to get familiar with for your further debugging.
In general http://php.net/ -> lookup for functions you are about to use.

PHP-5.4.44, Apache Phusion Passenger not supporting POST request parameters

I have a php file that pulls JSON response from my database.
The problem is that the same file works fine on my local but not after I upload it to the server. There are parameters that I pass with the URL and the php code just goes to the else part towards the end as it cannot find the parameters
Any help on this would be appreciated.
the php code in my index file is below:
<?php
ini_set('display_errors',1);
error_reporting(1);
if (isset($_POST['tag']) && $_POST['tag'] != '') {
$tag = $_POST['tag'];
require_once 'DB_Functions.php';
$response = array("tag" => $tag, "error" => FALSE);
// check for tag type
if ($tag == 'username') {
$username = trim($_POST['username']);
if(isset($username) && !empty($username)) {
$response = isUserRegistered($username);
echo json_encode($response);
}
}
}
else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter 'tag' is missing!";
echo json_encode($response);
}
I have tried using $_REQUEST['tag'] instead of $_POST['tag']
I tried echo $_POST['tag']; die; before the IF condition but that returns no data:
response contains no data
I was able to fix the issue.
mysql_connect function was deprecated due to php version 5.4.
Also, the mysql option was not checked under phpversion section by default, makes me feel a little foolish that I didnt think about that before
Reverted the server php version to 5.3 and check mysql which took care of the issue

Multiple IF statements in simple form validation

I am a newbie and trying to implement a simple validation script after reading up, but I can't see how I can have multiple Ifs that will only do an sql insert if all required fields are met. Rather than having the multiple else statements, what is a syntax approach for having all the form validation Ifs together and if one of them fails, then the correct error is shown and the sql is not execute?
if(isset($_POST ['submit'])){
$user_ID = get_current_user_id();
$catErr = $ratingErr = $titleErr = $textErr = "";
if (empty($_POST["category"])) {
$catErr = "Category is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["rating"])) {
$ratingErr = "Rating is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["post_name"])) {
$postErr = "Title is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["text"])) {
$textErr = "Text is required";
} else {
//DO THE INSERT BELOW!
}
//PDO query begins here...
$sql = "INSERT INTO forum(ID,
category,
rating,
post_name,
text
Use one variable for all the error messages and concatenate to it in the branches, so in the end if that variable is still empty string you won't do the insert. (And you don't need any of the empty else blocks that contain nothing but a comment.)
$err = "";
if (empty($_POST["category"])) {
$err .= "<br/>Category is required";
}
if (empty($_POST["rating"])) {
$err .= "<br/>Rating is required";
}
if (empty($_POST["post_name"])) {
$err .= "<br/>Title is required";
}
if (empty($_POST["text"])) {
$err .= "<br/>Text is required";
}
//PDO query begins here...
if($err=='')
{
$sql = "INSERT INTO forum(ID,
category,
rating,
...";
...
}
There are many solutions to your problem. Here are 3 methods of solving your issue.
You could combine all of your if statements like so:
if (empty($_POST['rating']) || empty($_POST'rating']) || ... ) { ... }
and separate them by double pipes.
You could also check the entire array:
if (empty($_POST)) $error = "There was an error!";
You could set a universal error variable and then output it.
A third solution could keep your current syntax but cut down on the amount of lines. You could save lines by doing without brackets. You can create an array and push your errors to the array.
Note: You can use empty() or isset().
// create an array to push errors to
$errors_array = array();
// if a particular field is empty then push the relevant error to the array
if(!isset($_POST['category'])) array_push($errors_array, "Category is required");
if(!isset($_POST['rating'])) array_push($errors_array, "Rating is required");
...
Once you have an array full of errors you can check for them like so:
// if the array is not empty (then there are errors! don't insert!)
if (count($errors_array) > 0) {
// loop through and echo out the errors to the page
for ($i = 0; $i < count($errors_array); $i++) {
echo $errors_array[i];
}
} else {
// success! run your query!
}
You should use javascript to validate the page before it is even processed into a post. This script will run client-side when they hit submit and catch errors before they even leave the page.
Here's a tutorial on how to do something like that: tutorial
Each field can have its own validation parameters and methods, and it will also make the page's code look a lot nicer.
I got it to go with this approach after showdev got me thinking that way. It's not very elegant perhaps, but does the trick, although all the user is taken to a blank page if there are errors and it simple says: Missing category (or whatever). Wondering if I can echo a link or something back to the page with the form from there so the user has an option like "go back and resubmit". Otherwise I will have to handle and display the errors alongside the form which will require a different approach altogether...
if(isset($_POST ['submit'])){
$errors = false;
if(empty($_POST['category'])) {
echo 'Missing category.<br>';
$errors = true;
}
if(empty($_POST['rating'])) {
echo 'Missing rating.<br>';
$errors = true;
}
if(empty($_POST['post_name'])) {
echo 'Missing title.<br>';
$errors = true;
}
if(empty($_POST['text'])) {
echo 'Missing text.<br>';
$errors = true;
}
if($errors) {
exit;
}
// THEN ADD CODE HERE. But how display form again if user makes errors and sees nothing but error message on page if they miss something (which is how it works now)
Generally, if you find yourself repeatedly writing very similar statements, using some sort of loop is probably a better way to go about it. I think what you said about "handling and displaying the errors alongside the form" is really what you need to do if you want the process to be user-friendly. If you put your validation script at the top of the file that has your form in it, then you can just have the form submit to itself (action=""). If the submission is successful, you can redirect the user elsewhere, and if not, they will see the form again, with error messages in useful places.
if (isset($_POST['submit'])) {
// define your required fields and create an array to hold errors
$required = array('category', 'rating', 'post_name', 'text');
$errors = array();
// loop over the required fields array and verify their non-emptiness
foreach ($required as $field) {
// Use empty rather than isset here. isset only checks that the
// variable exists and is not null, so blank entries can pass.
if (empty($_POST[$field])) {
$errors[$field] = "$field is required";
}
}
if (empty($errors)) {
// insert the record; redirect to a success page (or wherever)
}
}
// Display the form, showing errors from the $errors array next to the
// corresponding inputs

Should I refactor this code?

The code is for a view debate page. The code is supposed to determine whether or not to show an add reply form to the viewing user.
If the user is logged in, and the user is not the creator of the debate, then check if the user already replied to the debate.
If the user did not already reply to the debate then show the form...
Otherwise, Check If the user wants to edit their already existing reply by looking in the url for the reply id
If any of these tests dont pass, Then I save the reason as an int and pass that to a switch statement in the view.
The logic seems easy enough, but my code seems a little sloppy.
Here's the code.. (using Kohana V2.3.4)
public function view($id = 0)
{
$debate = ORM::factory('debate')->with('user')->with('category')->find($id);
if ($debate->loaded == FALSE)
{
url::redirect();
}
// series of tests to show an add reply form
if ($this->logged_in)
{
// is the viewer the creator?
if ($this->user->id != $debate->user->id)
{
// has the user already replied?
if (ORM::factory('reply')
->where(array('debate_id' => $id, 'user_id' => $this->user->id))
->count_all() == 0)
{
$form = $errors = array
(
'body' => '',
'choice_id' => '',
'add' => ''
);
if ($post = $this->input->post())
{
$reply = ORM::factory('reply');
// validate and insert the reply
if ($reply->add($post, TRUE))
{
url::redirect(url::current());
}
$form = arr::overwrite($form, $post->as_array());
$errors = arr::overwrite($errors, $post->errors('reply_errors'));
}
}
// editing a reply?
else if (($rid = (int) $this->input->get('edit'))
AND ($reply = ORM::factory('reply')
->where(array('debate_id' => $id, 'user_id' => $this->user->id))
->find($rid)))
{
$form = $errors = array
(
'body' => '',
'choice_id' => '',
'add' => ''
);
// autocomplete the form
$form = arr::overwrite($form, $reply->as_array());
if ($post = $this->input->post())
{
// validate and insert the reply
if ($reply->edit($post, TRUE))
{
url::redirect(url::current());
}
$form = arr::overwrite($form, $post->as_array());
$errors = arr::overwrite($errors, $post->errors('reply_errors'));
}
}
else
{
// user already replied
$reason = 3;
}
}
else
{
// user started the debate
$reason = 2;
}
}
else
{
// user is not logged in.
$reason = 1;
}
$limits = Kohana::config('app/debate.limits');
$page = (int) $this->input->get('page', 1);
$offset = ($page > 0) ? ($page - 1) * $limits['replies'] : 0;
$replies = ORM::factory('reply')->with('user')->with('choice')->where('replies.debate_id', $id);
$this->template->title = $debate->topic;
$this->template->debate = $debate;
$this->template->body = View::factory('debate/view')
->set('debate', $debate)
->set('replies', $replies->find_all($limits['replies'], $offset))
->set('pagination', Pagination::factory(array
(
'style' => 'digg',
'items_per_page' => $limits['replies'],
'query_string' => 'page',
'auto_hide' => TRUE,
'total_items' => $total = $replies->count_last_query()
))
)
->set('total', $total);
// are we showing the add reply form?
if (isset($form, $errors))
{
$this->template->body->add_reply_form = View::factory('reply/add_reply_form')
->set('debate', $debate)
->set('form', $form)
->set('errors', $errors);
}
else
{
$this->template->body->reason = $reason;
}
}
Heres the view, theres some logic in here that determines what message to show the user.
<!-- Add Reply Form -->
<?php if (isset($add_reply_form)): ?>
<?php echo $add_reply_form; ?>
<?php else: ?>
<?php
switch ($reason)
{
case 1 :
// not logged in, show a message
$message = 'Add your ' . html::anchor('login?url=' . url::current(TRUE), '<b>vote</b>') . ' to this discussion';
break;
case 2 :
// started the debate. dont show a message for that.
$message = NULL;
break;
case 3:
// already replied, show a message
$message = 'You have already replied to this debate';
break;
default:
// unknown reason. dont show a message
$message = NULL;
break;
}
?>
<?php echo app::show_message($message, 'h2'); ?>
<?php endif; ?>
<!-- End Add Reply Form -->
Should I refactor the add reply logic into another function or something.... It all works, it just seems real sloppy.
Thanks
Edit: I took all answers into consideration. Since I wasn't adding anything new at the moment and had time to kill, I chose to refactor the code. After a little thought, a better solution popped out to me. The whole process took me about 30 minutes, and I would say it was worth it. Thanks to all for your answers
Yes, refactor. Remove the PHP and use a real language. ;)
Seriously though, do refactor - avoid nesting if statements so deeply (doing so obfuscates logic & makes testing harder) and chunk monolithic sections into separate functions/methods.
No. If you've got one more line of code to write elsewhere on this project, spend your time on that instead.
As is often the case, there will be a ton of different ways to solve the same problem your code is solving. But if you've already solved the problem then take note of what you've learnt here and move on. If this code does turn out to be a weak link later on in development, then fine; you've got proof and a concrete validation that it should be re-factored. Until then you're wasting time that could be spent pushing the project forward by re-inventing your re-invention of the wheel.
I'd say Yes. Refactor it, measure the time it takes you, then when all done assess the improvement. How much time did it take? Was it worth it? So refactor it as an experiment. And please let us know your results. Bottom line: was it worth refactoring?
avoid nested if statement :)
Yes, refactor. If you run a cyclomatic complexity analysis against this code, it would probably return a pretty high number (bad). Elaborate case/switch statements, nested if's all contribute to a higher score.
A future developer who may need to work with this codebase would potentially run a cyclomatic complexity analysis before diving in, and probably estimate that there is relatively high risk/complexity in dealing with this codebase.

Categories