How to organize your code PHP - php

I am new to PHP and I am wondering how is the best way to organize your code. I have been trying to do something with a form (form.php) on the client side to talk to a remote server using PHP (testexec.php). I have come down to the issue where my testexec.php needs to access a variable from the form.php file and so now I am wondering if I should just put all my code in form.php so I don't have to call variables from a different php file. How would you guys organize your code in this situation.
form.php
<div class="box1">
<form method="post">
<label class="col">Up/Dowb</label>
<span class="col">
<input type="radio" name="option" id="r1" value="1" />
<label for="r1">Up</label>
<input type="radio" name="option" id="r2" value="2" />
<label for="r2">Down</label>
</span>
<span class="col">
<input type="submit" class="button"/>
</span>
</form>
</div>
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(".button").click(function(event){
if ((document.getElementsByName("gateway")[0].value == '')) {
alert('Gateway Required!');
return false;
}
else if (document.querySelectorAll('input[type="radio"]:checked').length < 1) {
alert('Please Choose Up/Down Value!');
return false;
}
else {
//alert('Sucess!');
event.preventDefault();
$.ajax({
url:"testexec.php",
type: "POST",
data: {option: $('input[type=radio]:checked').val()},
dataType: "text",
success:function(result){
$('#div1').html(result)
}
});
return true;
}
});
</script>
<div id="div1"></div>
</body>
</html>
testexec.php
$gateway = '';
$user = 'user';
$pwd = 'pass';
function cleanInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ( $_SERVER['REQUEST_METHOD'] == 'POST'){
$gateway = cleanInput($_POST['gateway']); //need to get the value of gateway from form.php
//create the ssh connection
if ($connection = #ssh2_connect($gateway, 22)) {
ssh2_auth_password($connection, $user, $pwd);
if(isset($_POST['option']) && $_POST['option'] == 1) {
$stream = ssh2_exec($connection, "/tmp/user/testscripts/up.sh");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo '<pre>' . stream_get_contents($stream_out) . '</pre>';
}
if(isset($_POST['option']) && $_POST['option'] == 2) {
$stream = ssh2_exec($connection, "/tmp/user/testscripts/down.sh");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo nl2br(stream_get_contents($stream_out));
}
}
}
?>
So now i have to somehow get the value of 'gateway' from my form.php for the following code to work:
$gateway = cleanInput($_POST['gateway']);
So I was wondering if this is good practive to seperate things like this?

I see no advantage in combining the scripts. There is no magic to $_POST. It only exists when a script has been the TARGET of a POST, and it doesn't matter if the target is the same script that originally had rendered the form, or a different script.
The only advantage to combining form code into a self-posting, all-in- one version, is when you have iterative error handling.
In that situation, frequently you want to do some server side validation, and if the form doesn't validate, need to send a response with the another form with an error, and usually with the original form elements already filled in, and typically with some visual indication as to which elements caused the problems.
It's much cleaner to have this all in one place, so you aren't reinventing the wheel with the form.
However, moreover, any script is cleaner and easier to read when you separate logic from presentation.
This is a big reason why people use template libraries like smarty or twig, an why every MVC framework comes with some sort of template system.
Even in your case, you could move the form data into it's own seperate script and include it with something like:
require_once('form_frm.php');
In your case, form.php has no logic whatsoever currently, so I see no major advantage to doing this at the moment.
I would recommend however, that you consider each function you are using, and why you are using it.
Stripslashes() for example, appears to have no value to you in this script, and in fact, stripslashes has had very little use for many years now, as magic_quotes_gpc() was deprecated long ago.
Escaping was a function of SQL database string handling, and due to the issues with different character sets and localization, if you needed to add escape characters, there were better database specific methods like mysql_real_escape_string() which take into account the character set of the client data and database.
At this point in time, most everyone knows that you should be using bind variables for adding string data to SQL queries, which essentially eliminates the need for any escaping of quotes, so there is no need for add slashes or mysql_real_escape_string() whatsoever, and the world is better for it.
If you are not calling addslashes(), why are you calling stripslashes()?

Related

Invisible reCaptcha PHP vs JS verification

