I have developed a php web service on a server with mysql database connection. It can not connect to database and does not execute codes after database connection. Also it does not show any error.
If I return something before database connection line, it is returned.
I have tested another php file with database connection and it works properly.
<?php require_once('lib/nusoap.php');
$server = new soap_server();
$server->configureWSDL('ivrmci', 'urn:ivrmciwsdl');
$server->register('upload_file', // method
array('username' => 'xsd:string','password' => 'xsd:string','encoded_filepath' => 'xsd:string','filename' => 'xsd:string'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:ivrmciwsdl', // namespace
'urn:ivrmciwsdl#upload_file', // soapaction
'rpc', // style
'encoded', // use
'Uploads files to the server' // documentation
);
$server->register('inquiryMsisdnCalls', // method
array('username' => 'xsd:string','password' => 'xsd:string','callerid' => 'xsd:string','advertise_id' => 'xsd:string'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:ivrmci', // namespace
'urn:ivrmci#inquiryMsisdnCalls', // soapaction
'rpc',
'encoded', // style // use
'Returns User Log' // documentation
);
function upload_file($username,$password,$encoded,$name) {
if ($username != "abc" OR $password != "123")
{
return "-2";
}
$location = "uploads/".$name; // Mention where to upload the file
//$current = file_get_contents($location); // Get the file content. This will create an empty file if the file does not exist
$current = base64_decode($encoded); // Now decode the content which was sent by the client
file_put_contents($location, $current); // Write the decoded content in the file mentioned at particular location
try
{
$db = new PDO('mysql:dbname=zzz;host=x.x.x.x',"root","1234",array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
return "-3";
}
$filename = explode(".", $name);
$sql = "INSERT INTO advertise (name) VALUES ($filename[0])";
try{
$db->exec($sql);
return $db->lastInsertid();
}
catch(PDOException $e)
{
return $e->getMessage();
}
if($name!="")
{
return "File Uploaded successfully..."; // Output success message
}
else
{
return "Please upload a file...";
}
}
function inquiryMsisdnCalls($username,$password,$callerid,$contentid)
{
if ($username != "abc" OR $password != "123")
{
return "-2";
}
try
{
$db = new PDO('mysql:dbname=zzz;host=x.x.x.x',"root","1234",array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
return "-3";
}
$sql = "select status from user_advertise_log where callerId=$callerid and advertise_id=$contentid";
try{
$log = $db->query($sql)->fetch(PDO::FETCH_OBJ);
return $log->status;
}
catch(PDOException $e)
{
return $e->getMessage();
}
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
Related
I wrote this simple php script, that should return a json.
I can't understand what is wrong here.
if I comment - remove the part of code regarding the connection to mySQL(PDO) I'm able to get the print out as expected otherwise Alamofire and SwiftyJson return me the error
'"JSON could not be serialized because of error:\nThe data couldn’t be read because it isn’t in the correct format."'
<?php
header('Content-Type: application/json');
// if i remove the pdo to connect to mySQL server the everthing work fine
// $host = "127.0.0.1";
// $user = "test";
// $password = "123456789";
// $database = "nx_database";
// try{
// $pdo = new PDO ("mysql:host=$host;dbname=$database", $user, $password);
// $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// print('connesso db -- ');
// }catch(PDOException $e){
// echo "DB Connection Fail" . $e->getMessage();
// die();
// }
$staff = $_POST['staff_ID'];
$array = [
'isLoggedIn'=>$staff
];
$js = json_encode($array);
echo $js;
?>
I attach the code also use to post the request:
func trysimple (){
let parm : [String : Any] = ["staff_ID": "3879"]
AF.request("http://127.0.0.1/nx/public/testRegister.php", method: .post,parameters: parm, headers: nil, interceptor: nil, requestModifier: nil)
.responseString { st in
print(st)
}
.responseJSON { js in
switch js.result {
case .success(let value) :
let json = JSON(value)
debugPrint(json)
case .failure(let err) :
debugPrint(err.localizedDescription)
}
}
}
}
I don't know why do you need a database connection here, but I think I know where is the mistake. You're displaying text that is not json here: print('connesso db -- '); If you expect a json format, you should display everything only in json format. Even on the failed connection possibility.
Here is how I would write it:
<?php
$host = "127.0.0.1";
$user = "test";
$password = "123456789";
$database = "nx_database";
header('Content-Type: application/json');
try{
$pdo = new PDO ("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo json_encode(['error' => "DB Connection Fail" . $e->getMessage()]);
exit;
}
$staff = $_POST['staff_ID'];
$array = [
'isLoggedIn'=>$staff
];
$js = json_encode($array);
echo $js;
?>
kindly update your code like this, for simple printing of json
<?php
header('Content-Type: application/json');
$array = array();
if(isset($_POST['staff_ID']))
{
$staff = $_POST['staff_ID'];
$array = array(
'isLoggedIn' => $staff
);
}
echo json_encode($array);
I have JSON-RPC handler function that handle objects like this:
class Service {
public function sqlite_query($token, $filename, $query) {
if (!$this->valid_token($token)) {
throw new Exception("Access Denied: Invalid Token");
}
$db = new SQLite($filename);
$res = $db->query($query);
if ($res) {
if (preg_match("/^\s*INSERT|UPDATE|DELETE|ALTER|CREATE/i", $query)) {
return $db->rowAffected();
} else {
return $res->fetchAll();
}
} else {
throw new Error("Coudn't open file");
}
}
}
SQLite is a class that call SQLite 2 or 3. The code catch all exceptions but when I try to execute invalid SQL I got not exception but php error handled by this code:
set_error_handler('error_handler');
ini_set('display_errors', 1);
ini_set('track_errors', 1);
ob_start();
function error_handler($err, $message, $file, $line) {
global $stop;
$stop = true;
$content = explode("\n", file_get_contents($file));
header('Content-Type: application/json');
$id = extract_id();
$error = array(
"code" => 100,
"message" => "Server error",
"error" => array(
"name" => "PHPErorr",
"code" => $err,
"message" => $message,
"file" => $file,
"at" => $line,
"line" => $content[$line-1]));
ob_end_clean();
echo response(null, $id, $error);
exit();
}
Is there a way to make SQLite throw exception?
Yes, use PHP's PDO to access SQLite3 (not the SQLite function). PDO is arguably the best and now standard and preferred way to access any database, including SQLite3. You can make PDO throw exceptions by specifying \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION when instantiating a PDO object.
I am developing an SMS Based Registration System and so far I'm at the stage of testing my system. All of a sudden, I was not able to receive any messages from my server when I tried to register via SMS it must receive a confirmation messages. Here's what i did when using PHP nusoap.
Register.php
<?php
// This will allow user to register via SMS.
error_reporting( E_ALL );
// load the nusoap libraries. These are slower than those built in PHP5 but
require_once('nusoap.php');
// create the client and define the URL endpoint
$soapclient = new nusoap_client('http://www.mnccyf.info/soap_book.php?wsdl');
// set the character encoding, utf-8 is the standard.
$soapclient->soap_defencoding = 'UTF-8';
$soapclient->call('sendSMS', array( 'uName' => '48dwi5',
'uPin' => '159597',
'MSISDN' => '09152886810',
'messageString' => 'Registered Successfully',
'Display' => '1',
'udh' => '',
'mwi' => '',
'coding' => '0' ),
"http://ESCPlatform/xsd");
?>
Inquiry.php
<?php
// This will allow user to inquire about the latest news within the organization.
error_reporting( E_ALL );
// load the nusoap libraries. These are slower than those built in PHP5 but
require_once('nusoap.php');
$soapclient = new nusoap_client('http://www.mnccyf.info/soapquery_server.php?wsdl');
// set the character encoding, utf-8 is the standard.
$soapclient->soap_defencoding = 'UTF-8';
// Call the SOAP method, note the definition of the xmlnamespace as the third in the call and how the posted message is added to the message string
$soapclient->call('sendSMS', array( 'uName' => '48dwi5',
'uPin' => '159597',
'MSISDN' => '09152886810',
'messageString' => 'Summer Camp 2013',
'Display' => '1',
'udh' => '',
'mwi' => '',
'coding' => '0' ),
"http://ESCPlatform/xsd");
?>
incoming_sms.php
<?php
require_once('nusoap.php');
function sendSMS($number,$soapclient)
{
$x=sendSMS("09152886810",$soapclient);
}
# Load XML string from input
$xml = simplexml_load_file('php://input');
# Parse the XML for parameters
$sms = array();
$nodes = $xml->xpath('/message/param');
foreach($nodes as $node)
{
$param = (array) $node;
$sms[$param['name']] = $param['value'];
}
if($sms['messageType'] == 'SMS-NOTIFICATION') {
sendSMS();
list($action, $messagetype, $source, $type) =explode (" ",$soapclient);
}elseif($sms['messageType'] == 'SMS') {
sendSMS();
list($action, $name, $age, $localchurch, $district) = explode(" ",$soapclient);
}elseif($sms['messageType'] == 'SMS') {
sendSMS();
list($action, $event,$location,$time) = explode(" ", $soapclient);
}
else {
echo "Unsupported Message Type";
}
?>
register_soapserver.php
<?php
//call library
require_once ('nusoap.php');
//using soap_server to create server object
$server = new nusoap_server;
$server ->configureWSDL('http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform?
wsdl','urn:http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform?wsdl');
//register a function that works on server
$server->register('reg');
// create the function
function reg()
{
$connect = mysql_connect("localhost","root","jya0312#");
if (!$connect)
{
die("Couldnt connect" . mysql_error());
}
mysql_select_db("cyfdb", $connect);
$sql = "INSERT INTO mydb(name, age,localchurch,district) VALUES ('{$_POST [name]}','{$_POST[age]}','{$_POST[localchurch]}','{$_POST[district]}')";
mysql_close($connect);
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
soapquery_server.php
<?php
//call libraryrequire_once ('nusoap.php');
//using soap_server to create server object
$server = new nusoap_server;
$server ->configureWSDL('http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform? wsdl','urn:http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform? wsdl');
//register a function that works on server
$server->register('getquery');
// create the function
function getquery()
{
$link=mysql_connect("localhost", "root", "jya0312#") or die("Cannot connect to DB!");
mysql_select_db("cyfdb") or die("Cannot select DB!");
$sql = "SELECT event,location,time from activity";
while($r = mysql_fetch_array($sql)){
$items[] = array('event'=>$r['event'],
'location'=>$r['location'],
'date'=>$r['date']);
}
return $items;
$mysql_close($link);
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
How to apply word wrap using zend_pdf library, I am using MyPDFTable lib as an extension for zendPdf lib.
I have used following code.
<?php
// include auto-loader class
require_once 'Zend/Loader/Autoloader.php';
// register auto-loader
$loader = Zend_Loader_Autoloader::getInstance();
try {
// set up database access parameters
$params = array ('host' => '127.0.0.1',
'username' => 'user',
'password' => 'pass',
'dbname' => 'world');
// configure adapter and query database
$db = Zend_Db::factory('PDO_MYSQL', $params);
$stmt = $db->query('SELECT Name, Code, Region FROM country LIMIT 0, 150');
// create PDF
$pdf = new My_Pdf_Document('example.pdf', '.');
// create page
$page = $pdf->createPage();
// define font resource
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
// set font
$page->setFont($font, 24);
// create table
$table = new My_Pdf_Table(3);
// iterate over record set
// set up table content
while ($record = $stmt->fetch()) {
$row = new My_Pdf_Table_Row();
$cols = array();
foreach ($record as $k => $v) {
$col = new My_Pdf_Table_Column();
$col->setText($v);
$cols[] = $col;
}
$row->setColumns($cols);
$row->setFont($font, 14);
$row->setBorder(My_Pdf::TOP, new Zend_Pdf_Style());
$row->setBorder(My_Pdf::BOTTOM, new Zend_Pdf_Style());
$row->setBorder(My_Pdf::LEFT, new Zend_Pdf_Style());
$row->setCellPaddings(array(10,10,10,10));
$table->addRow($row);
}
// add table to page
$page->addTable($table, 0, 0);
// add page to document
$pdf->addPage($page);
// save as file
$pdf->save();
echo 'SUCCESS: Document saved!';
} catch (Zend_Pdf_Exception $e) {
die ('PDF error: ' . $e->getMessage());
} catch (Exception $e) {
die ('Application error: ' . $e->getMessage());
}
?>
You will find this code on http://devzone.zend.com/1776/creating-pdf-documents-with-zend-framework/ In topic "Turning The Tables".
This tutorial talks about the same problem you faced. They have provided a custom solution also!
http://www.ibm.com/developerworks/opensource/tutorials/os-php-zend5/section4.html
My SOAP application written in NuSOAP returns an http 500 (Internal Server Error) error.
It is working fine on my local machine, I only get this error in live.
How do I diagnose this error?
Server:
require_once('nusoap.php');
// Create the server instance.
$server = new soap_server;
// Register the method to expose.
// Note: with NuSOAP 0.6.3, only method name is used without WSDL.
$server->register(
'hello', // Method name
array('name' => 'xsd:string'), // Input parameters
array('return' => 'xsd:string'), // Output parameters
'uri:helloworld', // Namespace
'uri:helloworld/hello', // SOAPAction
'rpc', // Style
'encoded' // Use
);
// Define the method as a PHP function.
function hello($name) {
require_once 'classes.php';
$db = new Database();
$sql = "select * from notifications where skey = '$name'";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
//return 'Hello, ' . $row['sales'];
$ret = "<salesdat>
<customername>". $row['sales']. "</customername>
</salesdat>";
return $ret;
}
// Use the request to (try to) invoke the service.
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
Client:
// Pull in the NuSOAP code.
require_once('nusoap.php');
// Create the client instance.
$client = new soapclient('http://----my site url ---/server.php');
//$client = new soapclient('http://localhost/cb/server.php');
// Check for an error.
$err = $client->getError();
if ($err) {
// Display the error.
echo '<p><b>Constructor error: ' . $err . '</b></p>';
// At this point, you know the call that follows will fail.
}
// Call the SOAP method.
$result = $client->call(
'hello', // method name
array('name' => 'shahidkari'), // input parameters
'uri:helloworld', // namespace
'uri:helloworld/hello' // SOAPAction
);
// Strange: the following works just as well!
//$result = $client->call('hello', array('name' => 'Scott'));
// Check for a fault
if ($client->fault) {
echo '<p><b>Fault: ';
print_r($result);
echo '</b></p>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error.
echo '<p><b>Error: ' . $err . '</b></p>';
} else {
// Display the result.
print_r($result);
}
}
This may due to the php error in your server script. Switch on the error reporting. Run the server in a browser.
server.php
error_reporting(-1);
ini_set('display_errors', 'On');
require_once './src/Test.php';
$server = new SoapServer("https://xxxx/Outbound.wsdl");
$server->setClass('Test');
$server->handle();
https://xxxx/server.php // calling this in a browser will throw the error.
In my case it was due to require_once './src/Test.php'; which was not including the class.