Web service not response result in client - php

i try test web service with nusoap and php. And here is my code:
Server.php:
require_once ("lib/nusoap.php");
$URL= 'http://myexample/service.php';
$namespace = $URL.'?wsdl';
$server = new soap_server();
$server->configureWSDL("topUsers",$namespace);
$server->register("getTopUser");
$server->soap_defencoding = 'UTF-8';
$server->decode_utf8 = false;
$server->encode_utf8 = true;
function getTopUser(){
$conn = mysql_connect('localhost','root','test#123') or die(mysql_error());
mysql_select_db('test',$conn)or die(mysql_error());
mysql_query("SET charactor_set_results=utf8",$conn);
mysql_query("SET NAMES 'utf8'");
$query = mysql_query("SELECT * FROM player ORDER BY money DESC LIMIT 0,10",$conn) or die (mysql_error());
while($row = mysql_fetch_array($query)){
$data[] = array(
'userid'=>$row['userid'],
'username'=>$row['nick'],
'money'=>$row['money']
);
}
return $data;
}
if(!isset ( $HTTP_RAW_POST_DATA ))$HTTP_RAW_POST_DATA = file_get_contents ('php://input');
$server -> service ( $HTTP_RAW_POST_DATA );
Client.php:
require_once("lib/nusoap.php");
$url = 'http://myexample/service.php?wsdl';
$client = new nusoap_client($url);
$reponse = $client->call('getTopUser',array());
$client->soap_defencoding = 'UTF-8';
$client->decode_utf8 = false;
//$client->decode_utf8 = false;
$err = $client->getError();
echo $err;
echo $reponse;
echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
And here is result of my code:
2015-08-27 03:14:09.228293 nusoap_parser: parsed successfully, found root struct: 2 of name getTopUserResponse
2015-08-27 03:14:09.228530 nusoap_client: sent message successfully and got a(n) string
return=string(0) ""
I don't know i wrong somewhere? Somebody help me, please. Thanks!

Related

How to get print on browser console using PHP

I am testing out my php code and want to make see the files that I am getting from json and check how it is displaying so I know how to send the code to mysql
php file
<?php
$json = json_decode(file_get_contents("php://input"));
$obj = json_decode($json,true);
print_r($json);
print_r($obj);
function debug_to_console( $data ) {
$output = $data;
if ( is_array( $output ) )
$output = implode( ',', $output);
echo "<script>console.log( 'Debug Objects: " . $output . "' );</script>";
}
debug_to_console( "Test" );
debug_to_console($obj);
print_r("hello");
echo "<script>console.log('" . json_encode($json) . "');</script>";
echo "<script>console.log('" . $obj . "');</script>";
echo "<script>console.log('" . '$obj' . "');</script>";
var_dump('Hello');
var_dump($obj);
var_dump($json);
header("Content-Type: application/json; charset=UTF-8")
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
None of this prints to the console
Want code to print to the console
You can try the following function
function consoleLogs($data) {
$html = "";
$coll;
if (is_array($data) || is_object($data)) {
$coll = json_encode($data);
} else {
$coll = $data;
}
$html = "<script>console.log('PHP: ".$coll."');</script>";
echo($html);
}
You can use this as :-
consoleLogs(array("test1", "test2"));

Get json output from php and mySql query using wordpress

I'm trying to create a php page that should shows me a json output.. I'm in a wordpress website and maybe it's a little bit different to retrive datas from database than in a normal php page. By the way, this is my code:
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
global $wpdb;
$code = '';
$code=$_REQUEST['code'];
$timestamp = '';
$timestamp=$_REQUEST['timestamp'];
$username = '';
$username=$_REQUEST['username'];
$selectData = "SELECT * FROM protocol_data_list WHERE username = '$current_user->user_login'";
//Create an array
$json_response = array();
$result = $wpdb->query($selectData);
echo $result;
while ($row=mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo $row;
$row_array['code'] = $row['code'];
$row_array['timestamp'] = $row['timestamp'];
$row_array['username'] = $row['username'];
array_push($json_response,$row_array);
}
$json_response = str_replace('\\/', '/', json_encode(array('item' => $json_response), 128));
echo $json_response;
?>
this kind of code is the one i use always to create a json.. But in wordpress it returns an empty array.. I don't know if something's wrong.

Ajax XML Error When Using PHP PDO

