php web service with json - php

I am new to PHP & JSON, and based on a tutorial I made a simple web service which returns the contents of a table of a mysql db.
The output is in JSON and the database caracter set is UTF-8. my problem is that when I try to run this it throws me a 404 error, and doesn't show me where the error is. Any idea what might be wrong?
The PHP file is the following:
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
$link = mysql_connect($mysql_host,$mysql_user,$mysql_password) or die("cannot connect to the DB");
mysql_select_db($mysql_database,$link);
$query = "select...";
$result=mysql_query($query) or die (mysql_error("error "));
$num=mysql_numrows($result);
$rows=array();
while($r=mysql_fetch_assoc($result)){
$rows[]=$r;
}
echo json_encode($rows);
?>
Any Idea? Thanks in advance

Add following line before json_encode()
header('Content-type: application/json');
That should solve your problem.

In this , I have written my php web service code.
follow this.
hope it will help you.
link :
http://stackoverflow.com/questions/12702128/json-parsing-in-iosphp

Are you sure you want use JSON? You can also use SOAP-NuSOAP and WSDL for creating a web service. See, for example,
Create a PHP Web Service in 5 Minutes Using PHP SOAP and WSDL Technology and NuSOAP.

Related

Is there any PHP configuration for passing JSON object to android?

I am trying to send JSON object from PHP web service to my android app. Initially for checking if my PHP file returns the JSON value, I typed the url in browser and got correct value as desired. To check my android code, I executed the code using correct host url but got only '[]' as output in logcat. For debugging purpose, I created a free web hosting and database in hosthinger.com. This time the exact same php and android code worked fine, giving me the desired output. List of things we did to ensure there is no mistake:
Checked the collation of database in both hostings (utf8_unicode_ci)
Both the hosting returned correct value in browser.
Is there any specific PHP configuration for JSON objects?. Or am I missing any header information? I'm not getting a clue why code is working perfectly in one hosting and not in the other.
Here is my PHP code:
<?php
include ('mysqlconnection.php');
$mobile = $_POST['mobile_number'];
$output = array();
$query="select name,status from content;";
$sql = mysql_query($query);
while($row = mysql_fetch_assoc($sql)) {
$output[]= array( 'imagename' => $row['name'], 'status' => $row['status'] );
}
echo json_encode($output);
?>
May be you need to specify content.type in your php:
header('Content-Type: application/json');
You should use an output buffer with a application/json header, instead of just echoing the json_encode() output.
Some servers tend to give errors when you're working with MySQL, check the configurations. And do not use mysql_* functions, use PDO or at least mysqli instead.
You should check for possible errors in your code, check your connection, query results etc.,THEN you can generate a JSON to give output.
Make sure your server's error_reporting is set to 0. Sometimes servers print out warnings, notices and error messages that messes up your output.
You can use Google Chrome's PostMan Extension to view the results of your web service. It also shows output as json parsed.

Unable to connect to Mongodb which is on windows server from ubuntu using php

I wanted to connect to the MongoDB which is installed in windows server from ubuntu using php.
I am trying to connect using the following code but output is nothing even mongoexception is not throwing any error.
$mngo = new Mongo("mongodb://192.168.1.119:27017");
$db = $mngo->selectDB('travelmanagement_qa');
Can anyone please tell me why i am not able to connect?
Thank You in advance
A few comments:
Please use new MongoClient instead of new Mongo.
This should not output anything at all. You're just selecting a database and assigning it to a variable. Is that your whole code snippet?
What did you expect the output to be?
To figure out what is actually happening under the hood with connections you can use MongoLog. With this functionality you can track down what the driver is doing internally. You'd use it like:
MongoLog::setLevel(MongoLog::ALL);
MongoLog::setModule(MongoLog::RS);
MongoLog::setCallback( 'printMsgs' );
function printMsgs($a, $b, $msg)
{
echo $msg, "\n";
}

Connect android app to an External MySQL database using PHP

