Printing Postan POST message - php

Goodday,
I am facing a problem fetching send POST messages from postman on my local server. When i send an POST message the postman preview function prints my send data. However the webpage itself doesn't see the data and prints an error.
Postmand screenshot
Server screenshot
Here is my PHP script:
<head>
<title>PHP test page</title>
<h1>Number</h><br>
</head>
<body>
<?php
//$i = 0;
$data = $_POST["par"];
//while($data == ""){
//if($i == 0){
// echo "No data available";
//}
//$i = 1;
//}
echo $data;
//$page = $_SERVER['PHP_SELF'];
//$sec = "1";
//header("Refresh: $sec; url=$page");
?>
</body>
I am not experienced with this kind of stuff and am obviously missing something.
Why does the data not appear on the webpage itself?
Greetings

On your webpage, you're probably not sending it as a POST request.
Try debugging:
var_dump($_POST); // Add this. $_POST probably doesn't have an index called "par"
$data = $_POST["par"];
echo $data

You need to POST "par" variable to this page.

Related

How to fetch data every second from MYSQL database

I'm trying to make a Chat App using HTML, CSS, JS, PHP and Mysql.
I've completed all the functionalities that includes sending a message, receiving a message, displaying users... But the issue i'm facing is that i need to refresh the page every time i received a new message.
I'm looking for a way to auto update data with new data from mysql database.
Code:
<?php
if ($_GET['id']){
$id = $_GET['id'];
$id = preg_replace("/[^0-9]/", "", $id);
$fetching_messages = "SELECT * FROM users_messages WHERE from_user='$id' OR to_user='$id' ORDER BY id";
$check_fetching_messages = $db->prepare($fetching_messages);
$check_fetching_messages->execute();
$messages_all = $check_fetching_messages->fetchAll();
} else {
}
?>
<div id="autodata">
<?php foreach($to_users as $to_user) : ?>
<?php
$to_user_id = $to_user['to_user'];
$to_user_name = "SELECT * FROM users_accounts WHERE id='$to_user_id'";
$check_to_user_name = $db->query($to_user_name);
while ($row_to_user_name = $check_to_user_name->fetch()) {
$id_user = $row_to_user_name['id'];
$username = $row_to_user_name['username'];
$pdp = $row_to_user_name['profile_image'];
}
if ($id_user == $user_id){
} else {
echo '
<form style="height: fit-content;" name="goto'.$to_user_id.'" action="inbox.php">
<div onclick="window.location.replace('."'".'?id='.$to_user_id."'".')" class="inbox_chat_field_user">';
if (empty($pdp)){
echo "<img class='inbox_chat_field_user_img' src='uploads\profile\default.jpg'/>";
} else {
echo "<img class='inbox_chat_field_user_img' src='".$pdp."'/>";
}
echo '
<span class="inbox_chat_field_user_p">'.$username.'</span>
</div>
</form>
<hr class="inbox_separing_hr">';
}
?>
<?php endforeach;?>
</div>
Simply you can't do that, PHP is a server-side language, you can't tell the clients to refresh from PHP.
To accomplish that chat you should consider JavaScript in the browser.
The easiest way is by sending an AJAX request to your server and check if there are new messages every 5 or 10 seconds, and then do what you want with the messages in the response.
If you use jquery in your application you can send ajax request in this way:
$.get( "messages.php", function( data ) {
console.log( "Data Loaded: " + data );
});
and in messages.php script, you can fetch new messages from the database and return them with HTML or JSON format
You may also use FCM service offered by firebase to push your messages to the client directly, Check this package for PHP FCM.
There are other solutions like websockets etc...
It would have been easier for me to directly update your code had you separated business logic from presentation, so I am not going to attempt to do that. Instead I will describe a technique you can use and leave it to you to figure out the best way to use it. You might consider using server-sent events. See the JavaScript class EventSource.
The following "business logic" PHP program, sse_cgi.php, periodically has new output every 2 seconds (for a total of 5 times). In this case the output is just the current date and time as a string. But it could be, for example, a JSON record. Note the special header that it outputs:
<?php
header("Content-Type: text/event-stream");
$firstTime = True;
for ($i = 0; $i < 5; $i++) {
if (connection_aborted()) {
break;
}
$curDate = date(DATE_ISO8601);
echo 'data: This is a message at time ' . $curDate, "\n\n";
// flush the output buffer and send echoed messages to the browser
while (ob_get_level() > 0) {
ob_end_flush();
}
flush();
if ($i < 4) {
sleep(2); # Sleep for 2 seconds
}
}
And this is the presentation HTML that would be outputted. JavaScript code in this case is just replacing the old date with the updated value. It could just as well append new <li> elements to an existing <ul> tag or <tr> elements to an existing <table>.
<html>
<head>
<meta charset="UTF-8">
<title>Server-sent events demo</title>
</head>
<body>
<div id='date'></div>
<script>
var evtSource = new EventSource('sse_cgi.php');
var date = document.getElementById('date');
evtSource.onmessage = function(e) {
// replace old content
date.innerHTML = e.data;
};
evtSource.onerror = function() {
// occurs when script terminates:
evtSource.close();
console.log('Done!');
};
</script>
</body>
</html>
Note that this presentation references the "business logic" scripts that returns the successive dates.
Important Note
It is important to realize that this technique keeps the connection to the server open for the duration until all the data has been ultimately sent and the business logic script ultimately terminates (or the presentation running in the browser issues a call to evtSource.close() to close the connection). So if you have a lot of simultaneous users, this could be an issue.
If your application does not have a limited number of messages to return then the previously described problem can be overcome by having the business logic script return immediately after having sent one message. This will break the connection with the browser, which if it is still there, will automatically attempt to re-connect with the business logic script (note that this reconnection can take a while):
Updated Business Logic
<?php
header("Content-Type: text/event-stream");
# Simulate waiting for next message:
sleep(2);
$curDate = date(DATE_ISO8601);
echo 'data: This is a message at time ' . $curDate, "\n\n";
// flush the output buffer and send echoed messages to the browser
while (ob_get_level() > 0) {
ob_end_flush();
}
flush();
Updated Presentation
<html>
<head>
<meta charset="UTF-8">
<title>Server-sent events demo</title>
</head>
<body>
<div id='date'></div>
<script>
var evtSource = new EventSource('sse_cgi.php');
var date = document.getElementById('date');
evtSource.onmessage = function(e) {
// replace old content
date.innerHTML = e.data;
};
</script>
</body>
</html>