I recently switched my code for accessing my database to a PHP PDO Object.
I have everything working accept for my ajax page. As far as I have been able to tell all the queries and data are being pulled out properly, however I get the following error when I try using PDO this was working before with a mysql_connect object.
I did find that if I comment out these lines it will run but then it is unable to run the query which causes more errors obviously.
//ini_set('include_path', 'C:\www\capc\libraries');
//include '/php/capc.php';
//include '/php/bio.php';
Error Message:
This page contains the following errors:
error on line 4 at column 6: XML declaration allowed only at the start of the document
Below is a rendering of the page up to the first error.
CAPC Class query function
public function query($sql) {
try {
$handler = new PDO('mysql:host=' . $this->dbhost . ';dbname=capc', $this->dbuser, $this->dbpass);
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
}
$query = $handler->prepare($sql);
$query->execute();
return $query;
}
Ajax.php
<?php
ini_set('include_path', 'C:\www\capc\libraries');
include '/php/capc.php';
include '/php/bio.php';
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
$bio_first = $_GET['First_Name'];
$bio_last = $_GET['Last_Name'];
if (!empty($bio_first) && !empty($bio_last)) {
$capc = new CAPC;
$sql = 'SELECT Bio_ID FROM `bio_users` WHERE Bio_First = "' . $bio_first . '" AND Bio_Last = "' . $bio_last . '";';
$query = $capc->query($sql);
$num_results = $query->rowCount();
}
echo '<bio>';
if ($num_results > 0) {
$bio_first = $capc->sanitize($bio_first, "string");
$bio_last = $capc->sanitize($bio_last, "string");
$bio = new Bio($bio_first, $bio_last);
echo '<bio_exists>';
echo 'True';
echo '</bio_exists>';
echo '<bio_fname>';
echo $bio->Bio_First;
echo '</bio_fname>';
echo '<bio_lname>';
echo $bio->Bio_Last;
echo '</bio_lname>';
echo '<bio_img>';
echo $bio->Bio_Img;
echo '</bio_img>';
} else {
echo '<bio_exists>';
echo 'False';
echo '</bio_exists>';
}
echo '</bio>';
?>
Finally got it working by moving the include for bio.php not sure why this works now and wouldn't before.
Working Ajax.php
<?php
ini_set('include_path', 'C:\www\capc\libraries');
include '/php/capc.php';
$bio_first = $_GET['First_Name'];
$bio_last = $_GET['Last_Name'];
if (!empty($bio_first) && !empty($bio_last)) {
$capc = new CAPC;
$sql = 'SELECT Bio_ID FROM `bio_users` WHERE Bio_First = "' . $bio_first . '" AND Bio_Last = "' . $bio_last . '";';
$query = $capc->query($sql);
$num_results = $capc->query($sql)->rowCount();
}
if ($num_results > 0) {
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<bio>';
$bio_first = $capc->sanitize($bio_first, "string");
$bio_last = $capc->sanitize($bio_last, "string");
include '/php/bio.php';
$bio = new Bio($bio_first, $bio_last);
echo '<bio_exists>';
echo 'True';
echo '</bio_exists>';
echo '<bio_fname>';
echo $bio->Bio_First;
echo '</bio_fname>';
echo '<bio_lname>';
echo $bio->Bio_Last;
echo '</bio_lname>';
echo '<bio_img>';
echo $bio->Bio_Img;
echo '</bio_img>';
} else {
echo '<bio_exists>';
echo 'False';
echo '</bio_exists>';
}
echo '</bio>';
?>

This is causing my page to load very slow or not at all?

I just updated from php 5.3.4 to 5.3.8. After the update it seems that all my code that includes try{ causes my page to hang and use up all my server memory.
if(preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip)){
$xml = #file_get_contents('http://' . $this->service . '/' . $this->version . '/' . $name . '/?key=' . $this->apiKey . '&ip=' . $ip . '&format=xml');
try{
$response = #new SimpleXMLElement($xml);
foreach($response as $field=>$value){
$result[(string)$field] = (string)$value; }
return $result;
}
catch(Exception $e){ $this->errors[] = $e->getMessage();
return;
}
}
This also causes a major issues
<?php
try{
$gt = new Gtranslate;
$gt->setRequestType('curl');
$SQL = "SELECT * FROM PAGE_CONTENT WHERE live_page = '1'";
$result = mysql_query( $SQL );
while( $row = mysql_fetch_array( $result ) ) {
$page_id_sub = $row["page_id"];
$page_title = $row["page_title"];
$page_permalink = $row["page_permalink"];
if(empty($mylang)){
echo "<a href='/$permalink/$page_permalink.html'>$page_title</a> |";
}
else {
$page_trans = $gt->$mylang("$page_title");
echo "<a href='/$permalink/$page_permalink.html'>$page_trans</a> |";
}
}
}
catch (GTranslateException $ge){
echo $ge->getMessage();
}
?>
This probably has very little to do with try and much more to do with your remote requests (i.e. file_get_contents() and $gt->$mylang()).
As a benchmark, remove those lines and see how your page performs. If they are indeed the culprit, you may want to consider caching their response or some other approach so your not making the request on every page load.

How can I create a json object in php

I am working in android and php.
I want to return a json object to android program from php program.
If these is a entry in a database then it is working properly. But when there is no record in database then it goes wrong.
I would welcome suggestions
I want to make json object like this ([{"id":"5"}])
This is my php program:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
//what should i right here to make jsonobject like this:- ([{"id":"5"}])
echo myjsono;
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
?>
How about something like this: (replace with your own variables)
if (empty($row)){
$arr = array('success' => 'false');
} else {
$arr = array('success' => 'true');
}
echo json_encode($arr);
If you want your android app to receive an object with a special id in the case of a not found condition I would return this:
{"id":"0"}
Then in your android app check if the id == 0 and that will tell you no records were found.
This is very correct solution for my question:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
// {"messages":{"message":[{"id": "17","user": "Ryan Smith","text": "This is an example of JSON","time": "04:41"}]};}
**echo '('.'['.json_encode(array('id' => 0)).']'.')';** //**note this**
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
//mysql_close($con);
//echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>

Categories