Calling a PHP API from HTML Form? - php

I've been developing iOS apps for a while now and have just started to get into designing my website. In one of my apps, I add data to my database by using:
let URL = NSURL(string: urlPath.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
let data = NSData(contentsOfURL: URL!)
var response = ""
if let data = data{
response = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
}
The urlPath would look something like: http://mydomainname.com/folder/anotherFolder/theAPI.php?arg1=one&arg2=two&arg3=three and so forth.
What I really want to be able to do is call that API.php file with all the arguments where each one (arg1=, arg2=, etc) is a field in a HTML form. I've found a couple of tutorials that deal with HTML forms and validating data, and now my form looks like:
<form action="action.php" method="post">
<div id="formtext">Name</div>
<input type="text" name="Name">
<div id="formtext"><br>Email Address:</div>
<input type="text" name="Email"><br>
<div id="formtext"><br>Password</div>
<input type="text" name="Password"><br><br>
<input type="submit" name="submit" value="Submit">
</form>
Apologies if the HTML is a little cringy, I'm not experienced enough to know what 'tidy'/conventional HTML code looks like and this is what I've managed to piece together from tutorials.
I also know that in the action.php you can get the values in the forms like: $_POST['Name']. I feel like I'm really close - I just can't find anywhere that will tell me how to call this api.
The closest I can get is:
$name = $_POST['Name']
$email = $_POST['Email']
$password = $_POST['Password']
$response = file_get_contents('http://domain.com/folder/api.php?Name=' . $name . '&Email=' . $email . '&Password=' . $password);
echo $response
If you're a php expert, again, sorry for butchering your code :)
(Oh, and the result just says there was an error on line 26 in the where clause - the API's fine because I tested it from my app).
Edit: Where clause used to be While Loop (sorry)
In conclusion, I'd greatly appreciate if someone showed me what to put in action.php (excluding verification - I'll get on to that later) and please do let me know if I'm doing anything ludicrously wrong.
Thanks :)

In HTML the name="" part of the tag should correlate with your arg1, arg2, arg3. I don't know how much experience you have with GET and POST, but if you want the URL to contain all of the args like in your example, you should set the form method to get. The action attribute of the form tag is the page you want the values to be sent to. Try the following for your form:
<form action="http://mydomainname.com/folder/anotherFolder/theAPI.php" method="get">
<div id="formtext">Name</div>
<input type="text" name="arg1">
<div id="formtext"><br>Email Address:</div>
<input type="text" name="arg2"><br>
<div id="formtext"><br>Password</div>
<input type="text" name="arg3"><br><br>
<input type="submit" name="submit" value="Submit">
</form>
After submitting this form you should be taken to the URL http://mydomainname.com/folder/anotherFolder/theAPI.php?arg1=inputfromfirstbox&arg2=inputfromfield2&arg3=inputfromfield3

First of all you need to put your PHP instructions between php markups.
<?php
//You php script here
?>
Moreover, php instruction ended by ";", you did it well for $response.
<?php
$name = $_POST['Name'];
$email = $_POST['Email'];
$password = $_POST['Password'];
$response = file_get_contents('http://domain.com/folder/api.php?Name=' . $name . '&Email=' . $email . '&Password=' . $password);
echo $response;
?>
Then, it is not a good idea to use directly data from a form. You should analyse them before (be sure that your email is a real one and not a random string etc.). To do that you can take a look at the regex : http://php.net/manual/en/function.preg-match.php
Let me know if you need more information.

Related

Manually Send Data PHP method post

