I have written this code
$ips = preg_split("/,/", $_SERVER["HTTP_X_FORWARDED_FOR"]);
$ip = $ips[0];
if ($key === $ip && $val === env('SERVER_ADDR')) {
$addr = env($ip);
if ($addr !== null) {
$val = $addr;
}
}
But I am getting following error:
<b>Notice</b>: Undefined index: HTTP_X_FORWARDED_FOR
Just dont use array keys without knowing for sure they always exist..
basic PHP one o' one
if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
// now only try to access this key
}
The alternative in Cake is to use wrapper methods that are designed to automatically check on the existence internally. Then you can just read the value directly. In your case env() checks on those server vars:
$result = env('HTTP_X_FORWARDED_FOR');
Related
I'm trying to create a Perl 6 client interface to an RPC server, with the class hierarchy matching the server URLs. e.g.
# for url path: /account/login
# client code:
$client.account.login;
For this to work, the 'child' object (account) needs to store a reference to its parent object (client).
This is what I've tried:
#!/usr/bin/env perl6
use v6;
class MyApp::Client::Account {
has $!client;
method login() {
# fake login
$!client.session_id = 'abc';
return 'ok';
}
}
class MyApp::Client {
has $.session_id is rw;
method account() {
state $empire = MyApp::Client::Account.new( :client(self) );
return $empire;
}
}
use Test;
plan( 2 );
my $client = MyApp::Client.new;
my $response = $client.account.login;
is( $response, 'ok', 'login successful' );
ok( $client.session_id, 'client has session_id' );
Running this gives the following error message:
1..2
Method 'session_id' not found for invocant of class 'Any'
in method login at test.pl6 line 9
in block <unit> at test.pl6 line 29
# Looks like you planned 2 tests, but ran 0
I don't really know any perl6 class/object idioms yet - am I even going about the design in the right way?
If so, why is $!client within the login() method undefined?
For reference, here's the perl5 (bare-bones) version that I'm trying to convert from:
#!/usr/bin/env perl
package MyApp::Client::Account;
sub new {
my $class = shift;
return bless {#_}, $class;
}
sub login {
my $self = shift;
# fake login
$self->{client}->session_id( 'abc' );
return 'ok';
}
package MyApp::Client;
sub new {
my $class = shift;
return bless {#_}, $class;
}
sub session_id {
my $self = shift;
if (#_) {
$self->{session_id} = shift;
}
return $self->{session_id};
}
sub account {
my $self = shift;
$self->{account} ||= MyApp::Client::Account->new( client => $self );
return $self->{account};
}
package main;
use Test::More tests => 2;
my $client = MyApp::Client->new;
my $response = $client->account->login;
is( $response, 'ok', 'login successful' );
ok( $client->session_id, 'client has session_id' );
Which gives the expected output:
1..2
ok 1 - login successful
ok 2 - client has session_id
So there are a few ways that Perl 6 OO differs from other implementations I've used. One is the awesome way that it will auto-fill your member variables for you. However, this only works when they are defined with public accessors.
class G {
has $!g;
has $.e;
method emit { say (defined $!g) ?? "$!g G thing" !! "nada G thing" }
}
Which will lead to the following behavior:
> my $g = G.new( :g('unit-of-some-kind'), :e('electric') )
G.new(e => "electric")
> $g.emit
nada G thing
> $g.e
electric
So when you are passing self as a reference to MyApp::Client::Account, it isn't being bound to the $!client variable because the default constructor will only bind to publicly accessible member variables.
You can either choose to make it accessible, or you can take the object construction logic into your own hands. This is how I imagine the code to look were I to need my own version in Perl 6 but had to keep client private:
class MyApp::Client::Account {
has $!client;
method new(:$client) {
self.bless( :$client );
}
# binds $!client to $client automatically based on the signature
submethod BUILD(:$!client) { }
method login() {
# fake login
$!client.session_id = 'abc';
return 'ok';
}
}
class MyApp::Client {
has $.session_id is rw;
has $.account;
# the default .new will call .bless for us, which will run this BUILD
submethod BUILD {
$!account = MyApp::Client::Account.new( :client(self) );
}
}
It can take some getting used to the new versus BUILD distinction. One key distinguishing point is that self is not available in the scope of new, but it is available in the scope of BUILD (albeit in a not-yet-fully-constructed form).
I am currently working on a project that uses web service PHP Nusoap. I implement it at first in the local computer and it is already working perfectly fine, it can insert already in the database.Since, we are also deploying our project in the production server (Linux RHEL 4) so we also need to include the web service. In implementing this in the production server, we got this error :
Operation '' is not defined in the WSDL for this service Here is the
full details :
<?xml version="1.0" encoding="utf-8"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode xsi:type="xsd:string">SOAP-ENV:Client</faultcode>
<faultactor xsi:type="xsd:string"></faultactor>
<faultstring xsi:type="xsd:string">Operation '' is not defined in the WSDL for this service
</faultstring>
<detail xsi:type="xsd:string"></detail>
</SOAP-ENV:Fault>
HERE IS THE CODE :
client.php
<?php
require_once('lib/nusoap.php');
$data = json_decode(file_get_contents("php://input"), true);
$file_name = $data['file_name'];
$location = $data['location'];
$client = new nusoap_client('http://servername:port/WebService/server.php?wsdl', true);
if ($SERVER['REQUEST_METHOD'] == 'POST') {
$err = $client->getError();
if ($err) {
echo "<h2> Constructor error </h2><pre>" . $err. "</pre>" ;
echo "<h2> Debug </h2><pre>" . htmlspecialchars($client->getdebug(), ENT_QUOTES) . "</pre>" ;
exit();
}
$datas = array (
'file_name' => $file_name,
'location' => $location
);
$result = $client->call('InsertData', $datas);
if ($client->fault) {
echo "<h2> Fault (Expect - The request contains an invalid SOAP Body)</h2> <pre>" ;
print_r ($result);
echo "</pre>";
} else {
$err = $client->getError ();
if ($err) {
echo "<h2> Error </h2><pre>" . $err. "</pre>";
} else {
print_r ($result);
}
}
} else if ($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "Method is not POST " ;
}
?>
server.php
<?php
require_once('lib.nusoap');
$server = new soap_server();
$server->configureWSDL('Database Sample Insertion', 'urn:Insert');
$server->soap_defenconding = 'UTF-8' ;
$server->register('InsertData',
array (
'file_name' => 'xsd:file_name',
'location' => 'xsd:location'
),
array ('return' => 'xsd:string'),
'urn:Insert',
'urn:Insertwsdl#InsertDate',
'rpc',
'literal'
);
function InsertData ($file_name, $location) {
$db_host = 'localhost';
$db_username = 'username';
$db_password = '' ;
$db_name = 'sample' ;
$conn = new mysqli ($db_host, $db_username, $db_password, $db_name);
if ($conn->connect_error) {
trigger_error('Database connection failed : ' .$conn->connect_error , E_USER_ERROR);
}
$sql = "INSERT INTO transaction (`filename`, `location`) VALUES ('$file_name', '$location')";
$query = $conn->query($sql);
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '' ;
$server->service($HTTP_RAW_POST_DATA);
?>
what does this problem means and how can we solve this? Or how to setup the web service PHP Nusoap in the production server? Any ideas/suggestions is appreciated. Thanks
I'v had the same problem when PHP/Apache version changed at my server. Im my case the problem was located inside nusoap library function: parse_http_headers()
There is a function used to get all HTTP headers getallheaders() and it seems not getting all headers as it should. There were no Content-Type which is required for nusoap to parse request (ex. text/xml).
Fortunately nusoap checks if function getallheaders() exists and if not it uses $_SERVER array to parse headers.
Finally the one thing I had to do was to change one line of code inside nusoap.php file to disable this function:
if (function_exists('getallheaders')){ ...
to this one:
if (0 && function_exists('getallheaders')){ ...
Hope this help others!
i get this wierd bug.
i have this code, which compares the password in the config file with the given argument:
if(label.equalsIgnoreCase("login")){
if(getConfig().getString("players."+p.getName()+".password") == args[0]){
p.sendMessage("OK!");
} else {
p.sendMessage("NOT OK!");
}
but no matter what, it ouputs "NOT OK!", what am i doing wrong?
ive tried to debug it, to send a message with the given argument and what it sees in the config file.
they were both the same!
You should try
String configValue = config.getString("players."+p.getName()+".password");
if(configValue != null && configValue.equals(args[0]) { // maybe you just need to change the index of args[], depending on if your command looks like /xy <password> or /xy z <password>
p.sendMessage("OK!");
} else {
p.sendMessage("NOT OK!");
}
I am pissed off with this problem from 2 days.
I am using MODx Revolution 2.2.5 (traditional) and want to login to modx from external server just to fetch some user details.
1) I know that runprocessor method works only if i am logged in to manager (unfortunately, that's the only way i know to login user in) So i tried IFRAME method to avoid (cross scripting) it worked perfectly but i am not able to read the data from IFRAME using javascript because of same issue, cross domain access policy.
When i try to post data using some other method like CURL, Ajax using
header("Access-Control-Allow-Origin: *");
I am able to login (I see $response->response['success'] == 1) but cant access any data and it says
Fatal error: Call to a member function get() on a non-object
Below is the snippet code i am using
if(isset($_POST) && count($_POST)){
$c = array(
'username' => $_POST['username'],
'password' => $_POST['password']
);
$response = $modx->runProcessor('security/login',$c);
if($response->response['success'] == 1){
$user['id'] = $modx->user->get('id');
$profile = $modx->user->getOne('Profile');
$user['fullname'] = $profile->get('fullname');
$user['email'] = $profile->get('email');
echo json_encode($user);
}else{
echo json_encode($response->response);
}
}
2) I can use login snippet but it doesnt return output what i expect. We have ready site and we are already using login plugin so i cant even modify login plugin to respond with expected data
How can i login to modx using api or any other method ??
You are really attacking this problem completely wrong in my opinion. If you want to access a server/webpage from another, you don't iFrame and do it the way you are. That is hacking, and this hole will most likely be fixed in a future version.
What you SHOULD do is connecting to the database and just gather the information from the user-table.
No hacking, no "tricks", won't stop working and much safer.
Well, I sorted out this today, Below is the complete come that worked perfectly.
Pay attention to
header("Access-Control-Allow-Origin: http://www.xyz.com");
Using above CORS specification you can allow 2 servers to communication.
header("Access-Control-Allow-Origin: http://www.xyz.com");
if(isset($_POST['username']) && isset($_POST['password'])){
// get username and password from POST array
$username = $modx->sanitizeString($_POST['username']);
$password = $modx->sanitizeString($_POST['password']);
if(trim($username) != "" and trim($password) != ""){
// Load lexicons to show proper error messages
if (!isset($modx->lexicon) || !is_object($modx->lexicon)) {
$modx->getService('lexicon','modLexicon');
}
$modx->lexicon->load('login');
$loginContext= isset ($scriptProperties['login_context']) ? $scriptProperties['login_context'] :
$modx->context->get('key');
$addContexts= isset ($scriptProperties['add_contexts']) && !empty($scriptProperties['add_contexts']) ? explode(',', $scriptProperties['add_contexts']) : array();
$mgrEvents = ($loginContext == 'mgr');
$givenPassword = $password;
/** #var $user modUser */
$user= $modx->getObjectGraph('modUser', '{"Profile":{},"UserSettings":{}}', array ('modUser.username' => $username));
if (!$user) {
$ru = $modx->invokeEvent("OnUserNotFound", array(
'user' => &$user,
'username' => $username,
'password' => $password,
'attributes' => array(
'loginContext' => $loginContext,
)
));
if (!empty($ru)) {
foreach ($ru as $obj) {
if (is_object($obj) && $obj instanceof modUser) {
$user = $obj;
break;
}
}
}
if (!is_object($user) || !($user instanceof modUser)) {
//echo "cant locate account";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_cannot_locate_account')));
exit;
}
}
if (!$user->get('active')) {
//echo "inactivated accout";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_user_inactive')));
exit;
}
if (!$user->passwordMatches($givenPassword)) {
if (!array_key_exists('login_failed', $_SESSION)) {
$_SESSION['login_failed'] = 0;
}
if ($_SESSION['login_failed'] == 0) {
$flc = ((integer) $user->Profile->get('failedlogincount')) + 1;
$user->Profile->set('failedlogincount', $flc);
$user->Profile->save();
$_SESSION['login_failed']++;
} else {
$_SESSION['login_failed'] = 0;
}
//echo "wrong username pass";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_username_password_incorrect')));
exit;
}
$fullname = $user->Profile->get('fullname');
echo '{"success":true,"message":"Welcome '.$fullname.'!"}';
}else{
echo '{"success":false,"message":"Please enter username and password"}';
}
}
I am using auth module of kohana. I did register and login and its working fine. But when i do Auth::instance()->get_user()->id i get NULL
While login i do it with Auth::instance()->login($validator['email'], $validator['password']) and then redirect user to home page.
But when in one of the controller i do Auth::instance()->get_user()->id i get NULL
What would be the cause. Is that i have to first set something???
Try Auth::instance()->get_user()->pk().
pk() is for primary key.
Works in KO3.
My Mistake
In the _login function of modules/auth/classes/kohana/auth/orm.php
In that i was doing the following
$user = ORM::factory('user');
$user->where('email', ' = ', $email)
->and_where('password', ' = ', $password)
->find();
// TODO remember to be done
if ($user !== null) {
$this->complete_login($user);
return true;
} else {
return false;
}
In above i was checking $user is null or not but if the email and password not match the user instance will be created with NULL values for all the columns.
So now i am checking $user->id !== NULL and it is working fine.
Try this:
if ($user->loaded()) {
$this->complete_login($user);
return true;
} else {
return false;
}
See ORM::__call() if you want to know what happends (since ORM::loaded() does not exist)