PHP echo in a HTML Page

I have a contact.html page I have a form on. The form action goes to .php page to handle the email, nothing special. On that page I have:
<?php
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$FirstName = check_input($_REQUEST['FirstName']);
$LastName = check_input($_REQUEST['LastName']);
$email = check_input($_REQUEST['email']);
$phone = check_input($_REQUEST['phone']);
$message = check_input($_REQUEST['message']);
$human = check_input($_REQUEST['human']);
$webpackage = check_input($_REQUEST['webpackage']);
$webdesign = check_input($_REQUEST['webdesign']);
$customdesign = check_input($_REQUEST['customdesign']);
if ($human == 5) {
$to = "****.com";
$subject = "From ****";
$body = " From: $FirstName $LastName\n\n E-Mail: $email\n\n Phone: $phone\n\n Message:\n\n $message\n\n Web Package:$webpackage\n\n Web Design:$webdesign\n\n Custom Design:$customdesign";
mail ($to, $subject, $body);
header('location: index.html');
}
else {
$result="<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please go back and check your anti-spam answer</div>";
}
?>
I have a simple box that equals 5 that I am checking value for. This works and email sent with all info. BUT if not equal to 5 is where the problem starts. The page goes to my action.php page and is blank.
My html on the contact.html page is:
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo($result); ?>
</div>
</div>
Using this to get to my action.php page through form. Everything else is .html:
<form class="form-horizontal" id="contact-form" method="post" action="/action.php">
Is there a way to do this? I have a work around where I just echo the error from the .php page. This works if !=5 but not exactly what I want to do. As you may tell, I am not PHP literate.
You can set a variable in the $_SESSION[] array, and in your "else" section use Header() to redirect to a page where you display the value you stored.
See example in this other answered question:
displaying a message after redirecting the user to another web page
Update your else part with following code :
} else {
header('location: contact.html?status=error');
}
Now check if get method is set on your contact.html page. if yes than set and display your $result value.
<?php
if(isset($_GET['status']) && $_GET['status']=='error' ) {
$result="<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please go back and check your anti-spam answer</div>";
} ?>
on contact.html check if $result has value and print it :)
Add a redirect towards contact.html in your action.php like this
else {
$result="Sorry there was an error sending your message. Please go back and check your anti-spam answer";
$result=str_replace(" ","%20",$result);
header('location: contact.html?result=$result');
}
And then get the result in contact.html with GET
$result= $_GET['result'];
Ideally do the html mark up for result in the destination Contact.html page after you receive the result. That eliminates the nuances of passing html over http

