PHP/frontend interaction - php

Having some trouble. New to web development. I'm trying to make a simple application that receives data from a Particle Photon board - using a webhook, everytime a particular event occurs on the board's end, a JSON is sent via POST. I'm running an Apache webserver. I want to process the POST request with PHP, and then have that PHP update what the user sees somehow. Right now I have only index.php, with the following:
<html>
<head>
</head>
<body>
<div>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$data = json_decode(file_get_contents("php://input"));
// do something with $data
}
?>
</div>
</body>
</html>
I'm not worried about input validation, I just want the rudimentary functionality. My thought process is that the webhook sends this POST request (it sends it to index.php, and appears to be working), and then the index.php will be triggered and then display the POST request information. I can't seem to get the index.php to receive the POST request. I've tried var_dump, echo, but it all comes back either blank or NULL. Is there something inherently flawed with my understanding of this setup?
This is the JSON that is being sent:
The only file I have on the server is index.php.

From comments:
First of all, prepare a process file, eg.: process.php, in this file you need only php code that check for a post, process it and store relevant data in your database.
<?php
if(isset($_POST)){
// Process post, store relevant data on database
}
Then, with data properly stored on database, you can show html pages to your users, retrieving data from database and showing to them accordingly.

Related

Can't find data in php file ,sent by ajax

I create to file ajax.php and jajaxget.php.
script in ajax.php is-
<script>
var data={name:"nikhil"};
$.ajax({type:"post",url:"jajaxget.php",data: {name:"nikhil"},success:function(r,s){alert(s);alert(r);}});
</script>
and jajaxget.php is
<!doctype html>
<html>
<body>
<?php
echo $_POST["name"];
?>
ajax.php works fine and in alert i can see the data which i send. I get a success alert and this ALERT
But when i open the get.php file in browser there is nothing . "nikhil" should show on the page. but the page is blank . why data is not recived by jajaxget.php file. It may be very foolish question .but please help
That should not show on the page when you open it on the browser because you are not passing any POST data when you do so. Your code is working as expected. I think your problem is you do not really get to understand how GET/POST works.
In the post environment variable the post data sent on request is stored. It is not stored forever nor as kind of a cookie. When you make another request, the variable will have different data according with the headers of the request.
So when you are using AJAX and send post data to your file, the return shows the "name" value you've passed because you've sent it on the request headers. However, when you request the page on a browser and you are not passing any POST data, that won't be shown, because nothing you've sent.
If you want your server to store that data, you may use databases or cookies for that.
For more information read some webpages online like http://www.w3schools.com/tags/ref_httpmethods.asp. And please try to understand a bit how the web works before filing it of low quality questions.
If you still have doubts, please ask me.

PHP Server Side Script

I have Linux operating system with Doc root(/var/www/html)in which I have an index.html file which has a form for asking user's name and then it puts that details into MYSQL Database(using php script called inside the index.html).
When I open the index.html in browser it presents me with the form to enter the user details and after clicking on submit, the php script is called(browser URL changes to /localhost/insert.php)and it inserts the data into database which is fine.
The issue is that the backend php script is directly available using /localhost/insert.php, so if I(or someone) bypasses the index.html and directly opens the /localhost/insert.php, it runs directly putting some vague data into MYSQL Database.
Any fixes to avoid running the backend(server side php script) directly from the browser.It should ONLY be allowed to run when called from the index.html.
It is better to check the request method than check if the $_POST variable is set, as there will be cases that a form will be correctly sent but the $_POST won't be sent.
You can do this by the following:
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
header('Location: index.html');
die();
}
Then you can do sanitisation to check the fields have been entered, then finally sanitise data. If you are inserting the data into a database be sure to use prepared statements (or at the very least sanitise your data inputs using a real escape string function). Also make sure you prevent XSS injections by using htmlspecialchars.
You need to bypass processing in insert.php by placing a check and executing only if the request is coming from a POST
if(!isset($_POST['formValue'])){
exit;
}
?>
formValue is the key being "Post" from your index.html
If you are handling things properly, using POST method, then things should work out good. It doesn't matter if the user is trying to access your php script directly. It all depends on your request method. Say for example your form tag goes like this.
<form action = "index.html" method = "post">
And your submit button goes like this,
<input type = "submit" id ="submit">
Then in your index.html php script their should be something like this.
if(isset($_POST['submit'])){
// redirect data to another php script. And in this script, data should be cleaned to prevent Sql injections !!
}
else
{echo "invalid request";}

Any tool or browser add on to check POST/ GET response?

Suppose I have test.php file which echo the value of user and data .Now I can easily check my test.php whether it is working fine or not from a HTML form with user and data
input. But I want to check my test.php file without html form.
Is there any tool or browser plugin to POST or to GET data from test.php.
//test.php.
<?php
echo $_POST['user'];
echo $_POST['data'];
?>
Thanks in advance
Update I have found RESTclient and its really fine for me.
Your best bet is to simply watch webpages interact with your service using Fiddler; you'll then understand what format the service expects.
To send requests in Fiddler, click the Composer tab and fill in the headers and body.
Its fairly straightforward to execute a POST request from the CLI using cURL
curl --data "user=sharif&data=HelloWorld" http://site.com
See also curl usage explained

