How to store audio in multipart using json on server php? - php

<?php
session_start();
include("db.php");//database connectivity
$uid=$_POST['uid'];//user's id
$meeting_id=$_POST['meeting_id'];//meeting id
// Create directory if it does not exist
if(!is_dir("audioupload/".$uid."/".$_SESSION["uid"]."/"))
{
mkdir("audioupload/".$uid."/".$_SESSION["uid"]."/");
}
$info = pathinfo($_FILES['audio']['name']);
$ext = $info['extension'];
$audio_name = "meeting_id".$meeting_id.".".$ext;
// Move the uploaded file
$upload=move_uploaded_file($_FILES["audio"]["tmp_name"], "audioupload/".$uid."/".$_SESSION["uid"] ."/". $audio_name);
$sql="INSERT INTO `audio`(`uid`,`meeting_id`,`audio`) VALUES ('".$uid."','".$meeting_id."','".$audio_name."')";
$result1 = mysqli_query($conn,$sql);
if($result1)
{
$sql1="select * from `audio` where `uid`='$_POST[uid]'";
$result = mysqli_query($conn,$sql1);
$count = mysqli_num_rows($result);
}
if($count>0)
{
$emparray = array();
while($row = mysqli_fetch_array($result))
{
$emparray=array(
'success' => true,
'message' => "Audio saved Successfully!",);
}
}
else
{
$row = mysqli_fetch_array($result);
$emparray=array(
'success' => false,
'message' => "Incorrect Data!",
);
}
echo json_encode($emparray,JSON_PRETTY_PRINT,JSON_FORCE_OBJECT);
mysqli_close($conn);
?>
this is my code for audio api.
i got to different results from same code. postman tool give me proper result whereas app doest give. wts the problem ?

Related

Can't get a JSON object response to an Ajax request on live server

I have a form which when submitted made request to the server through ajax using php curl. Everything worked perfectly in my local environment(wamp) but when I moved it to live server, it doesn't return any json response.
I can't figure out why it worked in wampserver but not on live server?
php code
<?php
if(isset($_POST['logins']))
{
require_once 'functions.php';
require_once("cons.php");
$licence = $_POST['licence'];
$url = "http://tapi.com/apis/User/api.php?licence=".$licence;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$data = json_decode($response, true);
$msg = $data['message'];
$lic = $data['licence'];
$p = $data['period'];
$u = $data['user'];
$sta = $data['status'];
if($msg == 'Successfully Validated!')
{
//$_SESSION['data'] = array($data, true);
$url = "http://tapi.com/apis/User/api.php?lic=".$lic;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$data = json_decode($response, true);
$msg = $data['message'];
if($msg == 'inserted')
{
$host = $_SERVER['HTTP_HOST'];
$hostaddrs = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$sys_info = php_uname();
$exp_date = encryptIt2($p);
$date = date('Y-m-d');
$ts = encryptIt2($date);
$queryu = "insert into tray(host, license, validity, et)values('$host', '$lic', '$exp_date', '$ts')";
$get = mysqli_query($mysqli,$queryu);
if($get){
echo "yes";
}else{
echo $mysqli -> error;
}
}else{
echo $msg;
}
}
else
{
echo $data['message'];
}
}
?>
jQuery code
function licenceForm()
{
var data = $("#licence-form").serialize();
$.ajax({
type : 'POST',
url : 'ext/b0a012.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-login").html('<img src="assets/img/find.png"
width="26" height="25"> Please wait...');
},
success : function(response)
{
if(response=="yes"){
$(".hideit").hide();
$(".shows").show();
setTimeout('window.location.href = "index.php"; ',2000);
}else{
$("#error").fadeIn(1000,function(){
$("#error").html('<div class="alert alert-danger text center">
<img src="assets/img/attention.png" width="45" height="40" />
<br/> '+response+'</div>');
$("#btn-login").html('Error occured. Try again.');
});
}
}
});
return false;
}
API
if (isset($_GET['licence']) && $_GET['licence']!="") {
$licence = $con->real_escape_string($_GET['licence']);
//$licence = "M7RS-8C46-APSE";
$selec = mysqli_query($con, "SELECT licence, period, users FROM licence_used WHERE licence='$licence'");
$mrow = mysqli_fetch_array($selec);
$count = mysqli_num_rows($selec);
if($count > 0){
$q2 = mysqli_query($con,"select count(licence) use_count FROM licence_used WHERE licence='$licence'");
$get = mysqli_fetch_array($q2);
//query 2
$selec = mysqli_query($con, "SELECT licence,
period, users FROM licence_used WHERE licence='$licence'");
$users = $mrow['users'];
$num = $get['use_count'];
if($num == $users){
$user_arr=array(
"status" => false,
"message" => "Licence key entered has been used up by ".$num." users. Please purchase another licence.",
);
}else{
while($row = mysqli_fetch_array($selec)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"licence" => $mrow['licence'],
"period" => $mrow['period'],
"user" => $mrow['users'],
"mstatus" => $mrow['status']
);
}
}
}else{
$select = mysqli_query($con, "SELECT licence, period, users FROM licence WHERE licence='$licence'");
if(mysqli_num_rows($select) == 0){
$user_arr=array(
"status" => false,
"message" => "Invalid Licence Key Entered. Please contact the software company.",
);
}else{
while($row = mysqli_fetch_array($select)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"licence" => $row['licence'],
"period" => $row['period'],
"user" => $row['users'],
"mstatus" => $row['status']
);
}
}
}
}
header("Content-Type:application/json");
print_r(json_encode($user_arr));
I used postman to test it and it worked. Do anyone know what the issue might be? Thanks.