I have a simple question.
I added a custom form with Google Invisible Captcha to avoid spam.
Currently I have a something like this (just works fine):
<script>
function onSubmit(token) {
document.getElementById("demo-form").submit();
}
</script>
<form id='demo-form' action="" method="POST">
<button class="g-recaptcha" data-sitekey="your_site_key" data-callback='onSubmit'>Submit</button>
<br/>
</form>
But to make it more "secure" I can add extra layer of verification via $_POST response as described below.
if( isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']) ) {
// verify response
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
// if all good => proceed registration
if ($responseData->success) {
Do you think it worth adding this extra verification via PHP or it's fine to leave it as is ?

Settup form script for ajax and post calls

i would like to know if its possible to set up my script so it can be handled by http ajax call and alternatively also the classic post way:
on the top i am first doing this:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
$AnswerType = 'die';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
$AnswerType = 'session';
}
Then i check if either of these two is set by doing the following:
if ($AnswerType == 'die' || $AnswerType == 'session' ){
*here i run my script*
}
When the script ends i finally try to send all responses in my $respond_message array back the way the form where initialy posted:
if ($AnswerType = 'die'){
die(print_r($respond_message));
}
if ($AnswerType = 'session'){
$_SESSION['formrespondmessage'].= print_r($respond_message);
header("Location: /");
}
You want the script to react different on ajax and on simple post request? I think in this case the best solution is just to pass any variable, which indicates, that data is being sent by ajax. Like this:
postparams['ajax']=1;
$.post(...
And then in php make check like this:
if (isset($_POST['ajax'])) {
code for ajax request
} else {
code for simple post request
}
Not sure about your code, I prefer not to use so complicated scripts, at least you need to add () after serializeArray, possibly everything else looks ok. I would do like this:
<form name="form1" id="form1">
<input type="text" name="qq" value="ww">
</form>
<input type="button" onclick="dt=$('#form1').serializeArray();dt[dt.length]={name: 'ajax', 'value': 1};$.post('test.php', dt, function(data) {alert(data)});">
And in php file just check if isset($_POST["ajax"]). For example, my looks like this:
<?
if (isset($_POST["ajax"])) print_r($_POST);
?>

Can I call the function from php class using jquery ajax?

I begin with an object-oriented programming in php.
I want to do the logging - using ajax and jquery.
EDIT: Can I call the function ajax from file jquery.php - using jquery AJAX?
//FILE jquery.php
class jquery {
public function ajax() {
echo "result";
}
}
If you make an ajax call similar to this :
http://example.com/ajax.php?firstParam=1
Within your ajax.php file you can do something like this :
switch($_GET['firstParam']){
case "1":
callYourFunction();
break;
case "2":
someOtherFunction();
break;
}
This is a very stripped down example... In a real world case you would have to take security into account and sanitize any information you are getting from outside your server (i.e. from a user).
The names I have given are only place holders - you can change the function/variable names to whatever you feel comfortable with.
I hope this sheds some light on your conundrum.
Not sure if you completely understand what AJAX is, but it's an acronym for Asynchronous JavaScript and XML. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behaviour of the existing page. That's it.
This I believe is what you're looking for (though its not OOP, but im not writing an entire OOP login to try answer your question)
File: login.php
<?php
$db = new PDO("mysql:host=localhost;dbname=database", SQL_USER, SQL_PASS );
$stmt = $db->prepare('SELECT user_id, user_activated FROM users WHERE ( username = AND user_password = ? LIMIT 1');
$stmt->execute( array( $_POST['u'], $_POST['p'] ) );
if( $stmt->rowCount() == 1 )
{
// Authentication session storage stuff here
echo 'Logged in';
}
else
{
echo 'bad login';
}
?>
So you could have a HTML page with something like:
<div id="results"></div>
<input type="text" id="txtUsername" /> <br />
<input type="password" id="txtPassword" /><br />
<button id="cmdLogin">Login</button>
<script>
$(document).ready(function(){
$("#cmdLogin").click(function(){
$u = $("#txtUsername").val();
$p = $("#txtPassword").val();
$.ajax({
type: "POST",
url: "http://yoursite.com/login.php",
data: "u="+u+"&p="+p
}).done(function(results) {
$("#results").html(results).hide().fadeIn();
});
});
});
</script>
Also, keep in mind this code is un-tested and written it as replying to this, so don't treat this as a solution to what you're wanting, but rather a resource to help you to implement what it is you're asking for.
You cannot call a class directly - but you can fetch the result of an execution.
Here an example how you can call it nearly direct - but don't use this for critical login code.
<?php
$ftcn = $_GET['getname'];
$bc = new ReallyBadCode();
$bc->$ftcn();
class ReallyBadCode{
function test(){
}
function __call($name, $args){
$this->$name($args);
}
}

Jquery Ajax no response

When I try to get the response from a php file using Jquery ajax, I just get (an empty string) (Accdg. to Firebug console using console.log(data))
Here's the Html code:
<form action="test.php" method="POST" id="ajax">
<input type="text" name="field" />
<input type="submit" value="submit" name="submit" />
</form>
Here's the Jquery code:
$('#ajax').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: $(this).serialize(),
url: 'test.php',
cache: false,
success: function(data) {
alert(data);
}
});
return false;
});
And the PHP code:
if ($_POST['submit'] == "submit")
{
echo 'Got your request';
}
Just basic. What frustrates me is that it's straightforward, I've done some research and still it doesn't work. I also want it to be as simple as possible.
Please enlighten me.
Don't check to see if you're in a POST situation by checking for fieldnames. That's incorrect - you might change your client-side form names and forget to update the PHP check.
The 100% reliable method is to use:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "Got your request";
}
However, since you just want to see if the server got pinged at all by your ajax call, why not do:
<?php
echo "Got your ", $_SERVER['REQUEST_METHOD'], " request";
Which'd just return Got your POST request or Got your GET request, etc...
As well, check your server log (or use HTTPFOX/Firebug Net tab, etc...) to see if that ajax request is actually going out and being received by the server.
The problem with the serialize() method is that it doesn't include the name of the button parameter which you use in your php script (submit=submit parameter). It doesn't do it because it doesn't know which button was clicked. This parameter is only included by the browser when you submit the form normally.
So one possibility is to manually attach this parameter as query string parameter:
url: 'test.php?submit=submit',
and in your PHP script:
if ($_GET['submit'] == "submit")
{
echo 'Got your request';
}