I have created a login_activity for my android app. I've gone through quite a few tutorials on how to fetch data from an external MySQL database. I have access to this external MySQL database. I've followed one of them to write the following PHP code which will fetch my data from the server for my login_Activity:
<?php
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
$dbhost="localhost";
$dbuser="";
$dbpass=""
$connect=mysql_connect($dbhost,$dbsuer,$dbpass) or die("database selection error");
$username=$_POST['username'];
$password=$_POST['password'];
$query=mysql_query("SELECT * FROM app_users_parent where Email='$username' AND Password='$password');
$num=mysql_num_rows($query);
if($num==1) {
while($list=mysql_fetch_assoc($query)) {
$output=$list;
echo json_encode('$output');
}
mysql_close();
}
?>
I understand I've got to place this php file onto the same server. But I don't really understand how to do that? Should I use something like FileZilla for FTP or what?
I could not find any tutorial on the net which shows how and where to save this php file.
If you need my Java code where I'm connecting to this file,I could give it to you.
(P.S.- I just started with android so not really a pro out here. Please respect that )
How to connect Android with PHP, MySQL tutorial definitely help you. Good luck.
Yes, you have to upload your .php file onto your server (wich contain the MySQL database).
Then, in you android class, create an asynctask class. That aynsctask class have to request your phpfile an get the json.

samba web client - setup connection in php script

I have to establish connection with Samba server from my php script in order to download some files into my local server.
Actually its first time I have heard of something like Samba so I Tried to look for a opensource code that I could make use of.
Here it is what I have found: First class - smbclient.php and I tried code posted on the page:
<?php
require_once ('smbclient.php');
$smbc = new smbclient ('//10.0.1.1/example', 'exampleuser', 'examplepassword');
if (!$smbc->get ('path/to/desired/file.txt', '/tmp/localfile.txt'))
{
print "Failed to retrieve file:\n";
print join ("\n", $smbc->get_last_stdout());
}
else
{
print "Transferred file successfully.";
}
?>
Adjusting it into my needs ( server, user, password), all i got is
Failed to retrieve file:
Fatal error: Call to undefined method smbclient::get_last_stdout()
Then I found out about smbwebclient.php project which looks awesome and can be found here.
And this class looks good but the problem is that I have no idea how to use it. Can anyone post it example connection or link to tutorial?
To get files from a samba server, you can try to use a smb wrapper, like the one here but changing the deprecated splits with explodes. Then you can include your php file using this code:
include_once('smb.php');
include( 'smb://user:password#server/folder/file.php');
Reviving old thread but I think I found the solution, the code must have changed since the pot was made on the blog:
print join ("\n", $smbc->get_last_stdout());
should now be
print join ("\n", $smbc->get_last_cmd_stdout());

XML received from response is out of format

Hi im currently using PHP on a linux server to receive response from a WebService hosted on a Windows server.
I am using the following PHP to read the response :-
while (!feof($socket)) {
$result .= fgets($socket, 4096);
}
fclose($socket);
if ($debug) echo '<pre>',$result,'</pre>';
Apparently when i received the the response it is out of format, with break lines between tags such as the following :-
/9j/4AAQSkZJRgABAQEAYABgAAD/4QBaRXhpZgAATU0AKgAAAAgABQMBAAUAAAABAAAASgMDAAEAAAABAAAAAFEQAAEAAAABAQAAAFERAAQAAAABAAAAAFESAAQAAAABAAAAAAAAAAA
AAYagAACxj
insetead of like these :-
</ResponseHdr><ResGetCustAreaSnapshot><cmc:GetCustAreaSnapshot xmlns:cmc="http://tnb.com.my/CGIS/D/cmc_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xMpJ+XkB5IuPUg44JGn/AMIJ4P8A+hU0P/wXQ/8AxNW7j/kbdO/68br/ANGW9ata1Phh6fqyI7y9f0Rz/wDwgng//oVND/8ABdD/APE1YsfCfhvTLyO8sPD+lWl1HnZNBZRxuuQQcMACMgkfjWxRWRZnQf8AIy33/Xnb/wDoc1aNZ0H/ACMt9/152/8A6HNWjQAUUUUAFZXhf/kUtG/68YP/AEWtatZXhf8A5FLRv+vGD/0Wtar+FL1X5Mh/GvR/oatFFFZFmdB/yMt9/wBedv8A+hzVo1nQf8jLff8AXnb/APoc1aNABRRRQBU1S9/s3Sb2/wDL8z7NA82zdjdtUnGe3SjS7L+zdJsrDzPM+zQJDv243bVAzjtnFVfFH/Ipaz/14z/+i2rVrV6Ul5t/glb82R9v5f1+QUUUVkWFccdVlW0uLC2LRFbq4M85VvkVrhwAAPmJJ4G35mPypzuaO/q2tlbcGLi3l4iZHIkuOQPkwCVQllG8ZY5ARSzoTzls832WFFHlYRX+0YAAVh5fmKqMTvfBRduOMRwfLmUduGwzmueW35nPWrcvurcybrRli1vR2sY8RWurJcXKZB8oyPDH1X50fe8
apparently even from here i cannot display the tags without using the code block which formats it properly.
would really appreciate it if someone could point me in the right direction on what to look for to fix this problem.
Thank You.
'ow do you look at your debug output: inside a browser or inside a terminal ? Could it be that you simply have the xml like tags ("<...>") in the reply swallowed by visualizing it as html in a browser ?
If that is not the case then I would check the content of the reply on a lower level. Use 'tcpdump' or 'wireshark' to dump the actual content without having to rely on a higher level output.
Try var_dump(htmlspecialchars($result)) instead of echo.

Categories