How would I pass information from one PHP to another?

I need to create a landing page that's dynamic to information picked up by a form that executes a php script.
Person submits form > PHP Code sends me an email > PHP code that displays information
I have a hidden input in every form that identifies what form it is, and depending on what the value or "identification" of the form a specific code on the php is executed using a switch and I thought that maybe I could use that same identifier to execute another switch on the page after that. My problem is I don't know how to carry that value or identifier from one php to the other.
So just to reiterate, I want to know how to move or copy variables from one php to another, after mail() is executed.
Im using $request to get those variables
Keep this source form identifier and render it into your new form identifier field. It will deliver the response form with same identifier
after you do your Mail() thing, call a function that runs whatever you want.
If the classes or functions you want to run are not available you must include or require them.
I'm not 100% sure about what you are asking for, but due the comments I'll make a try to answer it.
When I create forms I usually have one page with the actual form and another page that handles the data. When the data is handled I simply redirect the user back to the form and then give them feedback.
The reasons I'm using two separate pages are the following:
I like to keep the code for the form and the handler separated.
Users can't accidently submit the form again by refreshing the page.
The same handler can be used by eventual Ajax and uphold progressive enhancement.
An extremely simplified example below.
form.php:
<?php
//Start session
session_start();
//If the session variable has been set
if($_SESSION['remember'])
{
## DISPLAY FEEDBACK ##
}
else
{
## DISPLAY FORM ##
}
//Delete the session variable
unset($_SESSION['remember']);
?>
req.form.php
<?php
//Start session
session_start();
//If a form has been submited
if(isset($_POST['submit']))
{
## HANDLE THE DATA ##
//Set a session variable
$_SESSION['remember'] = true;
//Redirect the user back to the form
header('Location: /form.php');
exit;
}
?>

Redirect POST request and keep data. Possible?

My problem is simple. I need to upload a file directly to the correct server (which has currently low workload).
Therefore I do:
<?php
$server = file_get_contents('http://my-api.com/upload-server.php'); // returns url
?>
then i print my form like
<form method="post" action="<?php echo $server; ?>"...
Now I would like to shift this step to when the upload starts, like so:
<form method="post" action="http://my-api.com/upload-gateway.php"...
this url should do a redirect to the "real" server.
So that the upload page doesn't slow down loading and I have static html code that I can cache, embed etc...
Problem is that this works perfetly fine with get requests but not with post requests.
The request seems like to get transformed into a get request when redirecting using the location header. All post data is lost.
Is this impossible or am I doing it wrong? And yes, I considered a remote dynamic javascript that prints the html code with the correct server in the first place. I would rather like not to do that...
any ideas? Maby alternative uplod techniques?
edit:
this is the exact html code i use:
<form method='post' enctype='multipart/form-data' action='http://storage.ivana.2x.to/rest.php?action=target'>
<input type=hidden name=testfield value="test">
File to upload: <input type=file name=upfile><br>
Notes about the file: <input type=text name=note><br>
<br>
<input type=submit value=Press> to upload the file!
</form>
this is the redirect code i use:
if($_GET["action"] == "target") {
header("Location: http://storage.ivana.2x.to/rest.php?action=test");
}
this is the output code i use to see the results:
if($_GET["action"] == "test") {
echo "<pre>";
var_dump($_POST);
var_dump($_GET);
var_dump($_FILES);
}
the result when uploading a small file looks like:
array(0) {
}
array(1) {
["action"]=>
string(4) "test"
}
array(0) {
}
If you really want to load balance through the code while potentially caching the page with the upload form, first select the default download server (url); then, onSubmit call the server and find the best upload target and adjust the action attribute accordingly.
With this method, users who do not activate JS still get what they want, users with JS enabled get the better upload target, and you can still cache. Additionally, the timing of the cache request could potentially be more opportunistic, since the URL request will occur very shortly before the actual upload.
The only hitch will be the call to get the URL, which you can more easily performance tune (I imagine) than the process you are describing above. Uploading a file twice through a header directive and/or cURL call don't seem like a good tradeoff for caching a single html file, IMO. But I don't know what you're up against, either.
If you don't want to heavily administer the server environment and introduce load balancing, this is the option I would suggest.
Note, also, I am not a server administrator by trade.
You could try returning a code 302 (temporary moved), not 100% that would let your browser post the data to the changed url though, but it's worth something to check out.
[Edit]
According to this wikipedia article, the POST data would be converted to GET, which probably won't work for a file upload.
This is not a good solution. The file will be uploaded in it's entirety before the PHP script is even started. This means that if you succeed with what you're trying to do the client will have to upload the file twice!
I recommend that you try to figure out which server to send the request to when you're creating the form, so the action attribute in the form tag will point directly to the lesser loaded machine.
Or even better: use a serverside loadbalancer and make your HTTP infrastructure transparent to the browser. This is essentially a sysadmin problem.
i might be wrong but.. your form's action points to ?action=target and in your rest.php you do a header to "?action=test" well of course you wont find your $POST nor your $FILES!... a header() does not send those variables..
if you want to send your post and your file to a differente location you'll need to use the cUrl library.. but it wont be easy :)
Good Luck

Categories