i'm brazilian i does a website simple to sent a simple users data, but to do a test i want sent manually newer data in a link without need complete manual form if it run then i can use directly by my app to save all users data.
see my idea:
mywebsite.com/savedata?method=post&usernamesave=Nome&Misael&userxp=34&userid=35&userlevel=31&usermail=crod%40gmail.com&userprog1=1&userprog2=2&userprog3=23&userprog4=25&userprog5=25&userprog6=25&userprog7=100&userprog8=100&proceed=
if i can change this data from my app and using hrefs i can do this and save a simple data without a complex data connection, it's possible ?
<a href="mywebsite.com/simplepost?method=post&joao&6y"> << type of exeple.
But when i use this and press enterkey the data isn't saved into a textfile, why ?
i using this in php :
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/*Php 5.6.2 Code By : Michael S. author*/
//globais
$username = $_POST['usernamesave'];
$userxp = $_POST['userxp'];
$userid = $_POST['userid'];
}
If i got you right you want to save data using a post method. If this is what you want to accomplish, then you don't have to pass the variables in URL. This is the main difference between POST and GET method.
Now for data saving, i will assume that you all ready created a database and a table to save your information on it, so let's jump to the form and how to handle them.
<?php
/*
* First form one will be the POST method.
*/
if(isset($_POST)){
echo "post method where used from a form to send this variables";
var_dump($_POST);
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username: </label>
<input type="text" name= "username">
<label for="age">Age: </label>
<input type="number" name="age"/>
<input type="submit" value="Submit">
</form>
When you click on submit the information will be sent and can be handled after.
In get method it's different you will see the variables inside the URL after hitting submit, and the same way you can send data to other pages.
<?php
/*
* Second form one will be the GET method
* Check the url.
*/
if(isset($_GET)){
echo "get method where made from a form with this variables";
var_dump($_GET);
}
?>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username: </label>
<input type="text" name= "username">
<label for="age">Age: </label>
<input type="number" name="age"/>
<input type="submit" value="Submit">
</form>
Now in the url you should see something like
example.com/index.php?username=WaredNsour&age=24
I believe you are using the GET method to send information but in your PHP code, you are using the POST method to fetch them.
Try this :
if ($_SERVER["REQUEST_METHOD"] == "GET") {
/*Php 5.6.2 Code By : Michael S. author*/
//globais
$username = $_GET['usernamesave'];
$userxp = $_GET['userxp'];
$userid = $_GET['userid'];
}
In the code of your page that is processing the variables being sent, try the following (temporarily) as a test to see if variables are being sent/seen. If they are, they will be printed out.
<p>Post vars:
<?php var_dump($_POST) ?>
</p>
If nothing displays, try:
<p>Request vars:
<?php var_dump($_REQUEST) ?>
</p>
Note: in the url you posted you have: &Misael& if Misael is part of the username you should not use the & in front of it. http sees &s as separators for the variables. It will see Misael as a variable name, like: ...&Misael=something&.... If it is a space, use %20.

How to stay on HTML form page and not navigate to php form action page

I am working on a html form which will connect to a database using a php script to add records.
I have it currently working however when I submit the form and the record is added , the page navigates to a blank php script whereas I would prefer if it when submitted , a message appears to notify the user the record is added but the page remains the same. My code is below if anyone could advise me how to make this change.
Html Form :
<html>
<form class="form" id="form1" action="test.php" method="POST">
<p>Name:
<input type="Name" name="Name" placeholder="Name">
</p>
<p>Age:
<input type="Number" name="Age" placeholder="Age">
</p>
<p>Address
<input type="text" name="Address" placeholder="Address">
</p>
<p>City
<input type="text" name="City" placeholder="City">
</p>
</form>
<button form="form1" type="submit">Create Profile</button>
</html>
PHP Database Connection Code :
<html>
<?php
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx",
"Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values
('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
</html>
Typically your action file would be something like thankyou.php where you'd put whatever message to the user and then maybe call back some data that was submitted over. Example:
Thank you, [NAME] for your oder of [ITEM]. We will ship this out to you very soon.
Or this file can be the the same page that your form resides on and you can still show a thank you message with some javascript if your page is HTML. Something like:
<form class="form" id="form1" action="test.php" method="POST onSubmit="alert('Thank you for your order.');" >
I am taking into consideration that your PHP Database Connection Code snipplet that you posted above is called test.php because you have both connecting to the data base and inserting data into the database in one file.
Taking that into consideration, I think the only line you are missing, to return you back to to top snipplet of code that I shall call index.php would be an include statement just after the data has been added to the database
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values ('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
echo "Data added";
include 'index.php'; //This file is whatever had the earlier form
Once you hit the submit button on your form, test.php is called, your data is handled and passed back to index.php.
N.B:
The other thing i should mention is to make it a habit of using mysqli_real_escape_string() method to clean the data that is in the $_POST[]; because in a real website, if you don't, you give an attacker the chance to carry out SQL injection on your website :)
you said page is coming blank and data is saved so i assumed that there are two files one which contains form and another which contains php code (test.php).
when you submit the form you noticed that form is submitted on test.php
and your test.php has no any output code that's why you are seeing blank page.
so make a page thankyou.php and redirect on it when data is saved.header('Location: thankyou.php'); at the end of file.
Put this in form action instead of test.php
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Put your php code at top of the page.
$Name = $_POST['Name'];
This is step closer to being a safer way to posting into your db as well.
$Name =mysqli_real_escape_string( $_POST['Name']);
I like the jscript Alert from svsdnb to tell user data was successfully added to db.
This is not intended to be an out of the box solution; it's just to get you pointed in the right direction. This is completely untested and off the top of my head.
Although you certainly could do a redirect back to the html form after the php page does the database insert, you would see a redraw of the page and the form values would be cleared.
The standard way to do what you're asking uses AJAX to submit the data behind the scenes, and then use the server's reply to add a message to the HTML DOM.
Using JQuery to handle the javascript stuff, the solution would look something like this:
HTML form
<html>
<!-- placeholder for success or failure message -->
<div id="ajax-message"></div>
<form class="form" id="form1">
<p>Name: <input type="Name" name="Name" placeholder="Name"></p>
<p>Age: <input type="Number" name="Age" placeholder="Age"></p>
<p>Address: <input type="text" name="Address" placeholder="Address"></p>
<p>City: <input type="text" name="City" placeholder="City"></p>
<!-- change button type from submit to button so that form does not submit. -->
<button id="create-button" type="button">Create Profile</button>
</form>
<!-- include jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- ajax stuff -->
<script>
// wait until DOM loaded
$(document).ready(function() {
// monitor button's onclick event
$('#create-button').on('click',function() {
// submit form
$.ajax({
url: "test.php",
data: $('#form1').serialize,
success: function(response) {
$('#ajax-message').html(response);
}
});
});
});
</script>
</html>
test.php
<?php
// note: never output anything above the <?php tag. you may want to set headers.
// especially in this case, it would be better to output as JSON, but I'm showing you the lazy way.
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx", "Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
// if mssql needs the non-standard brackets, then put them back in...
// note placeholders to get benefit of prepared statements.
$query = "INSERT INTO SalesLT.Test " .
"(Name,Age,Address,City) Values " .
"(?,?,?,?)";
$params1 = array($Name,$Age,$Address,$City);
$success = false;
if($result = sqlsrv_query($conn,$query,$params1)) {
$success = true;
}
sqlsrv_close($conn);
// normally would use json, but html is sufficient here
// done with php logic; now output html
if($success): ?>
<div>Form submitted!</div>
<?php else: ?>
<div>Error: form not submitted</div>
<?php endif; ?>

Is this how AltoRouter GET POST method work?

I have been trying out this altorouter for weeks now. This is looks to be good router with not many working example either on the nets or the official site. You need to understand it somehow and get the job done.
I tried the basic GET and POST using the altorouter and do not know whether this is the right way of doing it.
Simple GET method in php
<html>
<head>
</head>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
The way I did it using AltoRouter
Index.php
<?php
require 'library/AltoRouter.php';
$router = new AltoRouter();
$router->setBasePath('/AltRouter');
$router->map('GET','/', function() {require __DIR__ . '/catalog/controller/home.php';}, 'home');
$router->map('GET|POST','/aboutus/', function() {require __DIR__ . '/catalog/controller/aboutus.php';}, 'aboutus');
$router->map('GET|POST','/contactus/', function() {require __DIR__ . '/catalog/controller/contactus.php';}, 'contactus');
$router->map('GET|POST','/welcome/', function() {require __DIR__ . '/catalog/controller/welcome.php';}, 'welcome');
$match = $router->match();
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
contactus.php (Get Method)
<html>
<head>
</head>
<body>
<form action="../welcome/" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
welcome.php
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
For some odd reason this works but I feel this isn't right. Reason: Information sent with the GET method is visible to everyone, the variables are displayed in the URL, it is possible to bookmark the page.Where as the URL that I get after submitting the form is this
http://localhost/altrouter/contactus/
No variable displayed after submitting the form in the URL.
Now for the POST method, this one works you need to let me know is this how we are supposed to do it or not.
Index.php
same as the one posted above
aboutus.php (POST method used)
<html>
<head>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["first_name"];
$email = $_POST["email_address"];
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
}
?>
<form action="<?php $_SERVER["PHP_SELF"]?>" method="post">
Name: <input type="text" name="first_name">
<br><br>
E-mail: <input type="text" name="email_address">
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
This works and the data posted is echo'ed out, URL after submitting
http://localhost/altrouter/aboutus/
Please let me know what is right and what is wrong.
I don't think I understand what you are asking... I do have some observations, though:
Information sent with the GET method is visible to everyone, the variables are displayed in the URL
Yes, that happens in HTTP method GET, the ?name=Joe&email=joe#example.com at the end of the url is called "query string". One of its differences with method POST is that the data is part of the url, so it's visible (alhtough don't trust that it is not visible otherwise) and as you say it can be bookmarked.
On GET vs POST, read about the usage of those methods and decide one for each route. I don't think it's good design, let alone easily maintainable, to have several methods mapped to a single controller. Take advantage of the router, map different methods, for instance:
$router->map('GET','/contactus', 'showContactForm');
$router->map('POST','/contactus', 'processContactForm');
Since you tag the question with "MVC", you could separate things further and have your controllers be just controllers which in turn call or generate views. Or, you can just use a full MVC framework, even a light one like Lumen, which manages routing, view templates, database connection, authentication and much more.
<form action="../welcome/" method="post">
From http://localhost/altrouter/contactus/ to http://localhost/altrouter/welcome/ the relative url can be just welcome. The .. means "go up a directory".
the URL that I get after submitting the form is this
http://localhost/altrouter/contactus/
I don't get why, if the form submitted successfully as you say, you should be in http://localhost/altrouter/welcome/
Avoid $_SERVER["PHP_SELF"]. It brings insecurities. A form with no action attribute will just submit to the same url. With method POST, you can, for the same url, handle both actions separately as I said earlier.

php post to use JSON_ENCODE

I am trying to create the back-end for my app which has to allow emoticons to be send. With a form and php POSTit gets send to a file which sends a notification with the emoticon (and optional text).
However if i use $_POST it will not be be encoded and just send as smiley, which will not be accepted by the devices (apple converts it?)
My Code:
$message = $_POST['message']; // contains only -> 😇
$test = "😇";
echo json_encode($test); //output = "\ud83d\ude07" AS it should be
echo json_encode(strval($message)); //outputs 😇 which is false.
If i use $_GET['message'] and change my other scripts it will work (used test file to check).
However having security in mind (browser history and such) i want to use $_POST.
how can i make this happen?
-- FORM as requested.
Please not that this is all i need So far.
]
<html>
<head>
</head<
<body>
<form action="./simplepush.php" method="post">
Message : <input type="text" name="message" /><br />
<input type="submit" name="submit" value="Send" />
</form>
</body>
</html>
Not using any headers (or specifying)
Have you tried to force the form to encode the post data as UTF8?
<form method="post" action="some/url" accept-charset="UTF-8">

$_POST coming in empty after submit

I'm writing a webpage, and am trying to use php to check a value after a form submits. The php is in the same page, as seen below. The $_POST variable is coming in empty after the submit code comes in though. I've looked at the other posts about this question but none of those answers seem to help.
Thanks for looking
<?php
session_start();
require_once 'assets/PHP/membership.php';
$membership = new Membership();
var_dump($_SESSION);
var_dump($_POST);
if($_POST && !empty($_POST['username']) && !empty($_POST['pwd']))
{
$response = $membership->validate_user($_POST['username'], $_POST['pwd']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<div id="login">
<form method="post" action = "">
<h2>LOG IN:</h2>
<label>User Name :</label>
<input type="text" name="username" id = "username"/>
<label>Password :</label>
<input type="password" name="pwd" id = "pwd"/>
<input type="submit" value="Login" id="submit" name="submit"/>
</form>
</div>
</html>
I'm very new to HTML and PHP so any help I could get would go a long way.
For anyone who is curious, I solved this by finding this reddit link: https://www.reddit.com/r/PHPhelp/comments/3uxapu/phpstorm_local_php_5616_post_always_empty/
All my superglobals were coming in blank. I'm not even sure why quite yet, I still need to read more about it. The following code snippet got me the results I needed:
$post_data = file_get_contents('php://input');
Post data now contains what I wanted to get from $_POST.
Thanks to everyone who tried to help me here!
If you want print $_post thn use code this....
If(isset($_POST['submit'])){
Print_r($_POST);
}
It's because, if you want to print data from form then you must submit the form first then you'll be able to get data in $_post.....

Categories