Cant unserialize string - php

When I try and unserialize the following string:
a:3:{i:0;s:19:\"Sales+%2F+Customers\";i:1;s:78:\"Micro+Business+%28less+than+10+employees+%26+turnover+under+%C2%A32+million%29\";i:2;s:13:\"Manufacturing\";}
It returns false and I get the following warning:
WARNING: Error at offset 9 of 158 bytes
It was generated by calling serialize on an array though and looks valid to me though, I don't understand what the problem is?

The slashes aren't valid in this case, use stripslashes(). Demo code below:
<pre>
<?php
$x = "a:3{i:0;s:19:\"Sales+%2F+Customers\";i:1;s:78:\"Micro+Business+%28less+than+10+employees+%26+turnover+under+%C2%A32+million%29\";i:2;s:13:\"Manufacturing\";}";
echo "unserializing $x: " . PHP_EOL;
try {
print_r(unserialize($x));
echo PHP_EOL;
} catch (\Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
$y = "a:3{i:0;s:19:\\\"Sales+%2F+Customers\\\";i:1;s:78:\\\"Micro+Business+%28less+than+10+employees+%26+turnover+under+%C2%A32+million%29\\\";i:2;s:13:\\\"Manufacturing\\\";}";
echo "unserializing $y: " . PHP_EOL;
try{
print_r(unserialize($y));
echo PHP_EOL;
} catch (\Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
echo "unserializing stripslashes($y): " . PHP_EOL;
try{
print_r(unserialize(stripslashes($y)));
} catch (\Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
?>
</pre>

Related

I dont know this error or how to fix it can some one fix it for me?

I'm getting this error message if I try to start the bot:
[INFO] Try to initialize connection...
PHP Fatal error: Uncaught Error: Call to a member function getAdapter() on null in /var/www/vhosts/kaitomar.de/httpdocs/tsbot/myteamspeakid/bot.php:70
Stack trace:
#0 {main}
Currently I'm using the php version 7.0.33.
I hope someone can help me out with my issue
<?php
session_start();
require_once("ts3phpframework-1.1.32/libraries/TeamSpeak3/TeamSpeak3.php");
require_once("config.php");
require_once("myTeamSpeak.php");
require_once("lib/color.class.php");
$colors = new Colors();
echo $colors->getColoredString("== START ==", "white"), PHP_EOL;
function connectToServer(&$ts3_VirtualServer)
{
global $query, $colors;
try {
echo $colors->getColoredString("[INFO] Try to initialize connection...", "light_gray"), PHP_EOL;
$ts3_VirtualServer = TeamSpeak3::factory("serverquery://" . $query['username'] . ":" . $query['password'] . "#" . $query['ipAddress'] . ":" . $query['port'] . "/?server_port=" . $query['voicePort'] . "&nickname=" . urlencode($query['nickname']) . "&blocking=0");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("serverqueryWaitTimeout", "onTimeout");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("notifyCliententerview", "onJoin");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("notifyTextmessage", "onTextmessage");
$ts3_VirtualServer->notifyRegister("server");
$ts3_VirtualServer->notifyRegister("textprivate");
echo $colors->getColoredString("[INFO] Connection to Virtual Instance \"".$ts3_VirtualServer["virtualserver_name"]."\" successfully established!", "light_gray"), PHP_EOL;
echo $colors->getColoredString("[INFO] Memory usage: ".convert($ts3_VirtualServer->getParent()->getAdapter()->getProfiler()->getMemUsage(),"MB"), "light_gray"), PHP_EOL;
$vVersion = $ts3_VirtualServer["virtualserver_version"];
$ex[1] = explode("]", $vVersion);
$ex[2] = explode(": ", $ex[1][0]);
(!"1530178919" >= $ex[2][1] ? stopBot() : '');
return true;
}
catch(TeamSpeak3_Transport_Exception $e){
$erromsg = $e->getMessage();
if(isset($erromsg) && $erromsg == "Connection refused"){
print_r($colors->getColoredString("[ERROR] Message from Framework: " . $erromsg . "\nThe query is not accessible.\nThe server is probably offline...", "white", "red"), PHP_EOL);
} else {
print_r($colors->getColoredString("[ERROR] " . $e->getMessage(), "white", "red"), PHP_EOL);
}
return false;
}
catch(Exception $e)
{
print_r($colors->getColoredString("[ERROR2] " . $e, "white", "red"), PHP_EOL);
return false;
}
}
function autoReconnect(&$ts3_VirtualServer, &$reconnectTime)
{
global $colors;
do{
echo $colors->getColoredString("gc_collect_cycles ".gc_collect_cycles(), "red"), PHP_EOL;
echo $colors->getColoredString("__destruct ". $ts3_VirtualServer->getAdapter()->__destruct(), "red"), PHP_EOL;
// sleep for wait to check if server is online
sleep(intval($reconnectTime));
}while(!connectToServer($ts3_VirtualServer));
}
$autoReconnectTime = $option['reconnect_int'];
while(true){
try{
if(!isset($ts3_VirtualServer)) connectToServer($ts3_VirtualServer);
try{
while(1) $ts3_VirtualServer->getAdapter()->wait();
}
catch(TeamSpeak3_Transport_Exception $e){
echo $colors->getColoredString("[EXC1] ".$e->getMessage(), "red"), PHP_EOL;
autoReconnect($ts3_VirtualServer, $autoReconnectTime);
}
catch(Exception $e){
echo $colors->getColoredString("[EXC2]", "red"), PHP_EOL;
echo $colors->getColoredString("ErrMsg: ".$e->getMessage(), "red", "white"), PHP_EOL;
echo $colors->getColoredString("Code: ".$e->getCode(), "white", "yellow"), PHP_EOL;
echo $colors->getColoredString("Sender: ".$e->getSender(), "red"), PHP_EOL;
}
}
catch(Exception $e){
echo $colors->getColoredString("[EXC0] ".$e->getMessage(), "red"), PHP_EOL;
autoReconnect($ts3_VirtualServer, $autoReconnectTime);
}
}
function stopBot(){
global $colors;
echo $colors->getColoredString("[WARNING] Stopping Bot...", "yellow"), PHP_EOL;
echo $colors->getColoredString("Reason you need minimum the Server-Version 3.3.0", "yellow"), PHP_EOL;
echo $colors->getColoredString("You can download the latest beta here: http://dl.4players.de/ts/releases/pre_releases/server/?C=M;O=D", "yellow"), PHP_EOL;
sleep(1);
exit();
}
function onTimeout($seconds, TeamSpeak3_Adapter_ServerQuery $adapter) {
$last = $adapter->getQueryLastTimestamp();
$time = time();
$newtime = $time-300;
$update = $last < $newtime;
//$update_str = ($update) ? 'true' : 'false';
//print_r("Timeout! seconds=$seconds last=$last time=$time newtime=$newtime update=$update_str\n");
if($update)
{
$adapter->request("clientupdate");
}
}
function onJoin(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3_Node_Host $host)
{
runChecker(getEvent($event, $host), $host);
}
function onTextmessage(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3_Node_Host $host)
{
global $settings, $db, $ts3_VirtualServer, $colors;
$client = $host->serverGetSelected()->clientGetById($event["invokerid"]);
$clientInfo = $client->getInfo();
if ($clientInfo["client_type"] == 0) {
if ($host->whoami()['client_unique_identifier'] != $event["invokeruid"]) {
if (isUID($clientInfo['client_unique_identifier'])) {
if (isCommand("!help", $event["msg"], $client)) {
$client->message("[u]Available command commands...[/u]");
$client->message("[B]!get info ram [KB|MB|GB][/B] | Shows the current RAM consumption of the bot.");
$client->message("[B]!get countKickedUser ofBadges[/B] | Shows the count of all kicked user if there have set badges (only on this session)");
} else if (isCommand("!get info ram KB", $event["msg"], $client) OR isCommand("!get info ram MB", $event["msg"], $client) OR isCommand("!get info ram GB", $event["msg"], $client)) {
if (isCommand("!get info ram KB", $event["msg"], $client)) {
$client->message("The RAM consumption is [B]" . convert($ts3_VirtualServer->getParent()->getAdapter()->getProfiler()->getMemUsage(), "KB") . "[/B]");
} else if (isCommand("!get info ram MB", $event["msg"], $client)) {
$client->message("The RAM consumption is [B]" . convert($ts3_VirtualServer->getParent()->getAdapter()->getProfiler()->getMemUsage(), "MB") . "[/B]");
} else if (isCommand("!get info ram GB", $event["msg"], $client)) {
$client->message("The RAM consumption is [B]" . convert($ts3_VirtualServer->getParent()->getAdapter()->getProfiler()->getMemUsage(), "GB") . "[/B]");
}
} else if (isCommand("!get info ram", $event["msg"], $client)) {
$client->message("Error, please use this command so [B]!get info ram [KB|MB|GB][/B]");
} else if (isCommand("!get countKickedUser ofBadges", $event["msg"], $client)) {
(!isset($_SESSION['countOfKickedBadgesUser']) ? $countKickedUserBadge = 0 : $countKickedUserBadge = $_SESSION['countOfKickedBadgesUser']);
$client->message("There were already " . $countKickedUserBadge . " users (in this session) kicked from the server because these badges had set!");
} else {
$client->message("Command not found, use \"!help\" for more informations...");
}
echo $colors->getColoredString("[EVENT][INCOMING][textprivate][" . date("d.m.Y h:i:sa") . "] '" . $clientInfo['client_nickname'] . "' send a message: " . $event["msg"], "light_blue"), PHP_EOL;
} else {
echo $colors->getColoredString("[" . date("d.m.Y h:i:sa") . "] Invalid Master '" . $clientInfo['client_nickname'] . "' send a message: " . $event["msg"], "light_blue"), PHP_EOL;
$client->message("You are not my Master!");
}
}
}
}

How to catch Exceptions correctly in PHP and MongoDB

My question is about the correct way to catch exceptions in PHP.
Based on the accompanying examples of the PHP MongoDB driver, I
have created the following script:
<?php
try {
$mng = new MongoDB\Driver\Manager("mongodb://localhost:2717");
$query = new MongoDB\Driver\Query([], ['sort' => [ 'name' => 1], 'limit' => 5]);
$rows = $mng->executeQuery("testdb.cars", $query);
foreach ($rows as $row) {
echo "$row->name : $row->price\n";
}
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
echo "In file:", $e->getFile(), "\n";
echo "On line:", $e->getLine(), "\n";
}
?>
The example is educational and meant to be run on the PHP CLI. In PHP CLI, we get all the exceptions on the console, but for didactic purposes, I wanted to catch exceptions in the try/catch block.
I have seen more Java code than PHP and therefore, catching a generic MongoDB\Driver\Exception\Exception does not look good to me. In Java, we catch specific exceptions and have multiple try/catch blocks for different kinds of exceptions.
The driver has the following Exceptions:
MongoDB\Driver\Exception\AuthenticationException
MongoDB\Driver\Exception\BulkWriteException
MongoDB\Driver\Exception\ConnectionException
MongoDB\Driver\Exception\ConnectionTimeoutException
MongoDB\Driver\Exception\Exception
MongoDB\Driver\Exception\ExecutionTimeoutException
MongoDB\Driver\Exception\InvalidArgumentException
MongoDB\Driver\Exception\LogicException
MongoDB\Driver\Exception\RuntimeException
MongoDB\Driver\Exception\SSLConnectionException
MongoDB\Driver\Exception\UnexpectedValueException
MongoDB\Driver\Exception\WriteException
Is this a kosher way to catch exceptions in PHP?
How about placing a switch statement in the catch part, and determine the exception's type with the instanceof language construct or the get_class() function?
For example:
[...]
} catch(\Exception $e) {
switch (get_class($e)) {
case 'MongoDB\Driver\Exception\AuthenticationException':
// do stuff
break;
case 'MongoDB\Driver\Exception\BulkWriteException':
//etc, etc...
}
}
At first, I would examine the return values of get_class(), to make sure you I'm comparing the result with the exact exception names.
You can add multiple catch statements
<?php
try {
$mng = new MongoDB\Driver\Manager("mongodb://localhost:2717");
$query = new MongoDB\Driver\Query([], ['sort' => [ 'name' => 1], 'limit' => 5]);
$rows = $mng->executeQuery("testdb.cars", $query);
foreach ($rows as $row) {
echo "$row->name : $row->price\n";
}
} catch (MongoDB\Driver\Exception\AuthenticationException $e) {
echo "Exception:", $e->getMessage(), "\n";
} catch (MongoDB\Driver\Exception\ConnectionException $e) {
echo "Exception:", $e->getMessage(), "\n";
} catch (MongoDB\Driver\Exception\ConnectionTimeoutException $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
Adding multiple catch statement I think it's a better approach than switch. However, what if the exception isn't from these classes with a switch you should have a default case and also if you do it with multiple catches.
try {
$mng = new MongoDB\Driver\Manager("mongodb://localhost:2717");
$query = new MongoDB\Driver\Query([], ['sort' => [ 'name' => 1], 'limit' => 5]);
$rows = $mng->executeQuery("testdb.cars", $query);
foreach ($rows as $row) {
echo "$row->name : $row->price\n";
}
} catch (MongoDB\Driver\Exception\AuthenticationException $e) {
echo "AuthenticationException:", $e->getMessage(), "\n";
} catch (MongoDB\Driver\Exception\ConnectionException $e) {
echo "ConnectionException:", $e->getMessage(), "\n";
} catch (MongoDB\Driver\Exception\ConnectionTimeoutException $e) {
echo "ConnectionTimeoutException:", $e->getMessage(), "\n";
}catch (\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}

Zend Search Lucene case insensitive search doesn't work

I've got a Search class, which has
public function __construct($isNewIndex = false) {
setlocale(LC_CTYPE, 'ru_RU.UTF-8');
$analyzer = new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive();
$morphy = new Isi_Search_Lucene_Analysis_TokenFilter_Morphy('ru_RU');
$analyzer->addFilter($morphy);
Zend_Search_Lucene_Analysis_Analyzer::setDefault($analyzer);
Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('utf-8');
//if it's true, then it creates new folder to the path in $_indexFieles;
if ($isNewIndex) {
$this->_indexes[$this->_key] = Zend_Search_Lucene::create(Yii::getPathOfAlias('application.' . $this->_indexFiles), true);
} else {
$this->_indexes[$this->_key] = Zend_Search_Lucene::open(Yii::getPathOfAlias('application.' . $this->_indexFiles));
}
}
public function find($query, $eventId)
{
try
{
Zend_Search_Lucene_Search_QueryParser::setDefaultOperator(Zend_Search_Lucene_Search_QueryParser::B_AND);
$query = "($query) AND (event_id:$eventId)";
Zend_Search_Lucene::setResultSetLimit(self::ACCREDITATION_LIMIT);
return $this->_indexes[$this->_key]->find("{$query}");
}
catch (Zend_Search_Lucene_Search_QueryParserException $e)
{
echo "Query syntax error: " . $e->getMessage() . "\n";
}
catch (Exception $e)
{
echo $e->getMessage(). "\n";
}
}
I've got a record with name Test, when I'm looking for Test it works, but can't find this record with request test
Code example:
$s = new Search();
$s->find('test', 1232);//no results
I found a solution, the problem was that I was saving fields (name, etc.) as keyword, I changed it to text, and now it's working perfectly.

PHP - Define file include in class for all methods to use

Is there a way on including a file at the beginning of a class for all methods to use. The example below is a simplified version of what I am trying to achieve. Currently I have to include the file within every method.
Example Logic (not working)
class Myclass
{
protected require_once 'folerd1/folder2/pear/HTTP/Request2.php'; // this does not work
public function aMethod()
{
$request = new HTTP_Request2('http://example1.com/', HTTP_Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
public function aMethod1()
{
$request = new HTTP_Request2('http://example2.com/', HTTP_Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
// more methods
}
2 solution
1) require_once taken outside from class
require_once 'folerd1/folder2/pear/HTTP/Request2.php';
class Myclass
{
2) Include in the construct
public function __construct() {
require_once 'folerd1/folder2/pear/HTTP/Request2.php';
}
But it is better first option
The best way is to look at autoloading standard http://www.php-fig.org/psr/psr-0/
Have you tried this? I don't know what's your Request2.php file content. So my code is only a PoC!
require 'folerd1/folder2/pear/HTTP/Request2.php';
class Myclass
{
public function aMethod()
{
$request = new Request2('http://example1.com/', Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
public function aMethod1()
{
$request = new Request2('http://example2.com/', Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
As I commented out, just require the file in the constructor of the PHP class:
class Myclass{
function Myclass(){
require_once('folerd1/folder2/pear/HTTP/Request2.php');
}
I have not checked this, but it MIGHT be possible that what you're just doing is including it not only for all the class to see, but the entire script. Please, check that out if it is a problem for you. If not, the other 2 solutions might end up doing the same.
Cheers

catch error from a SOAP?

How to catch an error from a SOAP?
How can I avoid the fatal error and convert it to my own error.. In this example it's a SERVER_BUSY
code
class Validate_vatno {
private $client = null;
private $options = array(
'debug' => false
);
public function __construct(){
$this->client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', array('trace' => true));
}
public function check($country, $vatno){
$result = $this->client->checkVat(array(
'countryCode' => $country,
'vatNumber' => $vatno
));
if(!empty($this->options['debug'])){
echo '<pre>'.htmlentities($this->client->__getLastResponse()).'</pre>';
}
if($result->valid){
list($denomination, $name) = explode(' ', $result->name, 2);
return array(
'denomination' => utf8_decode($denomination),
'name' => ucwords(utf8_decode($name)),
'address' => ucwords(utf8_decode($result->address)),
);
}
else{
return array();
}
}
}
$vatValidation = new Validate_vatno();
if($return = $vatValidation->check('DK', 33214944)){
echo '<h1>valid one!</h1>';
echo 'denomination: ' . $return['denomination']. '<br/>';
echo 'name: ' . $return['name']. '<br/>';
echo 'address: ' . $return['address']. '<br/>';
}
else{
echo '<h1>Invalid VAT</h1>';
}
error
Fatal error: Uncaught SoapFault exception: [soapenv:Server] { 'SERVER_BUSY' } in /var/www/
Review how to handle exceptions
Throwing and Catching a Exception
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo 'Hello World';
?>

Categories