php - encode json to path

I have a JSON file and in it consists of site data. This site data is for a homepage (I decode the JSON into variables so I can echo them out within the HTML).
Here is my code:
<?php
//start json stuff
$path = "../assets/json/home.json";
$fileexists = file_exists($path);
if ($fileexists) {
$json_d = file_get_contents($path,TRUE);
$json = json_decode($json_d,TRUE);
} else {
die("Error retrieving site data - please refresh the page. If that doesn't work, please report a problem, here and come back later.");
}
if(isset($_POST['submit'])) {
$navtitle = $_POST['navtitle'];
$title = $_POST['title'];
$json_arr = array('navtitle' => $navtitle, 'title' => $title);
$json_enc = json_encode($json_arr);
$json_result = file_put_contents($path, $json_enc);
if($json_result) {
echo "<script>alert('WORKING!');</script>";
} else {
echo "<script>alert('NO WORKING!');</script>";
}
}
?>
So, I have created the array, encoded the array and placed it in the file (I think) but I do not see any changes.
NOTE: I have added the <meta http-equiv="expires" content="0"> meta tag to force the website/browser to grab the home.json file everytime the page is loaded in.
Thank you for any help.

How to display json data in a smarty template?

I'm using smarty and php for my website. There is some code which converts the data into json. I want to use that data in a smarty template. That data is a set of error messages and I want to display those messages in a assigned smarty template at desired ID. I'm not able to get that in smarty template. Actually what is happening is the error messages are displayed on a plain page instead in the desired tag.
Following is my smarty and PHP code:
Following is the smarty code where I want to display the error messages:
if $error_msg}<div class="error-info">{$error_msg.error_msgs}</div>{/if}
Now following is my PHP code:
<?php
if($request['form_submitted']=='yes') {
$ret = $objPracticeSheet->InsertPracticeSheet($request, $practice_sheet_error_messages);
if(!$ret) {
$error_msg = $objPracticeSheet->GetAllErrors();
$data = array();
$data['error_message'] = $error_msg['error_msgs'];
$data = json_encode($data);
echo $data;
die;
} else {
$data = array();
$data['success_message'] = "success";
$data = json_encode($data);
echo $data;
die;
}
} else {
$all_subjects = $objSubjectsTopicsQues->GetAllSubjectsHavingTopics();
$smarty->assign('all_subjects', $all_subjects);
$smarty->assign('sheet_type', 'practice');
$bread_crumbs_text = 'Add Practice Sheet';
$submit_value = 'Submit';
$cancel_value = 'Cancel';
$file_to_show = 'manage-practice-sheet.tpl';
}
$smarty->assign("op", $op);
$smarty->assign("query_string", $query_string);
$smarty->assign("bread_crumbs_text", $bread_crumbs_text);
$smarty->assign("submit_value", $submit_value);
$smarty->assign("cancel_value", $cancel_value);
$smarty->assign("error_msg", $error_msg);
$smarty->assign("file_to_show", $file_to_show);
/*$smarty->assign('create', '-active');
$smarty->assign("sub_menu_file", "epn-create-sub-menu.tpl");
$smarty->assign('practice_sheet', '-active');*/
$smarty->assign('practice_sheet', 'active');
$smarty->assign('prepare', 'selected');
$smarty->display("index.tpl");
?>
Can you help me in displaying the error messages json data in the above div? Thanks in advance. I'm also attaching the screenshot of the current output.
Use JavaScript to parse the JSON, then put the errors in the div.
To make this easier, let's give your div an id:
<div id="error-info-main" class="error-info"></div>
Then
<script>
{literal}
(function() {
var error_json = {/literal}{$error_msg.error_msgs}{literal};
var errors = JSON.parse(error_json);
document.getElementById('error-info-main').innerHTML = errors.error_message;
}());
{/literal}
</script>
Alternatively, you could just the pass the message itself from PHP:
$smarty->assign("error_msg", $error_msg->error_message);
This may not be 100% correct, as I don't have your data to test with, but I believe that's right. You get the idea at any rate.

How to convert Box's "code" to "token" after user allows access