PHP header() redirect with POST variables [duplicate]

This question already has answers here:
PHP Redirection with Post Parameters
(8 answers)
Closed 9 years ago.
I'm working with PHP, and I'm making an action page which a form posts to. The page checks for errors, then if everything is fine, it redirects them to the page where the data has been posted. If not, I need to to redirect them back to the page they were at with an error and the POST variables. Here is the gist of how it works.
The HTML would look like this...
<form name="example" action="action.php" method="POST">
<input type="text" name="one">
<input type="text" name="two">
<input type="text" name="three">
<input type="submit" value="Submit!">
</form>
action.php would look like this...
if(error_check($_POST['one']) == true){
header('Location: form.php');
// Here is where I need the data to POST back to the form page.
} else {
// function to insert data into database
header('Location: posted.php');
}
In the case of an error, I need it to POST back to the first page.
I can't use GET, because the input will be too large.
I don't want to use SESSION, if possible.
Is this possible?
// from http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = #stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.
// form.php
<?php
if (!empty($_POST['submit'])) {
// validate
if ($allGood) {
// put data into database or whatever needs to be done
header('Location: nextpage.php');
exit;
}
}
?>
<form action="form.php">
<input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
...
</form>
This can be made more elegant, but you get the idea...
It is not possible to redirect a POST somewhere else. When you have POSTED the request, the browser will get a response from the server and then the POST is done. Everything after that is a new request. When you specify a location header in there the browser will always use the GET method to fetch the next page.
You could use some Ajax to submit the form in background. That way your form values stay intact. If the server accepts, you can still redirect to some other page. If the server does not accept, then you can display an error message, let the user correct the input and send it again.
It would be beneficial to verify the form's data before sending it via POST. You should create a JavaScript function to check the form for errors and then send the form. This would prevent the data from being sent over and over again, possibly slowing the browser and using transfer volume on the server.
Edit:
If security is a concern, performing an AJAX request to verify the data would be the best way. The response from the AJAX request would determine whether the form should be submitted.
Use a smarty template for your stuff then just set the POST array as a smarty array and open the template. In the template just echo out the array so if it passes:
if(correct){
header("Location: passed.php");
} else {
$smarty->assign("variables", $_POST);
$smarty->display("register_error.php");
exit;
}
I have not tried this yet but I am going to try it as a solution and will let you know what I find. But of course this method assumes that you are using smarty.
If not you can just recreate your form there on the error page and echo info into the form or you could send back non important data in a get from and get it
ex.
register.php?name=mr_jones&address==......
echo $_GET[name];

Categories