I working on a very simple form project, I send items using ajax and save them on the database using PHP insert query, then by clicking a button I fetch data using ajax from another PHP file using SELECT query, the problem is when I want to get new data the PHP query doesn't update data and it returns old data if I check the file whit out using ajax and I put the URL like mysite.com/getdata.php it still returns old data and I have to refresh this page until it fetches new data, I don't have any error or warning in my javascript code or PHP and I have no idea why it doesn't get new data whit new request and I have to refresh the URL till fetches new data.
It worked correctly local I see this bug when I upload my code to the server
My getdata.php file code:
<?php
$servername = "localhost";
$username = "projectform";
$password = "jtq*o2ZL7qBPt_HS";
$dbname = "projectform";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
$responseData = json_encode(array(
"status" => $status,
"message" => "Connection failed: " . $conn->connect_error,
"data" => null,
));
die($responseData);
}
$sql = "SELECT * FROM form_data";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$data[] = array(
'id' => $row["id"],
'Title' => $row["title"],
'address' => $row["address"],
'photo' => $row["p_date"],
'phone' => $row["phone"],
'detail' => $row["detail"],
'create' => $row["created_at"],
'status' => $row["status"],
);
}
$status = "success";
$message = "";
$response = $data;
} else {
$data = null;
$status = "error";
$message = "NO data found.";
}
$conn->close();
$responseData = json_encode(array(
"status" => $status,
"message" => $message,
"data" => $response,
));
die($responseData);
If you are using pure PHP, you can try to disable browser cache like this:
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Connection: close");
Related
I need help in Twilio getting reply responses and storing them in the database in response to sending SMS after user input in response to the message. I am sending an SMS to the user about his/her order schedule and asking him/her to confirm delivery by inputting Ok and when he/she confirm, I am getting his response successfully.
The question or the issue I am facing is that I want to know that when he/she confirm the delivery, I want to update the database record in response to the delivery SMS we sent to him/her earlier. My issue will be resolved if I am able to get order_id from the first message and send it in replytoSMS function.
My Code to send SMS and webhook (replytoSMS) are given below.
<?php
public function initiateSMS(Request $request) {
try {
foreach ( $request->get('items') as $item ) {
$order_id = $item['order_id'];
$phone = $item['phone_number'];
$order = Orders::where('id', $order_id)->first();
$phone_number = $this->client->lookups->v1->phoneNumbers($phone)->fetch();
if($phone_number) {
$template_value = $order->message;
$sms = $this->client->messages->create($phone, [
'from' => $this->from,
'body' => $template_value,
"method" => 'POST',
"statusCallbackMethod" => 'POST',
"statusCallback" => 'https://example.com/simply/public/api/notification/statusMessageBack?order_id='.$order_id.'',
]);
// print($sms->sid);
}
} // foreach loop end
if($sms){
return Response::json(['success' => 'sms initiated successfully!']);
}
} catch (Exception $e) {
return Response::json(['Error' => $e->getMessage()]);
} catch (RestException $rest) {
return Response::json(['Error' => $rest->getMessage()]);
}
}
function statusMessageBack(){
header('Content-type: text/xml');
header('Cache-Control: no-cache');
$response = new MessagingResponse();
$order_id = $_REQUEST['order_id'];
$user_phone = $_REQUEST['To'];
$MessageSid = (!empty($_REQUEST['MessageSid'])) ? $_REQUEST['MessageSid'] : '';
$MessageStatus = (!empty($_REQUEST['MessageStatus'])) ? $_REQUEST['MessageStatus'] : '';
if($MessageStatus && $MessageStatus == "delivered"){
$notification = Notification::create([
"response_code" => $MessageSid,
"type" => $category,
"table_ref" => "orders",
"table_ref_pk" => $order_id,
"response_status" => "",
"medium" => $user_phone,
"status" => $MessageStatus,
"sender_id" => $sender_id
]);
}
print $response; exit;
}
public function replyToSMS(){
header('Content-type: text/xml');
header('Cache-Control: no-cache');
$response = new MessagingResponse();
$MessageSid = (!empty($_REQUEST['MessageSid'])) ? $_REQUEST['MessageSid'] : '';
$MessageStatus = (!empty($_REQUEST['MessageStatus'])) ? $_REQUEST['MessageStatus'] : '';
$body = $_REQUEST['Body'];
$order_id = $_REQUEST['order_id'];
$from_phone = $_REQUEST['From'];
if (strtolower($body) == 'ok' || strtolower($body) == 'yes' || strtolower($body) == 'confirm') {
$response->message('Your delivery has been confirmed. Thank you', [
'callbackUrl' => "https://example.com/api/notification/reply_status?order_id='.$order_id.'",
'callbackMethod' => "POST"
]);
$notification = Notification::where('order_id', $order_id)->update(array("response_status" => "confirmed"));
} else {
$response->message('Sorry');
$notification = Notification::where('order_id', $order_id)->update(array("response_status" => "call store"));
}
print $response;
}
function reply_status(){
header('Content-type: text/xml');
header('Cache-Control: no-cache');
$response = new MessagingResponse();
echo $order_id = $_REQUEST['order_id'];
$user_phone = $_REQUEST['To'];
$MessageSid = (!empty($_REQUEST['MessageSid'])) ? $_REQUEST['MessageSid'] : '';
$MessageStatus = (!empty($_REQUEST['MessageStatus'])) ? $_REQUEST['MessageStatus'] : '';
if($MessageStatus && $MessageStatus == "delivered"){
}
print $response; exit;
}
The SMS protocol does not any concept of additional metadata with SMS messages, nor does it have the concept of replying to a specific message (you can test this by opening your phone's SMS application and trying to respond to any message from someone that wasn't the last one you received).
You can only really tell what someone may be responding to chronologically. That is, if you have sent them a message, then their response is related to that last message that you sent.
This is an issue if you intend to send more than one message asking for a response at the same time. In this situation, we recommend you use two different From numbers to send the message and store that From number against the order in your system. That way you can tell which message was being responded to by matching up the user's phone number and the phone number that you used to send the message.
I am developing an app with Kotlin-PHP-MySql.
I will be appreciated if someone has an idea why I get this exception "com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path" when I call createUser function.
I don't get an exception when I call getUser function with Same api.
I checked these two functions in postman. JSONs are formatted properly. Begins with
{ "key" : "value", "key1" : "value1", .... }
This is my api:
interface Api {
...
#POST("/api/v1/users/register_user.php")
suspend fun createUser(
#Body userDto: UserInfoPreviewDto
) : QueryResponse
#POST("/api/v1/users/get_user.php")
suspend fun getUser(
#Body jsonObject : JsonObject
) : UserDto
}
and my Retrofit instance:
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(RamonApiUser::class.java)
and my server-side php code is
register_user.php file:
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-
Headers, Authorization, X-Requested-With");
include_once("../../config/database.php");
include_once("../../classes/user.php");
$db = new Database();
$connection = $db->connect();
$user = new User($connection);
if($_SERVER['REQUEST_METHOD'] === "POST") {
$data = json_decode(file_get_contents("php://input"));
$user->username = $data->username;
$user->password = $data->password;
$user->fullname = $data->fullname;
$user->email = $data->email;
if($user->register()) {
http_response_code(200);
$result = array(
"status" => "200",
"message" => "saved"
);
echo json_encode($result);
}
else {
http_response_code(500);
echo json_encode(array(
"status" => "500",
"message" => "Error 500"
));
}
}
else {
http_response_code(503);
echo json_encode(array(
"status" => "503",
"message" => "Error 503"
));
}
this my get_user.php file:
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers,
Authorization, X-Requested-With");
include_once("../../config/database.php");
include_once("../../classes/user.php");
$db = new Database();
$connection = $db->connect();
$user = new User($connection);
if($_SERVER['REQUEST_METHOD'] === "POST") {
$param = json_decode(file_get_contents("php://input"));
if(!empty($param->id)) {
$user->id = $param->id;
$user_data = $user->getById();
if (!empty($user_data)) {
http_response_code(200);
$user_data['isPublicProfile'] = (bool)$user_data['isPublicProfile'];
$user_data['isLastOnlineVisible'] =
(bool)$user_data['isLastOnlineVisible'];
$user_data['isPhoneNumberVisible'] =
(bool)$user_data['isPhoneNumberVisible'];
echo json_encode($user_data);
}
}
}
else {
http_response_code(503);
echo json_encode(array(
"status" => "0",
"message" => "503 error"
));
}
getById() function in user.php :
public function getById() {
$sqlQuery = "SELECT * FROM ". $this->table_name ." WHERE id = ? LIMIT 0,1";
$obj = $this->conn->prepare($sqlQuery);
$obj->bind_param("i", $this->id);
$obj->execute();
$data = $obj->get_result();
return $data->fetch_assoc();
}
I have QueryResponse data class in the client-side with the fields status and message. user->register() returns true or false . I think the problem is with my json_encode method. I also tried this:
I created a QueryReponse php class with fields status and message and encode this object like this:
$query_response = new QueryResponse();
$query_response->status = "200";
$query_response->message = "registration successful";
$echo json_encode($query_response);
it didn't help either.
I created another file called get_query_response.php. Just to make sure that my QueryResponse classes are OK and doesn't throw exceptions.
get_query_response.php:
....
include_once("../../config/database.php");
include_once("../../classes/query_response.php");
$db = new Database();
$connection = $db->connect();
$query_response = new QueryResponse($connection);
if($_SERVER['REQUEST_METHOD'] === "POST") {
$query_response->id = 1;
$query_response_data = $query_response->getById();
// I fetch query_response_data from mysql
if (!empty($query_response_data)) {
http_response_code(200);
$result = array(
"status" => "500",
"message" => "save successfully"
);
echo json_encode($result); // doesn't throw exception.
works fine
//echo json_encode($query_response_data);
//when i use this line, it doesn't throw exception
//either. works fine
}
}
I call this file get_query_response.php from my api like this:
interface MyApi {
...
#POST("/api/v1/users/get_query_response.php")
suspend fun getQueryResponse() : QueryResponse
...
}
No errors, no exceptions. Both echo json_encode($result) and echo json_encode($query_response_data) works fine.
The only difference between two register_user.php and get_query_response.php files is this line:
$data = json_decode(file_get_contents("php://input"));
I don't get the reason why these two files behave differently. They are almost identical. Why does not this code work in register_user.php?
$result = array(
"status" => "200",
"message" => "saved successfully"
);
echo json_encode($result);
I finally solved the problem. It was my data class UserInfo. One field of the class was being assigned null during instantiation. Api is sending a class which two properties of that class has null values. The problem is solved by assigning values to those properties.
I am sending an e-mail with different variables as an JSON encoded array from an online store. I get the mail just fine and all the data is in there except for one of the variables, which is a JSON encoded array by itself. this particular variable shows as "false" in the e-mail. I'm missing something?
I'm using PHP mail to do it.
<?php
require_once "Mail.php";
$link = mysqli_connect("localhost", "xxx", "xxx", "xxx");
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM users WHERE user = '" . $_SESSION['logged'] . "'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_assoc($result);
$user = $_SESSION['logged'];
$rua = $_POST['rua'];
$numero = $_POST['numero'];
$apt = $_POST['apt'];
$cep = $_POST['cep'];
$total = $_POST['total'];
$comment = $_POST['observacion'];
$from = $row['mail'];
$mailTo = "xxxxx#hotmail.com";
$subject = "compra online - no cep";
$compra = $_SESSION["shopping_cart"];
$compra2 = json_encode($compra);
$bod = array(
'user' => $user,
'rua' => $rua,
'cep' => $cep,
'compra' => $compra2,
'comment' => $comment,
'total' => $total,
);
$body = json_encode($bod);
$headers = array(
'From' => $from,
'To' => $mailTo,
'Subject' => $subject,
);
$smtp = Mail::factory('smtp', array(
'host' => 'smtp-mail.outlook.com',
'port' => '587',
'auth' => true,
'username' => 'xxxxxxx#hotmail.com',
'password' => 'xxxxxxx',
));
$mail = $smtp->send($mailTo, $headers, $body);
if (PEAR::isError($mail)) {
echo ("<p>" . $mail->getMessage() . "</p>");
} else {
header("Location: lojacart.php?mailok");
}
mysqli_close($link);
I'm getting the e-mail with all the data except for the $compra2 variable which is showing as 'compra'=false. now if I echo the variable $compra2 it actually have a large string of data on it.
I think it might have to do with the variable being a JSON encoded session, but I'm not sure.
After a lot of trying and getting frustrated I came with a solution, for those looking for a something like this:
I added a hidden input to the form on the previous page and assigned it a value as "print_r($SESSION['whatever you session is called'], TRUE)" ...
on the next page I took the $_POST[] form that input and added the variable to the $body array for the mail().
It will print some array garbage in the middle BUT it works like a charm! and I cleaned all the "extra" text form the array using preg_replace(). It may not be an elegant way of doing it but as I said... it worked
I am trying to implement a web service using PHP. I am following xml-rpc protocol.
I am trying to call a function through index file and display records from the database but when i try to call the function in file server2 nothing is printed on the screen just a blank white screen is showed up here is my code so far.
Kindly help me out with this I have spent hours searching about this but cannot find any help
server2.php
<?php
$request_xml = file_get_contents("php://input");
function say_hello($method_name, $args) {
$dbLink = mysqli_connect('localhost','root','saad','enstructo');
if (!$dbLink) {
echo "ERROR";
}
$query = "SELECT * FROM Admin";
if ($result = mysqli_query($dbLink,$query)) {
while($getquery = mysql_fetch_array($result)){
$returnquery[] =array($result['username'],$result['email']) ;
}
}
return $returnquery;
}
$xmlrpc_server = xmlrpc_server_create();
xmlrpc_server_register_method($xmlrpc_server, "say_hello", "say_hello");
header('Content-Type: text/xml');
print xmlrpc_server_call_method($xmlrpc_server, $request_xml, array());
?>
index.php
<?php
$request = xmlrpc_encode_request("say_hello", array('10'));
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml\r\nUser-Agent: PHPRPC/1.0\r\n",
'content' => $request
)));
$server = 'http://localhost/rpc/basic/server2.php';
$file = file_get_contents($server, false, $context);
$response = xmlrpc_decode($file);
echo $response;
?>
Can anyone please tell me how to store images in an oracle database as BLOBs using PHP?
A working example would be nice. Thankyou.
You first need to get the image that is being uploaded from the $_FILES #global array:
$image = file_get_contents($_FILES['image_field_name']['tmp_name']);
Then to insert the image in the database try this:
$sql = "INSERT INTO table (id, image) VALUES(1, empty_blob()) RETURNING image INTO :image";
$result = oci_parse($connection, $sql);
$blob = oci_new_descriptor($connection, OCI_D_LOB);
oci_bind_by_name($result, ":image", $blob, -1, OCI_B_BLOB);
oci_execute($result, OCI_DEFAULT) or die ("Unable to execute query");
if(!$blob->save($image)) {
oci_rollback($connection);
}
else {
oci_commit($connection);
}
oci_free_statement($result);
$blob->free();
Thank you DRiFTy, I build my small JSON query on your example.
Let's clarrify that you can save large images with both examples.
<?php
// Database parameters
$oci_user = 'YOUR_DB_USER';
$oci_pw = 'YOUR_DB_PASSWORD';
$oci_db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 000.000.000.000)(PORT = 1521)))(CONNECT_DATA=(SID=XXX)))";
// Get data from JSON imput
$data = json_decode(file_get_contents("php://input"),true);
// Now you can do some checks on date etc.
$img = $data['IMAGE'];
$jfid = $data['OBJECT_ID'];
$jfdate = $data['DATE'];
// Let's beginn with the blob upload
// We have 3 fiels in our table: OBJECT_ID,DATE,BLOBIMAGE
// First you fill your BLOB with an 'Empty' one and assign in PL/SQL style :img
$sql = "INSERT INTO ZAEHLER.METERAPP_BILD (OBJECT_ID,DATE,BLOBIMAGE)
VALUES (".$jfid.",to_date('".$jfdate."','DD/MM/YYYY'),empty_blob())
RETURNING BLOBIMAGE INTO :img";
$result = oci_parse($conn, $sql);
$blob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($result, ":img", $blob, -1, OCI_B_BLOB);
oci_execute($result, OCI_NO_AUTO_COMMIT);
// Now let's check if we could connect to database or if we have to output something => 500
if(!$result){
$err = oci_error();
header('HTTP/1.0 500 Internal Server Error');
header('Content-Type: application/json');
$out = array('code' => '500', 'response' => '500 Internal Server Error / SQL connection problem', 'error sql' => $err[message]);
echo json_encode($out);
}
// Can we same the image ($img) or not => 406
// This step saves the image to the db
if(!$blob->save($img)) {
oci_rollback($conn);
header('HTTP/1.0 406 Not Acceptable');
header('Content-Type: application/json');
$out = array('code' => '406', 'response' => '406 Not Acceptable / Wrong image type or JSON error');
echo json_encode($out);
}
// If both was ok, we're going to commit and output an OK => 200
else {
oci_commit($conn);
header('HTTP/1.0 200 OK');
header('Content-Type: application/json');
$out = array('code' => '200', 'response' => '200 OK', 'response advanced' => 'Image saved', 'object_id' => $jfid, 'file date' => $jfdate);
echo json_encode($out);
}
// Clean up
oci_free_statement($result);
$blob->free();
?>
You can use PDO too:
<?php
include '../conexao_oracle.php';
$db = $pdo;
$db->beginTransaction(); // Essential!
$mimetype = 'image/jpeg';
$funcionario_id = 10;
$stmt = $db->prepare(
"INSERT INTO foto (mimetype, binario, funcionario_id) ".
"VALUES (:mimetype, EMPTY_BLOB(), :funcionario_id) ".
"RETURNING binario INTO :binario");
$stmt->bindParam(':mimetype', $mimetype);
$stmt->bindParam(':binario', $blob, PDO::PARAM_LOB);
$stmt->bindParam(':funcionario_id', $funcionario_id);
$blob = fopen('fotos/10.jpg', 'rb');
$stmt->execute();
$pdo->commit();