How does this POST request works? [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
"Send a message as a POST request to a web service. The address must
start with “http://”, and may optionally include the port number
(default is 80) and the path to a specific web service. The
notification message fills the body of the content part of the POSTed
message, with no key=value form-style formatting – you just read the
input stream directly."
The above is extracted from the Alien UHF RFID F800 manual. The mentioned request is used to send the RFID tags that are scanned by the reader to a web service. The domain name is myrfidtest.com and the path is /insertdb.php. Now the insertdb.php is set up to accept two parameters, for example, id and RFID tag number. So the complete URL is http://myrfidtest.com/insertdb.php?id=21&rfid=2eda1. This data then gets successfully inserted into my database.
Hence I understand how to insert data into the cloud-hosted database using the above URL. However, I do not understand the extract, and what is meant by "you just read the input stream directly"?
In addition, how do I change the insert.php script to accept the tags from the reader?
My insert.php scritp:
<?php
class data_new
{
public $conn='';
function __construct($id,$rfid)
{
$this->storeInDB($id,$rfid);
}
function storeInDB($id,$rfid)
{
$conn = new mysqli('localhost','user','password','db');
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "insert into cloud set id='".$id."', rfid='".$rfid."'";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
if($_GET['id'] != '' and $_GET['rfid'] != '')
{
$data_new = new data_new($_GET['id'],$_GET['rfid']);
}
?>

Normally when you post form data in a HTTP request, you (or your browser) puts the posted data into the body of the HTTP request, and formats it rather like a querystring e.g. field1=value1&field2=value2, so that the server receiving the request can tell the fields apart and know which value belongs to which field. I think the article is saying that in this particular request, the entire body of the request is simply a single field containing the notification data, without any name=value style formatting - because there's only one parameter in the body.
In PHP, posted data normally appears in the $_POST array, with one entry in the array per parameter in the data (so you'd end up with $_POST["field1"], $_POST["field2"], etc. But you can also read the raw input data using:
$postdata = file_get_contents("php://input");
instead. This would be useful in the case mentioned above where the data is just one big stream of text inside the request body, rather than being formatted.
P.S. I can't answer the second part of your question " how do I change the insert.php" because I don't know what script you're referring to, what it does or looks like, or what tags you're talking about. I suggest asking a second, separate question about that as it sounds like a different issue, and giving a clear example of what you mean, within the question text.

Related

cannot pass value to PHP file from URL? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a problem I use an internal server when I pass a value through the URL and type a valid value showing me a message that he did not scroll see my code:
// pass value from this URL:
http://localhost/test/get.php?name=aa
<?php
// include Marei DB Class
include 'DB.php';
// get content input and create json object to parse it
$data = file_get_contents("php://input");
$obj = json_decode($data);
// create db instance to use marei db queris
$db = DB::getInstance();
// set type of header response to application/json for respone
header('Content-Type: application/json');
if(!empty($_GET["name"])){
print "{\"status\":0,\"message\":\"Username is Non !\"}" ;
}else{
print "{\"status\":0,\"message\":\"Username is Don !\"}" ;
}
?>
// print these lines :
{"status":0,"message":"Username is Non !"}
Change if(!empty($_GET["name"])){
to if(empty($_GET["name"])){
You did the mistake to use ! operator.
PHP is understanding it as a not
And you're asking if the $_GET variable is NOT empty the result is true of course.
Please check http://php.net/manual/en/language.operators.php for more informations.
Could you clarify the method in which a file is being uploaded to your server? Form input?
Assuming that a file is being uploaded...I can see 2 maybe 3 issues, all of which are not mutually exclusive, so it could be be all three issues working together to foil your coding plans...
ONE Use $_FILES , not input
$name = $_FILES['file']['name']; <--- name of the file from its source
$path - $_FILES['file']['tmp_name']; <--- path to the uploaded file
you have to move the uploaded file from your uploads folder... to its new home.
TWO Request method should be POST not GET... Especially the request is created by a form.
THREE - check your php.ini file to make sure file uploads are enabled.
empty is enough. Also you can use
if (!$_GET["name"]) {
print json_encode(['status' => 0, 'message' => 'Username is Non !']);
}

Output Buffering: Easy way to make string out of HTML-Code

I'm currently using Chatfuel to open the index.php-file of my website which sends the user the html code into his browser. There he can register and set up his account.
An example URL might look like this:
https://my.domain.com?key_value='123456789'
Depending on if that user is a new or a existing one, I wanna present him with a different form. In order to check so, I do a simple query to the MySQL db and see if the passed on key_value is already in the db and safe true or false to a boolean. Stating the obvious: If hes not an existing user, the 'empty' form with no values should show up. If he is registered he should see the information he filled in from last time.
My idea:
At the top of my index.php I do the check whether he's an existing customer or not (Note: This is working already). Then I want to use outputbuffering to alter the html-code depending on the boolean, before it is sent to the client.
My problem:
I developed the blueprint of the website in plain html (see code below). And OB only catches it as output if its within a string. Since I use " as well as ' in the document the string gets interrupted every few lines. Is there a simple workaround to this? Because the OB function is unable to access anything within the <html>...</html> tags.
Or do i need to use redirecting after the check (in my index.php) and create a separate form + script for both edit customer data and add new customer data?
<?php
//Connection stuff
// Prepare statment: !TODO: string needs to be escaped properly first
$query_string = "SELECT * FROM tbl_customer WHERE unique_url = '$uniqueurl'";
$query_rslt = mysqli_query($conn, $query_string);
if($query_rslt == FALSE)
{
// Failure
echo "<br> Oops! Something went wrong with the querying of the db. " . $conn->connect_error;
//Handle error
}
else
{
if ($query_rslt->num_rows > 0)
{
// Set boolean
$existing_customer = TRUE;
// Create an array called row to store all tuples that match the query string
while($row = mysqli_fetch_assoc($query_rslt)) {
//...
}
}
}
// Custom post processing function
function ob_postprocess($buffer)
{
// do a fun quick change to our HTML before it is sent to the browser
$buffer = str_replace('Testing', 'Working', $buffer);
// Send $buffer to the browser
return $buffer;
}
// start output buffering at the top of our script with this simple command
// we've added "ob_postprocess" (our custom post processing function) as a parameter of ob_start
if (!ob_start('ob_postprocess'))
{
// Failure
echo "<br> Oops! Something went wrong with output buffering. Check that no HTML-Code is sent to client before calling this start function.";
// Handle error
}
else
{
// Success
// This is where the string should get accessed before sending to the client browser
echo "Testing OB.";
}
?>
<!--DOCTYPE html-->
<html lang="en">
<head>
<meta charset="utf-8">
//...
</body>
</html>
<?php
// end output buffering and send our HTML to the browser as a whole
ob_end_flush();
?>
Output: "Working OB."
EDIT: I added source code example. This code won't compile.
Since, i can't comment, so i'll put some of my question here.
I dont really get the point, but give me a try, are you mean escaping string? you can use backslashes \ to escape string.
Like this "select from ".$dbname." where id = \"".$id."\"".
You can easily using addslashes($var) before adding the variable to the sql. like this
$id = addslashes($_POST['id']);
$sql = "select form db where id = '$id'";
If you mean checking the existent of the user to select which form to show in the page, why dont you do this?
if(userCheck()) {
?>
// here write the html code if user passed
<?php
} else {
?>
// here write the html code if user not passed
<?php
}
You can put userCheck() as global function or whereever you place it, as long as you can use it when you want to check the user before showing the form.
tl;dr: The thing I was looking for was a combination of file_get_contents() and object buffering.
file_get_contents() returns a string of a plain html-file of your choice. I could post a ton of explanation here or simply link you to phppot.com. The article offers you a directly executable demo with source (Download here). In case you wanna try it with a html file of yours, simply change the file path.
So once the whole html was converted into a string, I used the postprocessing function of OB to alter the string (= basically my html) if it's an existing user that came to alter his data. Then all the html-code (in a string still at this point) is sent to the client using ob_end_flush(). I will put up the actual code asap :)

How can I differentiate between a 'Message' update and a 'Callback Query' update? (Telegram Bot API)

Sorry if my question gets too messy, I'm new here, so, any advice is welcome.
How can I differentiate between a 'Message' update and a 'Callback Query' update?
I've managed to make an inline keyboard, but when I use it, the bot just hangs, he doesn't reply anything. I did a little bit of research and found this question, which helped me understand the problem, but not much else.
My bot uses something like this right now:
// read incoming info and grab the chatID
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
switch($update["message"]["text"]){
/* insert magic here */
}
So, this code can handle Messages, but not CallbackQueries. If I wantew to handle them, I could use something like this (based on the other question's answer):
$callback_query = $update["callback_query"]
/* same as above */
But how can I check whether it is a message or a callback query?
if (($update['message']) != null) {
} else if ($update['callback_query'] != Null) {
According to telegram Docs:
At most one of the optional parameters can be present in any given
update.
so you just need to check which one of them is not Null.
You can simply check if CallbackQuery is null or not.
See the Telegram docs:
CallbackQuery
This object represents an incoming callback query from a callback
button in an inline keyboard. If the button that originated the query
was attached to a message sent by the bot, the field message will be
present. If the button was attached to a message sent via the bot (in
inline mode), the field inline_message_id will be present. Exactly one
of the fields data or game_short_name will be present.

HTTP Request to Edit Database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to use a MySQL database to verify that a user has bought a program from my site. I don't need to use a database, but this is the easiest way that I though this could be accomplished (any suggestions on different ways to accomplish a purchase-verification system are greatly appreciated).
My current algorithm:
User pays for the program (through one of various payment gateways provided by WooCommerce)
User is given a unique, randomized hex string by the server (this string is also stored in the database, as a key/value pair; string: 0; the 0 signifies unused)
User enters the string into the program (required), which sends an HTTP request (which includes the string) to the server. This request tells the server to look for the given string in the database. If it's found, change it's value to 1 (used). If the value is already 1 OR the string cannot be found, send an error report back to the user (program will not work).
If everything works correctly, the user can now use the program.
I have to use the HTTP request because only the server can edit the database. My website uses shared hosting, so I cannot directly modify the database on any local user.
I've never worked with databases before, but I know I have to use the INSERT, CREATE TABLE, UPDATE, and SELECT commands. In addition, I've never directly worked with HTTP requests.
How should the HTTP request look like, and how do I handle them on the server? Any other tips on how to work the database would also be appreciated.
Note: I'm probably going to use PHP (server-side) and Python (client-side).
Your html would look like this
<html>
<body>
<form action="validate.php" method="post">
Name: <input type="text" name="name"><br>
unique string: <input type="text" name="uniqueString"><br>
<input type="submit">
</form>
</body>
</html>
And on the server side, your validate.php would look like this.
<?php
$name = $_POST["name"];
$unqString = $_POST["uniqueString"];
//connect to your DB
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT uniqueStringUsedFlag FROM <stringTableName> WHERE uniqueString='.$unqString.'")
or die(mysql_error());
while($info = mysql_fetch_array( $data )) {
if $info['uniqueStringUsedFlag']==1{
return 'Error Message';
}else
{
mysql_query("update <stringTableName> set uniqueStringUsedFlag =1 where uniqueString='.$unqString.'");
return 'Success';
}
}
//if the control comes here, it means the record was not found.
return 'Error message'
?>
Replace < stringTableName > with your actual table name.
And do the same with the columns too.
PS: This code is untested. And please do proper validations, etc. Haven't included that here.
Let me know if this works.

using href to two links(php and a webpage) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
While($enreg=mysql_fetch_array($res))
{
$link_d.="<font color=\"red\">clic here to download</font></td>"
}
i want to use the href so it leads to download link, also to send the id to a php file so i can get how many times the files have been downloaded !
How can we use href to multiple links !
You can't. A link can only point to one resource.
Instead, what you should do is have your PHP script redirect to the file. The link points at your PHP script with the counter, and then set a Location: header (which automatically sets a 302 status code for redirection) with the value being the URL you want to redirect to.
Also, you should really use htmlspecialchars() around any variable data you use in an HTML context, to ensure you are generating valid HTML.
Ideally you would have some checks to see if it's a human downloading (Web crawlers may trigger it - we will put no-follow in the link which will help though). You could also use a database but that gets more complicated. My preferred way would be to use Google Analytics Events. But here is a simple PHP script that might fulfill your needs without the complexity of the other solutions.
First modify your links to have a tracker script and to urlencode
$link_d.= '<a style="color:red" href="tracker.php?url='.urlencode($enreg[link]).'" target="_blank">click here to download</a>';
}
Then create a script that will record downloads (tracker.php)
<?php
// keep stats in a file - you can change the path to have it be below server root
// or just use a secret name - must be writeable by server
$statsfile = 'stats.txt';
// only do something if there is a url
if(isset($_GET['url'])) {
//decode it
$url = urldecode($_GET['url']);
// Do whatever check you want here to see if it's a valud link - you can add a regex for a URL for example
if(strpos($url, 'http') != -1) {
// load current data into an array
$lines = file($statsfile);
// parse array into something useable by php
$stats = array();
foreach($lines as $line) {
$bits = explode('|', $line);
$stats[(string)$bits[0]] = (int)$bits[1];
}
// see if there is an entry already
if(!isset($stats[$url])) {
// no so let's add it with a count of 1
$stats[$url] = 1;
} else {
// yes let's increment
$stats[$url]++;
}
// get a blank string to write to file
$data = null;
// get our array into some human readabke format
foreach($stats as $url => $count) {
$data .= $url.'|'.$count."\n";
}
// and write to file
file_put_contents($statsfile, $data);
}
// now redirect to file
header('Location: ' . $url);
}
You can't.
Anchor are meant to lead to one ressource.
What you want to do is tipically addressed by using an intermediate script that count the hit and redirect to the ressource.
eg.
Click here to download
redirect.php
// Increment for example, a database :
// UPDATE downloads SET hits = (hits + 1) WHERE id=42
// Get the URI
// SELECT uri FROM downloads WHERE id=42
// Redirect to the URI
// (You may also need to set Content-type header for file downloads)
header( "Location: $uri" );
You may optimize this by passing the uri as a second parameter so that you won't need to fetch it at redirect time.
Click here to download
Another way of collecting this kind of statistics is to use some javascript tools provided by your statistics provider, like Google Analytics or Piwik, adding a listener to the click event.
It is less invasive for your base code but won't let you easily reuse collected data in your site (for example if you want to show a "top download" list).
Create a file with download script for example download.php and route all your downloads through it. Update your counter in this page and use appropriate headers for download.
eg:
url may be download.php?id=1&file=yourfile
in download.php
//get id and file
//database operation to update your count
//headers for download

Categories