hi i have a php web that return json data usin json!encode but when i change it from GET to POST it return null
<?php
header('Content-Type: application/json; charset=utf-8');
include('settings.php');
mysql_connect($host,$user,$password);
mysql_select_db($base);
mysql_query('SET CHARACTER SET utf8');
$login = $_GET['login'];
$password = $_GET['password'];
$req = "select * from user WHERE username = '".$login."' and password = '".$password."'";
$sql=mysql_query($req);
$nn=mysql_num_rows($sql);
$items = array("items" => NULL);
while ($data=mysql_fetch_array($sql))
{
$items["items"][] = array(
"id" => $data['id'],
"username" => $data['username'],
"password" => $data['password'],
"nom_prenom" => $data['nom_prenom'],
"nom_prenom_arabe" => $data['nom_prenom_arabe'],
"specialite" => $data['specialite'],
"specialite_arabe" => $data['specialite_arabe'],
"adresse" => $data['adresse'],
"adresse_arabe" => $data['adresse_arabe'],
"telephone_cabinet" => $data['telephone_cabinet'],
"gsm" => $data['gsm'],
);
}
echo json_encode($items,JSON_UNESCAPED_UNICODE);
?>
it returns
{"items":[{"id":"2","username":"**","password":"*","nom_prenom":"****","nom_prenom_arabe":"مهذب عبد الصمد ","specialite":"Pediatrie","specialite_arabe":"إختصاصي في الامراض النفسية و العصبية","adresse":"Av tahar sfar imm .El BARAKA sousse 4000","adresse_arabe":" 4000 شارع طاهر سفر عمارة البركة سوسة","telephone_cabinet":"73698521","gsm":"25631478"}]}
but with
$login = $_POST['login'];
$password = $_POST['password'];
it return
{"items":null}
can anyone explain to me why :) thanks
Because the post that invoke this page has a GET method , so remplace it with POST then it will work as expected.
another point is it's discouraged to use string concatenation when quering databases due to security risk. use prepared statements instead.
First of: For the love of.. Clear text password and no request validation?
Please before you do anything at all, read up about sql injections and why clear text is BAD, really really bad.
Now to you question.
The $_GET arrays contains query parameters ex (?test=test) on GET METHOD calls to the server. GET is the basic HTTP call and tells the server you want to read a page.
IN OLD TIME :
The $_POST array contains post parameters on POST METHOD calls. POST is used when you want to update or add information on the server. This is usually called from a html form.
W3School have a guide on HTTP Method calls here.
BUT NOW WITH AJAX AND THE NEW FEATURES OF HTML5 :
YOU CAN USE THE 'POST' TO GET DATA.
THE PROBLEM HERE IS THE SECURITY OF THE NAVIGATORS LIKE FIREFOX AND CHROME;
THE SOLUTION :
Modify the cors http : in the server PHP add this in first of your page php:
//Part added by ilyas :
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
//End of part.
Related
I'm getting below error while creating a sample php webservice using nusoap.
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.
On checking the network tab, I can see that XML output is generated on the 4th line. Cannot figure out why. There is no space before of after tags as I saw as potential reasons online.
<?php
require_once('lib/nusoap.php');
require_once('dbconn.php');
$server = new nusoap_server();
/* Fetch one set data */
function fetchSSData($SS_id){
global $dbconn;
$sql = "SELECT SS_id, SS_name FROM SS_soap where SS_id = :SS_id";
// prepare sql and bind parameters
$stmt = $dbconn->prepare($sql);
$stmt->bindParam(':SS_id', $SS_id);
// insert a row
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
return json_encode($data);
$dbconn = null;
}
$server->configureWSDL('SSsoapServer', 'urn:SSsoap');
$server->register('fetchSSData',
array('SS_id' => 'xsd:string'), //parameter
array('data' => 'xsd:string'), //output
'urn:SSsoap', //namespace
'urn:SSsoap#fetchSSData' //soapaction
);
$server->service(file_get_contents("php://input"));
After hours of searching found the answer. Adding ob_clean() in the beginning of php file clears the output buffer. This solved the problem for me.
When I run this piece of code in an individual php file it works fine.
$ip = '*****';
$account_id = '*****';
$account_email = '*****';
//INITIALIZE MAXMIND
include_once 'src/maxmind/minfraud.phar';
use MaxMind\MinFraud;
//FORM THE MAXMIND REQUEST
$mf = new MinFraud(1234567, 'abcdefghijk');
$score_request = $mf->withDevice([
'ip_address' => $ip,
])->withEvent([
'type' => 'survey',
])->withAccount([
'user_id' => $account_id,
])->withEmail([
'address' => $account_email,
]);
//To get the minFraud Score response model, use ->score():
$score_response = $score_request->score();
//And then you'd grab $scoreResponse->ip_address->risk for the IP risk (if you're just passing the IP address), or $scoreResponse->riskScore if you are passing additional fields.
$risk_score = $score_response->riskScore;
echo $risk_score;
But if I place it in a larger segment of code I get 500 error?
I often find this when I am using libraries that this annoying problem happens and I can't see any logical reason why this is happening?
I am creating a 3D Secure PHP Project. I am having a rather bizzare issue in that the "MD" code is going missing when re-submitting the Array of data
My code is as follows :
$paRes = $_REQUEST['PaRes'];
$md = $_REQUEST['MD'];
require "payment_method_3d.php";
x_load('cart','crypt','order','payment','tests');
/*
* For Debugging Purposes
* Only.
echo "The Value Of PaRes is : ";
echo $paRes;
*/
$soapClient = new SoapClient("https://www.secpay.com/java-bin/services/SECCardService?wsdl");
$params = array (
'mid' => '',
'vpn_pswd' => '',
'trans_id' => 'TRAN0095', // Transaction ID MUST match what was sent in payment_cc_new file
'md' => $md,
'paRes' => $paRes,
'options' => ''
);
It seems that the $_REQUEST['MD'] string seems to go missing AFTER the soap call. Although I am having difficulty print this out to the screen. The strange thing is the $paRes variable works without issue.
Any ideas why this would be the case?
Check your case. PHP array keys are case sensitive. From this little bit of code it looks as if the request variable may be 'md' instead of 'MD'.
Try $md = $_REQUEST['md'];
PHP array statements are case sensitive, so this should work:....
$md = $_REQUEST['md'];
Thanks for your responses guys.
What was happening was the include page was sitting in front of the request methods and causing issues loading the REQUEST methods to the page.
I am using PHP5 and Codeigniter to connect to a .NET web service through SOAP requests. I'm having trouble making an update to that dataset. This is my first experience working with Codeigniter (although doesn't factor here much), SOAP, PHP SimpleXML class, and .NET web services in general. For example, this is to update a user profile. I don't have any problems getting responses but I'm unsure how to update this based on the user's edits to the profile.
My string from the dumping request is this (Note: I'm concerned with the 0, which is the start of the dataset. The 1111 is username and the next 1111 is a password)
11111111 0RandyFloydGM1955-11-05T00:00:00-04:00317787129131789770001910 E. Markwood AvenueIndianapolisIN46227falsefalse
This gives me a 400 Bad Request error. It seems obvious that is due to the space between the 0 and the last 1. By doing htmlspecialchars() I see that it looks like it is the xml declaration isn't needed.
<?xml version="1.0"?> <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml- msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"><dsEmployee xmlns="http://SHSSrv/dsEmployee.xsd"><Employee diffgr:id="Employee1" msdata:rowOrder="0"><EmplId>0</EmplId><FirstName>Randy</FirstName><LastName>Floyd</LastName><MI>G</MI><Sex>M</Sex><DOB>1955-11-05T00:00:00-04:00</DOB><HomePhoneArea>317</HomePhoneArea><HomePhone>7871291</HomePhone><WorkPhoneArea>317</WorkPhoneArea><WorkPhone>8977000</WorkPhone><Address1>1920 E. Markwood Avenue</Address1><Address2/><City>Indianapolis</City><St>IN</St><ZIP>46227</ZIP><ReceiveNewsLetter>false</ReceiveNewsLetter><PagerArea/><PagerNo/><EmailAddress>randy#test.com</EmailAddress><SpanishContact>false</SpanishContact></Employee></dsEmployee></diffgr:diffgram>
Taking the original response and just sending it back as update works like this.
111111110RandyFloydGM1955-11-05T00:00:00-04:00317787129131789770001910 E. Markwood AvenueIndianapolisIN46227falsefalse
And with htmlspecialchars() looks like this (No XML declaration):
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml- msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"><dsEmployee xmlns="http://SHSSrv/dsEmployee.xsd"><Employee diffgr:id="Employee1" msdata:rowOrder="0"><EmplId>0</EmplId><FirstName>Randy</FirstName><LastName>Floyd</LastName><MI>G</MI><Sex>M</Sex><DOB>1955-11-05T00:00:00-04:00</DOB><HomePhoneArea>317</HomePhoneArea><HomePhone>7871291</HomePhone><WorkPhoneArea>317</WorkPhoneArea><WorkPhone>8977000</WorkPhone><Address1>1920 E. Markwood Avenue</Address1><Address2/><City>Indianapolis</City><St>IN</St><ZIP>46227</ZIP><ReceiveNewsLetter>false</ReceiveNewsLetter><PagerArea/><PagerNo/><EmailAddress>randy#test.com</EmailAddress><SpanishContact>false</SpanishContact></Employee></dsEmployee></diffgr:diffgram>
Here is the code:
function employee_update_request()
{
ini_set( 'soap.wsdl_cache_ttl' , 0 );
//Get XML from the Employee Profile Request
$response = $this->employee_profile_request();
//Turn the string into an object to manipulate
$dataset = simplexml_load_string($response->any);
//Manipulate some data from the update form
$dataset->dsEmployee->Employee->EmailAddress = "randy#test.com";
$dataset->dsEmployee->Employee->Address1 = "1920 E. Markwood Avenue";
$any = $dataset->saveXML();
//Add back the string to the original response object returned from web service
$response->any = $any;
//Get username and password for the params
$username = $this->session->userdata('username');
$password = $this->session->userdata('password');
$params = array('sUserId' => $username, 'sPassword' => $password, 'dsEmployee' => $response);
//SOAP Options
$options = array(
'soap_version'=>SOAP_1_1,
'exceptions'=> 0,
'trace'=> 1,
'uri' => "http://www.w3.org/2003/05/soap-envelope"
);
//New soap client with options
$client = new SoapClient('http://localhost/SHSSRV/SHSSrv.asmx?WSDL', $options);
//Request the employee profile fromt the webservice, passing in credentials
$update_request = $client->EmployeeUpdateRequest($params);
$update_response = $update_request->EmployeeUpdateRequestResult;
return $update_response;
}
I really need help, I need to figure out how best to make updates to this data. Am I able to get the declaration stripped out somehow, or should I request that the .NET web service be changed in some way? I don't have access directly to that but I can talk to the developer if there is a better way all together.
Thanks!
I've solved this by doing this. I'd love to know if there is a better way though.
$no_xml_doctype = str_replace('<?xml version="1.0"?>' , '' , $any);
$trimmed = trim($no_xml_doctype);
$response->any = $trimmed;
//Get username and password for the params
$username = rtrim($this->session->userdata('username'));
$password = rtrim($this->session->userdata('password'));
$params = array('sUserId' => $username, 'sPassword' => $password, 'dsEmployee' => $response);
I'm trying to get a check_authentication response working, but so far, all consumers reject it and say that my server denied check_authentication.
This is the GET and POST data that my server file receives:
$_GET:
Array
(
[mode] => profile
[username] => hachque
[domain] => roket-enterprises.com
)
$_POST:
Array
(
[openid_assoc_handle] => {HMAC-SHA1}{4b00d7b2}{vo1FEQ==}
[openid_identity] => http://www.roket-enterprises.com/openaccount/openid:hachque
[openid_mode] => check_authentication
[openid_response_nonce] => 2009-11-16T04:40:18Zrrz8R4
[openid_return_to] => http://openiddirectory.com:80/openidauth/id/c/finish_auth.php?nonce=adCevd6T
[openid_sig] => SgFE5iT9IGd5EftkrZ72mgCHiLk=
[openid_signed] => assoc_handle,identity,mode,response_nonce,return_to,signed,sreg.email,sreg.fullname,sreg.nickname
[openid_sreg_email] => jrhodes#roket-enterprises.com
[openid_sreg_fullname] => James Rhodes
[openid_sreg_nickname] => jrhodes
)
This is the header reponse that I am outputting (contains POST data as it was explained to me on IRC that sending the key-values as headers shouldn't be done to the consumer server EDIT: Come to think of it, it doesn't make much sense RESPONDING with POST data. Maybe some here can explain the whole process of check_authentication clearly).
Content-Type: text/plain;
Content-Length: 675;
openid.mode=id_res&openid.assoc_handle=%7BHMAC-SHA1%7D%7B4b00d7b2%7D%7Bvo1FEQ%3D%3D%7D&openid.identity=http%3A%2F%2Fwww.roket-enterprises.com%2Fopenaccount%2Fopenid%3Ahachque&openid.response_nonce=2009-11-16T04%3A40%3A18Zrrz8R4&openid.return_to=http%3A%2F%2Fopeniddirectory.com%3A80%2Fopenidauth%2Fid%2Fc%2Ffinish_auth.php%3Fnonce%3DadCevd6T&openid.signed=assoc_handle%2Cidentity%2Cmode%2Cresponse_nonce%2Creturn_to%2Csigned%2Csreg.email%2Csreg.fullname%2Csreg.nickname&openid.sreg_email=jrhodes%40roket-enterprises.com&openid.sreg_fullname=James+Rhodes&openid.sreg_nickname=jrhodes&openid.sig=MGVhMmQ1Mzg4ZWFlMWY1OWVlYjlmZmY0Njc3OTc5YWIzMjM3NGFjMQ%3D%3D&openid.is_valid=true;
This is the PHP code that my file is using to handle check_authentication (remember that PHP turns all . characters into _ for $_GET and $_POST variables since they aren't valid character in PHP array keys):
// Retrieve the OpenID information from the $_REQUEST data
// I'm not sure whether it's possible that this data might
// come in on the $_GET parameter instead of $_POST, so that's
// what it uses $_REQUEST.
$assoc_handle = $_REQUEST['openid_assoc_handle'];
$sig = $_REQUEST['openid_sig'];
$signed = $_REQUEST['openid_signed'];
// The method for returning data is via the headers outputted
// by the webserver. Create an array that stores the headers
// to be returned.
$keys = array(
'openid.mode' => 'id_res',
'openid.assoc_handle' => $_REQUEST['openid_assoc_handle'],
'openid.identity' => $_REQUEST['openid_identity'],
'openid.response_nonce' => $_REQUEST['openid_response_nonce'],
'openid.return_to' => $_REQUEST['openid_return_to'],
'openid.signed' => $_REQUEST['openid_signed'],
'openid.sreg_email' => $_REQUEST['openid_sreg_email'],
'openid.sreg_fullname' => $_REQUEST['openid_sreg_fullname'],
'openid.sreg_nickname' => $_REQUEST['openid_sreg_nickname']
//'openid_mode' => 'id_res'
);
// The server may request that we invalidate the user's session
// via $_REQUEST['openid_invalidate_handle']. In this case we
// will clear the session data (you may need to change this
// depending on how you implement the session). After doing so
// we continue and tell the server we did via a variable
if (strlen($_REQUEST['openid_invalidate_handle']) > 0)
{
// Reset the session
session_unset();
session_name('openid_server');
session_start();
// Set the header we need to return
$keys['openid.invalidate_handle'] = $_REQUEST['openid_invalidate_handle'];
}
// We need to validate the signature now. This constructs a token_contents
// for signing the data. The signing key is returned as openid.sig
// and is generated with base64(HMAC(secret(assoc_handle), token_contents)
$token_contents = '';
foreach (explode(',', $signed) as $param) {
$post = preg_replace('/\./', '_', $param);
$token_contents .= sprintf("%s:%s\n", $param, $_REQUEST['openid_' . $post]);
}
// Generate our openid.sig and add it to the list of keys to
// return.
$keys['openid.sig'] = base64_encode(hash_hmac('sha1',$token_contents,$assoc_handle));
// Add the data that we are sharing (via SReg) to the headers.
// For now this is fixed data (see action_authorization.php).
//$keys["sreg.fullname"] = 'James Rhodes';
//$keys["sreg.nickname"] = 'jrhodes';
//$keys["sreg.email"] = 'jrhodes#roket-enterprises.com';
// Just accept the request for now..
// phpMyID does some kind of secret-shared-key thing
// here to determine whether it is valid. I'm not
// quite sure how that process works yet, so we are just
// going to say go ahead.
$keys["openid.is_valid"] = "true";
// We need to format the $keys array into POST format
$keys_post = "";
$keys_post_first = true;
foreach ($keys as $name => $value)
{
if ($keys_post_first)
$keys_post_first = false;
else
$keys_post .= "&";
$keys_post .= urlencode($name) . "=" . urlencode($value);
}
// Now output the POST data
header('Content-Type: application/x-www-form-urlencoded');
header('Content-Length: ' . strlen($keys_post));
header($keys_post);
Can anyone help me with my problem? I've been trying to get this working for months and I can't get a straight answer on how this stage of OpenID authentication is meant to work.
First of all, although PHP transforms periods to underscores in parameter names, be sure you're sending periods and not underscores.
Secondly, your check_authentication response should only have three parameters, but you have six. Check the spec and fix up your response and see if that helps.
Andrew Arnott,you're wrong!
documentation from openid.net:
11.4.2.1. Request Parameters
openid.mode
Value: "check_authentication"
Exact copies of all fields from the authentication response, except for "openid.mode".
may be more than three fields!
I had a similar issue. In my case, the client (relying party) failed to resolve the name of the OpenId provider to the correct ip. Although this is unlikely to be the case, please check name resolution on your relying server.