PHP pass an ID between scripts

I have a problem that I can't solve.
I am creating an Android App where there is a section showing user data.
The data is saved on a MySql database through Register.php and to get them use the Show.php file.
When I open the user activity in the app, there is a hidden field that contains the user's id, the app sends the id to the Php script and shows all the data of that user.
The problem is that the data is shown with a bit of delay, because it has to read the id from the app and show the filtered data.
What I would like is that in the Php file there was already the user id, so the display of the data on the app would be instantaneous, because so I already have the value of the variable that contains the id to use then in the Query.
To do this I thought of using sessions.
But it does not work.
In the Register.php file I inserted a session variable to store the value of the variable id_restaurants that I need in the show.php script to show that user's data through a Query.
But in the Register.php file it seems that the value of the variable $ _SESSION ['varId'] is not saved.
What am I doing wrong?
Here is the registration file: Register.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD']=='POST'){
include_once("config2.php");
$idUser = $_POST['idUser'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$restaurant = $_POST['restaurant'];
$id_restaurant = $_POST['id_restaurant'];
$_SESSION['varId'] = '$id_restaurant';
if($name == '' || $surname == '' || $restaurant =='' ){
echo json_encode(array( "statusr" => "false","message" => "Insert all data") );
}else {
$query= "SELECT * FROM Restaurants WHERE restaurant='$restaurant'";
$result= mysqli_query($con, $query);
if(mysqli_num_rows($result) > 0){
echo json_encode(array( "statusr" => "false","message" => "Name restaurant already exist") );
}else{
$query = "INSERT INTO Restaurants (idUser,name,surname,restaurant,id_restaurant) VALUES ('$idUser','$name','$surname','$restaurant','$id_restaurant')";
if(mysqli_query($con,$query)){
$query= "SELECT * FROM Restaurants WHERE name='$name' AND surname='$surname' AND restaurant='$restaurant' ";
$result= mysqli_query($con, $query);
$emparray = array();
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
}
echo json_encode(array( "statusr" => "truer","message" => "Registered succesfully!" , "datar" => $emparray) );
}else{
echo json_encode(array( "statusr" => "false","message" => "Error") );
}
}
mysqli_close($con);
}
} else{
echo json_encode(array( "statusr" => "false","message" => "Errore3") );
}
?>
Here is the show file: Show.php
<?php
session_start();
include 'config.php';
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
$idRestaurant = $_SESSION['varId'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Food WHERE id_restaurant ='$idRestaurant'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
?>
And then you think there's a better way to pass the id between Php scripts?
I listen to you willingly.
Thanks a lot.

Unable To echo an HTML <form></form> within PHP

I am trying to echo an HTML form within PHP but I just can't get it done.
It just echo pre-formatted HTML. I ain't getting the form.
Here is my PHP script
do-reset.php
<?php
require_once 'connect.php';
session_start();
if($_SERVER['REQUEST_METHOD'] === 'GET') {
if(isset($_GET['email']) && !empty($_GET['email']) && isset($_GET['hash']) && !empty($_GET['hash'])) {
$email = htmlentities(mysqli_real_escape_string($connection, trim($_GET['email'])));
$hash = htmlentities(mysqli_real_escape_string($connection, trim($_GET['hash'])));
$search_query = "SELECT email, hash, status FROM users WHERE email = '{$email}' AND forgot_password_hash = '{$hash}' AND
status = '1'";
$do_search_query = mysqli_query($connection, $search_query);
if($do_search_query) {
$count_rows = mysqli_num_rows($do_search_query);
if($count_rows > 0) {
$_SESSION['email'] = $email;
$_SESSION['hash'] = $hash;
echo "<form method='post' action='do-reset.php'><input type='password' name='password'><br><input type='submit' value='Reset My Password'></form>";
}
else {
$data = array("result" => -3, "message" => "Invalid URL");
}
}
else {
$data = array("result" => -2, "message" => "Something Went Wrong! Try Again Later.");
}
}
else
{
$data = array("result" => -1, "message" => "Certain Request Parameters Are Missing!");
}
}
else {
$data = array("result" => 0, "message" => "Incorrect Request Method!");
}
mysqli_close($connection);
/* JSON Response */
header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);
?>
1.: Remove the header('Content-type: application/json');
This will basically tell the browser to display the output as text.
2.:
to preserve formatting, you can use <pre>-tags:
echo "<pre>";
echo json_encode($data, JSON_PRETTY_PRINT);`
echo "</pre>";
Different approach:
only set content type to application/json when the $data-array is filled
if(!empty($data)){
header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);
}
I found a way out! $type_json did the trick for me.
<?php
require_once 'connect.php';
session_start();
$type_json = true;
if($_SERVER['REQUEST_METHOD'] === 'GET') {
if(isset($_GET['email']) && !empty($_GET['email']) && isset($_GET['hash']) && !empty($_GET['hash'])) {
$email = htmlentities(mysqli_real_escape_string($connection, trim($_GET['email'])));
$hash = htmlentities(mysqli_real_escape_string($connection, trim($_GET['hash'])));
$search_query = "SELECT email, hash, status FROM users WHERE email = '{$email}' AND forgot_password_hash = '{$hash}' AND
status = '1'";
$do_search_query = mysqli_query($connection, $search_query);
if($do_search_query) {
$count_rows = mysqli_num_rows($do_search_query);
if($count_rows > 0) {
$_SESSION['email'] = $email;
$_SESSION['hash'] = $hash;
$type_json = false;
echo "<form method='post' action='do-reset.php'><input type='password' name='password'><br><input type='submit' value='Reset My Password'></form>";
}
else {
$data = array("result" => -3, "message" => "Invalid URL");
}
}
else {
$data = array("result" => -2, "message" => "Something Went Wrong! Try Again Later.");
}
}
else
{
$data = array("result" => -1, "message" => "Certain Request Parameters Are Missing!");
}
}
else {
$data = array("result" => 0, "message" => "Incorrect Request Method!");
}
mysqli_close($connection);
/* JSON Response */
if($type_json) {
header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);
}
?>
PHP is executed on the server side and is treated as a script instead of a markup language, meaning the HTML on the requested page doesnt matter to the server at all it only cares about the PHP. so if you did
<?php
if(true) {
?>
<form>Hello</form>
<?php
}
?>
the html form will only be displayed with the text hello if the statement is true, which true always is true ofcourse. you could replace this with any statement, for example to check if someone hes entered something in a field from the form they submitted.
hope this helps!

Php unable to determine userid availability with jQuery Validate

I have a problem with using jQuery validate remote function with php. I try to check the user id with query whether the user id is exist or not. But it alway show user is in used.
Here is my jQuery validate code:
userID: {
required: true,
minlength: 5,
remote : {
url: "checkUserId.php",
type: "post"
}
},
Here is my php checking code:
<?php
include "session.php";
include 'dbConnect.php';
global $conn;
$requestedID = $_POST['userID'];
$query = "SELECT * FROM Users WHERE _userID = '$requestedID'";
$result = sqlsrv_query($conn,$query);
$row_count = sqlsrv_num_rows($result);
if($row_count === false){
echo 'false';
}
else if($row_count >=0){
echo 'true';
}
?>
Anything I did wrong in my query?
Change your if else condition.
if($row_count == 0){
echo 'true';
}else{
echo 'false';
}
true = not exist, false = exist
I had successfully solved it with this code. Thanks for all the support.
Here is my updated code:
<?php
include "session.php";
include 'dbConnect.php';
global $conn;
$requestedID = $_REQUEST['userID'];
$query = "SELECT * FROM Users WHERE _userID = '$requestedID'";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result = sqlsrv_query($conn,$query , $params, $options);
$row_count = sqlsrv_num_rows($result);
if($row_count >= 1){
echo 'false';
}
else{
echo 'true';
}
?>

not returning sufficient rows

What I'm trying to figure out here is how to access the different array values that I need. I have the following query and it returns this for an array when the print_r() is applied. For some reason it only does the first row from the db table. It should return a whole another row.
<?php
session_start();
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = "no";
if((empty($_POST['answer1'])) || (trim($_POST['answer1'])=="") || ($_POST['answer1'] == NULL) || (!isset($_POST['answer1']))){$errors = "yes";}
if((empty($_POST['answer2'])) || (trim($_POST['answer2'])=="") || ($_POST['answer2'] == NULL) || (!isset($_POST['answer2']))){$errors = "yes";}
// Error checking, make sure all form fields have input
if ($errors == "yes") {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => true, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answerPost) {
} else {
$errors = "yes";
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => true, 'message' => $message);
}
}
} else {
$errors = "yes";
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Because you just fetch the first one, where you should loop on the result set instead:
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '$userID'";
$result = mysqli_query($dbc,$query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
print_r($row);
}
}
By the way, you should be using prepared statements to avoid SQL injection.
You need to wrap your fetch in a loop. e.g.
if (mysqli_num_rows($result) > 0)
{
while (($row = mysqli_fetch_array($result)) !== false)
{
if ($row['answer'] == $answerPost)
{
// $row matches what we're looking for
}
else
{
$errors = "yes";
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => true, 'message' => $message);
}
print_r($row);
}
}

Categories