Purpose and outcome of the following PHP - php

Could someone elaborate on the purpose of this code and whether it would function, if so what the outcome would be?
The following is my interpretation of it, please point out where im going wrong.
Firstly, the client.php file; this is storing a name within the $param variable, not quite sure what else its doing... the $response is calling a 'get_message' which im guessing is being stored on the server.php file?
server.php is now creating the get_message function based on what was entered from your_name? it then provides a result of a message including your name...
Sorry if this is wrong, im quite new to this and a brief overview of what is happening would greatly help the overall understanding of it.
client.php
<?php
2 require_once (’lib/nusoap.php’);
3 $param = array( ’your_name’ => ’BIA Student’);
4 $client = new nusoap_client(’http://localhost/WebServiceSOAP/server.php’);
5 $response = $client->call(’get_message’,$param);
6 if($client->fault)
7 {
8 echo "FAULT: <p>Code: (".$client->faultcode."</p>";
9 echo "String: ".$client->faultstring;
10 }
11 else
12 {
13 echo $response;
14 }
15 ?>
server.php
1 <?php
2 require_once (’lib/nusoap.php’);
3 $server = new soap_server;
4 $server->register(’get_message’);
5 function get_message($your_name)
6 {
7 if(!$your_name){
8 return new soap_fault(’Client’,’’,’Put Your Name!’);
9 }
10 $result = "Welcome ".$your_name .". Thanks for calling your
11 first Web Service using PHP with SOAP!";
12 return $result;
13 }
14 if ( !isset( $HTTP_RAW_POST_DATA ) )
15 $HTTP_RAW_POST_DATA =file_get_contents( ’php://input’ );
16 // create HTTP listener
17 $server->service($HTTP_RAW_POST_DATA);
18 exit();
19 ?>

The client.php will create a soap connection to a web service. That client.php then queries that web service to see if a fault has occurred, if it does it displays the fault.
The server.php will responds to the client connection with a fault if no name has been set. If a name has been set, it returns a message however saying welcome and creates a listener.

Related

If and Else are both executed when the code is executed

PHP Version: 7.3.8
CakePHP Version: 4.0.1
Database Server: 10.4.6-MariaDB - mariadb.org binary distribution
Web server: Apache/2.4.39 (Win64) OpenSSL/1.1.1c
// WHAT I'M DOING
I created an error recording function to compliment the comprehensive error reporting functionality that comes out of the box with Cake. It's purpose in development is to assist me in reducing the amount of time it takes me to isolate an error when it occurs. And it's purpose when my app goes live is to do the same as in development but also assist me in monitoring any security vulnerabilities.
// WHAT'S HAPPENING:
Between 6 and 9 errors are being recorded in the database but the function that records the error is housed in the if part of the statement.
// USERS CONTROLLER
public function view(string $userID = null): void
{
// Initialise the variables.
$this->args = func_num_args();
$this->params = func_get_args();
if ($this->args !== 1) {
echo 'in FAILED ' . '<br /><br />';
// THIS IS THE FUNCTION THAT RECORDS THE ERROR.
$this->setErrorLocation(
$this->controller(). ' - Line ' . __LINE__);
if ($this->recordError(
$this->getErrorLocation()) === false) {
throw new UnauthorizedException();
}
throw new UnauthorizedException();
}
else {
// BUT THIS IS WHATS PRINTED TO THE SCREEN.
echo 'in PASSED ' . '<br /><br />';
}
// Rest of view code...
}
When the above code is executed the else part of the statement is executed and 'in PASSED' is printed to the screen. This is the expected behaviour.
And this is the unexpected behaviour:
Between 6 and 9 errors are recorded in the database?
'in FAILED' is NOT printed to the screen?
No exception is thrown?
======================================================================
// CODE TO REPLICATE
I've streamlined the code to the bare bones to hopefully enable replication of the behaviour.
// APP CONTROLLER
// The record error function:
The idea behind this function is best case scenerio I get a log in my database and Cake logs the error and throws an exception and worst case scenerio is Cake logs the error and throws an exception.
public function recordError(string $errorLocation): bool
{
// Initialise the variables.
$this->args = func_num_args();
$this->params = func_get_args();
// Check the number of arguments.
if ($this->args !== 1) {
return false;
}
// Check the argument type.
if (!is_string($this->params[0])) {
return false;
}
// Insert into the database.
$Errors = TableRegistry::getTableLocator()->get('Errors');
$error = $Errors->newEmptyEntity();
$error->ip = '::1';
$error->user_id = 1001; // NOTE: This must be a valid id so if $rules->existsIn is present in the user model the save does not fail.
$error->location = $this->params[0];
$error->date_occurred = '0000-00-00 00:00:00';
// Save the error.
if ($Errors->save($error)) {
return true;
}
return false;
}
// The error location setter and getter.
protected function setErrorLocation(string $errorLocation): object
{
$this->errorLocation = $errorLocation;
return $this;
}
protected function getErrorLocation(): string
{
return $this->errorLocation;
}
// USERS CONTROLLER
The controller name
private function controller(): string
{
$val = 'UsersController';
return $val;
}
// DATABASE
Table name: errors
Name Type Collation Attributes Null Default
id Primary int(10) No None AUTO_INCREMENT
ip varchar(100) utf8mb4_unicode_ci No None
user_id int(10) No None
location varchar(200) utf8mb4_unicode_ci No None
date_occured datetime No None
======================================================================
// RELEVANT INFO
The majority of the time this function works as expected but in the controllers view, edit and index methods multiple errors are being recorded.
I use this technique several times in view, edit and index and its only on a couple of instances does it not work as expected.
Also it's not just when I use PHP argument functions, it also records multiple errors in index when I use is_string.
I'm not sure if it's my environment, PHP, Cake or something I'm doing.
======================================================================
// MY QUESTION
Why are the errors recorded in the database?
(I mean how can the errors be recorded unyet no exception is thrown and in PASSED is printed to the screen?)
Thanks Zenzs.
======================================================================
#Jeto
I used the below backtrace function and it prints the following:
$e = new \Exception;
var_dump($e->getTraceAsString());
string(3679) "
0 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Controller\Controller.php(524): App\Controller\UsersController->view('1026')
1 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Controller\ControllerFactory.php(79): Cake\Controller\Controller->invokeAction(Object(Closure), Array)
2 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\BaseApplication.php(229): Cake\Controller\ControllerFactory->invoke(Object(App\Controller\UsersController))
3 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Runner.php(77): Cake\Http\BaseApplication->handle(Object(Cake\Http\ServerRequest))
4 C:\xampp\htdocs\crm\vendor\cakephp\authentication\src\Middleware\AuthenticationMiddleware.php(122): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
5 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Runner.php(73): Authentication\Middleware\AuthenticationMiddleware->process(Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
6 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\I18n\Middleware\LocaleSelectorMiddleware.php(70): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
7 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Runner.php(73): Cake\I18n\Middleware\LocaleSelectorMiddleware->process(Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
8 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Runner.php(77): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
9 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Middleware\CsrfProtectionMiddleware.php(132): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
10 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Runner.php(73): Cake\Http\Middleware\CsrfProtectionMiddleware->process(Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
11 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Runner.php(58): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
12 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Routing\Middleware\RoutingMiddleware.php(162): Cake\Http\Runner->run(Object(Cake\Http\MiddlewareQueue), Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
13 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Runner.php(73): Cake\Routing\Middleware\RoutingMiddleware->process(Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
14 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Routing\Middleware\AssetMiddleware.php(68): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
15 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Runner.php(73): Cake\Routing\Middleware\AssetMiddleware->process(Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
16 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Error\Middleware\ErrorHandlerMiddleware.php(118): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
17 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Runner.php(73): Cake\Error\Middleware\ErrorHandlerMiddleware->process(Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
18 C:\xampp\htdocs\crm\vendor\cakephp\debug_kit\src\Middleware\DebugKitMiddleware.php(60): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
19 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Runner.php(73): DebugKit\Middleware\DebugKitMiddleware->process(Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
20 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Runner.php(58): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
21 C:\xampp\htdocs\crm\vendor\cakephp\cakephp\src\Http\Server.php(90): Cake\Http\Runner->run(Object(Cake\Http\MiddlewareQueue), Object(Cake\Http\ServerRequest), Object(App\Application))
22 C:\xampp\htdocs\crm\webroot\index.php(40): Cake\Http\Server->run()
23 {main}"
XDebug is an excellent suggestion but as yet I have not installed it but it's on my list.
And this comment helps me understand a little more:
It could easily be that some of the calls fall in the error case and one of them passes.
Thanks.
======================================================================
#ndm
I'm using Chrome and it is making multiple requests but only to the ones in the head section of my app. I can't see any requests for any other than the ones it should be. IE: Requests to the following because all the following are stored locally:
<script src="bootstrap-sass/javascripts/jquery.min.js"></script>
<script src="bootstrap-sass/javascripts/bootstrap.min.js"></script>
<script src="bootstrap-sass/javascripts/crm-sys.js"></script>
<link rel="stylesheet "href="bootstrap-sass/stylesheets/all.css" type="text/css" media="screen"/>
<link rel="stylesheet" href="bootstrap-sass/stylesheets/sys-styles.css" media="screen" type="text/css"/>
Due to the fact that I installed Compass which complies my sass I have a slightly different webroot structure. IE:
webroot
->bootstrap-sass
->.sass-cache
->fonts
->javascripts
->sass
->stylesheets
->webfonts
config.rb
->css
->font
->img
->js
IE: I don't store my stylesheets in the Cake default css folder. I'm not sure if I can recompile it so it does but I thought I'd save that job for just before I go live.
A POSSIBLE ANSWER:
Chrome doesn't make requests to anything it shouldn't be but because I use compass I have to traverse the directory to ensure the files can be found on index, add, view and edit and Chrome confirms it makes multiple requests for the same file.
And I have to declare each of the above links 3 times like below and Chrome confirms it's making 3 requests for each file.
<!-- Welcome and index etc -->
<script src="bootstrap-sass/javascripts/jquery.min.js"></script>
<!-- Add -->
<script src="../bootstrap-sass/javascripts/jquery.min.js"></script>
<!-- View and edit -->
<script src="../../bootstrap-sass/javascripts/jquery.min.js"></script>
Could this be the cause of the behaviour I'm seeing?
I think that might be it because the multiple entries in the database are always either an extra 3, 6, 9. Ie: Always grouped in threes and it's a bit coincidental that I declare each file 3 times and the user agent confirms its making 3 requests.
Surely that's got to be it. Would you agree?
Also thanks for the heads up about not echoing data from the controller. Can I confirm you mean I should write to a flat file or even to the db.
Thanks.

cPanel Parked Domains Not returning array

A password was changed and cPanel broke. Fixed the password and it's still broken! I have to iterate over parked domains. I've verified the user / password combination is correct via PuTTY.
<?php
include_once('cpanel_api_xml.php');
$domain = 'example.com';
$pass = '';//etc
$user = '';//etc
$xmlapi = new xmlapi('127.0.0.1');
$xmlapi->password_auth($user,$pass);
$domains_parked = $xmlapi->listparkeddomains($user);
foreach ($domains_parked as $k1=>$v1)
{
if ($v1->domain == $domain) {$return = true; break;}
}
?>
That code generates the following error:
Invalid argument supplied for foreach()
Apparently $domains_parked is not even set! I've spent time looking at the function being called so without dumping all 86KB here is the cleaned up version of $xmlapi->listparkeddomains:
<?php
public function listparkeddomains($username, $domain = null)
{
$args = array();
if (!isset($username))
{
error_log("listparkeddomains requires that a user is passed to it");
return false;
}
if (isset($domain))
{
$args['regex'] = $domain;
return $this->api2_query($username, 'Park', 'listparkeddomains', $args);
}
return $this->api2_query($username, 'Park', 'listparkeddomains');
}
?>
I don't know what they're doing with setting a variable as the second parameter. I've called this function with and without and tested the reaction with a simple mail().
Next I tried calling the API in a more direct fashion:
$xmlapi->api2_query($username, 'Park', 'listparkeddomains')
That also does not work. Okay, let's try some really raw output testing:
echo "1:\n";
print_r($xmlapi);
echo "2:\n";
print_r($xmlapi->api2_query($user, 'Park', 'listparkeddomains'));
echo "3:\n";
$domains_parked = $xmlapi->listparkeddomains($user);
print_r($domains_parked);
die();
That outputs the following:
1: xmlapi Object (
[debug:xmlapi:private] =>
[host:xmlapi:private] => 127.0.0.1
[port:xmlapi:private] => 4099
[protocol:xmlapi:private] => https
[output:xmlapi:private] => simplexml
[auth_type:xmlapi:private] => pass
[auth:xmlapi:private] => <pass>
[user:xmlapi:private] => <user>
[http_client:xmlapi:private] => curl ) 2: 3:
I have never encountered such fragile code though I have no choice but to use it. Some help please?
So cPanel version 74 killed off the whole XML API and it doesn't frigin tell you with any error messages. I can not objectively say in the least that cPanel provides a stable platform to build anything reliable upon. You can either intentionally gimp your server from automatically updating (and potentially miss out on security updates) or every so X iterations of time completely rewrite the code again...and again...and again.

SFTP PHP 5.6 using phpseclib hangs

I'm trying a simple example
$sftp = new phpseclib\Net\SFTP(FTP_ADDRESS);
if (!$sftp->login(FTP_USER, FTP_PASS)) {
$logger->error("FTP credentials error");
$logger->error($sftp->getLastSFTPError());
} else {
$logger->log("Connection successful");
}
print_r($sftp->rawlist());
However the script just hangs and finally times out
( ! ) Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\XookCatalogFeed\lib\phpseclib\Net\SSH2.php on line 3186
Call Stack
# Time Memory Function Location
1 0.2015 152184 {main}( ) ..\index.php:0
2 0.2244 2275600 handle ( ) ..\index.php:95
3 0.2246 2276880 {closure:C:\xampp\htdocs\XookCatalogFeed\handlers\import.php:157-285}( ) ..\index.php:95
4 0.2254 2303944 phpseclib\Net\SFTP->login( ) ..\import.php:170
5 5.1277 4457272 phpseclib\Net\SFTP->_send_sftp_packet( ) ..\SFTP.php:444
6 5.1278 4457592 phpseclib\Net\SSH2->_send_channel_packet( ) ..\SFTP.php:2635
7 30.0009 4457760 phpseclib\Net\SSH2->_send_binary_packet( ) ..\SSH2.php:3332
I have tried a lot of stuff but nothing seems to work. I have done some debugging (step by step) it looks like the servers accepts thje credential but then the client just loops sending empty data at _send_binary_packet.
Here is the log: https://gist.github.com/vlopez/2a48d261ab7713dbc06d
Someone, please help.

Odd issue with PHP namespace

I have slapped together a test PHP script. It would output some remote connection's geo ip based data. Nothing fancy, just a quick prototype.
But I am seeing an odd behavior, so I am asking here if somebody had any clues about it.
PHP is version 5.5.12 on Ubuntu 64 bit.
Here's some code from the geoip_test.php calling script:
require_once ('geoip_utils.php');
$server_geoip_record = geoip_record_by_name('php.net');
echo '<pre>PHP.net web server location: ' . print_r($server_geoip_record, 1);
echo '<br />PHP.net web server local time: ' . \df_library\getUserTime($server_geoip_record)->format('Y-m-d H:i:s');
Nothing fancy at all, isn't it?
Now the simple geoip_utils.php code:
<?php
namespace df_library;
require_once('timezone.php');
// Given an IP address, returns the language code (i.e. en)
function getLanguageCodeFromIP($input_ip)
{
};
// Given a geo_ip_record, it returns the local time for the location indicated
// by it. In case of errors, it will return the optionally provided fall back value
function getUserTime($geoip_record, $fall_back_time_zone = 'America/Los_Angeles') {
//Calculate the timezone and local time
try
{
//Create timezone
$timezone = #get_time_zone($geoip_record['country_code'], ($geoip_record['region'] != '') ? $geoip_record['region'] : 0);
if (!isset($timezone)) {
$timezone = $fall_back_time_zone;
}
$user_timezone = new \DateTimeZone($timezone);
//Create local time
$user_localtime = new \DateTime("now", $user_timezone);
}
//Timezone and/or local time detection failed
catch(Exception $e)
{
$user_localtime = new \DateTime("now");
}
return $user_localtime;
}
?>
When I run the calling script I get:
PHP Fatal error: Call to undefined function df_library\getUserTime() in /var/www/apps/res/geoip_test.php on line 5
The funny part is: if I add this debug code:
$x = get_defined_functions();
print_r($x["user"]);
I get this output:
Array
(
[0] => df_library\getlanguagecodefromip
[1] => df_library\gettimezone
[2] => df_library\getutcdatetime
[3] => df_library\getlocalizedtime
[4] => df_library\getutcdatetimeaslocalizeddatetime
[5] => df_library\getlocalizeddatetimeasutcdatetime
[6] => get_time_zone
)
First of all, I don't understand why the function names are converted to lower case.
But most of all, notice how index 0 shows the empty function function getLanguageCodeFromIP($input_ip) being defined, and that function is right above the one that the interpreter complains about as not being defined!
Why does PHP see the other function in that file but not the one I want to use?
Any ideas are welcome!
There is an extra semi-colon ; after the close bracket of function getLanguageCodeFromIP which causes PHP parser somehow unable to recognize the functions after getLanguageCodeFromIP.
As proven in OP's comment, removing the ; solved the problem.

MySql Query adding number 1 to variable when used in query?

Hope you can help I have a simple query updating positions x and y based various user id etc. But I have a problem when I pass the variable to be updated (through ajax) to PHP, I get the variable fine but on placing it in a query a number 1 is added to the query end making the last id unusable (see example id 68 becomes 681).
Never seen this before, I am relatively new to sql tho, hope someone can shed some light on this?
$xupdate = $_POST['xupdate'];
$yupdate = $_POST['yupdate'];
$stickytext_id = $_POST['stickytextid'];
$user_id= $_POST['uid'];
$proj_id=$_POST['projid'];
echo $xupdate; //output 358
echo'<br>';
echo $yupdate; //output 203
echo'<br>';
echo $stickytext_id; //output 68
echo'<br>';
echo $proj_id; //output 7
echo'<br>';
$sql_update_stickyxy="UPDATE textsticky SET textsticky_x = $xupdate AND textsticky_y = $yupdate
WHERE textsticky_id = $stickytext_id";
echo $sql_update_stickyxy; //outputs UPDATE textsticky SET textsticky_x = 358 WHERE textsticky_id = 681 not 68?
Looking at your echo'd output you obviously embezzled some of your code. As a first debugging measure you might use $_POST['stickytextid'] instead of $stickytext_id inside your query and see where it gets you.

Categories