I'm new at this, trying to hook up Box's API v2. I successfully set up a PHP client library, which I found thanks to the link in the first paragraph on developers.box.com/auth. I've read Box's walkthrough in full more than twice along with roughly 100,000 questions and replies here in regard to the matter. My problem occurs after the user redirects to Box's authorization page, enters his credentials and clicks on "Allow." The results vary according to my redirect_uri and the url of my login page where I've put my client_id and client_secret: 1) If my redirect_uri matches my https://mysite.com/login_with_box, the user redirects to that same url, obviously, which in turn sends the user back to Box's authorization page; and 2) if my redirect_uri differs from https://mysite.com/login_with_box page, then the user successfully returns to my redirect_uri, the url of which includes the 30-second code. I know that I'm close to figuring this out but don't know how to turn the code into a token in 30 seconds or less and use it to show the user's folders, files, info or whatever else. Many thanks for your consideration. Here's where I stand:
// mysite.com/client.php:
// ...
case 'Box':
$this->oauth_version = '2.0';
$this->request_token_url = '';
$this->dialog_url = 'https://api.box.com/oauth2/authorize?client_id={CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&state={STATE}';
$this->append_state_to_redirect_uri = '';
$this->access_token_url = 'https://api.box.com/oauth2/token';
$this->authorization_header = true;
$this->url_parameters = false;
break;
// ...
// mysite.com/login_with_box.php:
// ...
$client->client_id = '[my_client_id]';
$client->client_secret = '[my_client_secret]';
if(($success = $client->Initialize())) {
if(($success = $client->Process())) {
if(strlen($client->access_token)) {
$success = $client->CallAPI(
'https://api.box.com/2.0/users/me',
'GET', array(), array('FailOnAccessError'=>true), $user);
}
}
$success = $client->Finalize($success);
}
// ...
It looks like you need your redirect URL to be something different from the URL that initially sends the user through the OAuth process.
For example, you could have https://mysite.com/login_with_box send the user through the OAuth process, and https://mysite.com/receive_box_oauth_response be the URL that is redirected to after the auth process and handles the OAuth response from box.
I figured it out. The problem of course was entirely my fault. Here's how I hooked up the Box API v2 with the PHP OAuth library reccommended by Box:
Create an app on developers.box.com and set the required redirect_uri to something like https://mysite.com/oauth/login_with_box.php.
Download the PHP OAuth library at www.phpclasses.org/package/7700-PHP-Authorize-and-access-APIs-using-OAuth.html
Add something like the following case to PHP OAuth library's oauth_client.php.
case 'Box':
$this->oauth_version = '2.0';
$this->request_token_url = '';
$this->dialog_url = 'https://api.box.com/oauth2/authorize?response_type=code&client_id={CLIENT_ID}&state={STATE}';
$this->append_state_to_redirect_uri = '';
$this->access_token_url = 'https://api.box.com/oauth2/token';
$this->authorization_header = true;
$this->url_parameters = false;
break;
Create something like login_with_box.php and add it to PHP OAuth library. My login_with_box.php reads as follows.
<?php
require('http.php');
require('oauth_client.php');
$client = new oauth_client_class;
$client->server = 'Box';
$client->redirect_uri = 'https://mysite.com/oauth/login_with_box.php';
$client->client_id = 'xxxxxx_BOX_API_CLIENT_ID_xxxxxx';
$client->client_secret = 'xxxxxx_BOX_API_CLIENT_SECRET_xxxxxx';
if(strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
die('You need an app to do that.');
if(($success = $client->Initialize())) {
if(($success = $client->Process())) {
if(strlen($client->access_token)) {
$success = $client->CallAPI(
'https://api.box.com/2.0/folders/0',
'GET', array('format'=>'json'), array('FailOnAccessError'=>true), $folder);
}
}
$success = $client->Finalize($success);
}
if($client->exit)
exit;
if($success) {
?>
<!doctype html>
<html>
<head>
<title>Box OAuth client results</title>
</head>
<body>
<?php echo '<h1>You successfully logged in with Box</h1>'; echo '<pre>', HtmlSpecialChars(print_r($folder, 1)), '</pre>'; ?>
</body>
</html>
<?php } else { ?>
<!doctype html>
<html>
<head>
<title>OAuth client error</title>
</head>
<body>
<h1>OAuth client error</h1>
<pre>Error: <?php echo HtmlSpecialChars($client->error); ?></pre>
</body>
</html>
<?php } ?>
I hope this helps somebody.

Categories