Loop until the request response message equals to "true" in php - php

I'm trying to make a php script that would make a loop that would get the contents of my site/server and if the text response is for example "false" then it would do the same thing, basically will loop until the site's text response will echo "true".
This is what i tried:
$getcontents = file_get_contents("http://example.com/script.php"); // it will echo false
if (strpos($getcontents , 'false')) {
$getcontents = file_get_contents("http://example.com/script.php");
else if (strpos($getcontents , 'false')) {
$getcontents = file_get_contents("http://example.com/script.php");
}
else if (strpos($getcontents , 'true')) {
echo "finished".;
}
I'm not sure if this is the right way or even if it is possible and i apologize in advance if i did not explain myself very well. Thank you for attention!

You could use a regular while loop.
$getcontents = 'false'; //set value to allow loop to start
while(strpos($getcontents , 'false') !== false) {
$getcontents = file_get_contents("http://example.com/script.php");
}
echo "finished";
This will loop until $getcontents does not contain false.
You could also use a recursive function like this.
function check_for_false() {
$getcontents = file_get_contents("http://example.com/script.php");
if(strpos($getcontents , 'false') !== false) {
check_for_false();
} else if(strpos($getcontents , 'true') !== false) {
echo "finished";
} else {
echo "response didn't contain \"true\" or \"false\"";
}
}
This function should keep calling itself until $getcontents contains the word true, and does not contain false.

Related

PHP reading lines from file and compare them

I am trying to read all lines from a file and than see if a given string contains any of these lines.
My code
$mails = file('blacklist.txt');
$email = "hendrik#anonbox.net";
$fail = false;
foreach($mails as $mail) {
if(strpos($email, $mail) > 0) {
$fail = true;
}
}
if($fail) {
echo "Fail";
} else {
echo "you can use that";
}
The blacklist.txt can be found here http://pastebin.com/aJyVkcNx.
I would expect strpos return a position for at least one string in the blacklist, but it does not. I am guessing that somehow I am generating not the kind of values within the $mails as I am expecting.
EDIT this is print_r($mails) http://pastebin.com/83ZqVwHx
EDIT2 some clarification: I want to see if a domain is within an email, even if the mail contains subdomain.domain.tld. And I tried to use !== false instead of my > 0 which yielded the same result.
You need to parse the email well since you're checking the domain of the email address if its inside the blacklist. Example:
$email = "hendrik#foo.anonbox.net";
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
preg_match('/#.*?([^.]+[.]\w{3}|[^.])$/', $email, $matches);
if(!empty($matches) && isset($matches[1])) {
$domain = $matches[1];
} else {
// not good email
exit;
}
// THIS IS FOR SAMPLES SAKE, i know youre using file()
$blacklist = explode("\n", file_get_contents('http://pastebin.com/raw.php?i=aJyVkcNx'));
foreach($blacklist as $email) {
if(stripos($email, $domain) !== false) {
echo 'you are blacklisted';
exit;
}
}
}
// his/her email is ok continue
strpos returns FALSE if the string was not found.'
Simply use this :
$fail = false;
foreach($mails as $mail) {
if(strpos($email, $mail) === false) {
$fail = true;
}
}
Or even better use this:
$blacklist = file_get_contents('blacklist.txt');
$email = "hendrik#anonbox.net";
if(strpos($email, $blacklist) === false){
echo "fail";
} else {
echo "This email is not blacklisted";
}
You have found the common pitfall with the strpos function. The return value of the strpos function refers to the position at which it found the string. In this instance, if the string begins at the first character, it will return 0. Note that 0 !== false.
The correct way to use the function is:
if(strpos($email, $mail) !== false){
// the string was found, potentially at position 0
}
However, this function may not be necessary at all; if you are simply checking if $mail is the same as $email, instead of seeing if the string exists within a larger string, then just use:
if($mail == $email){
// they are the same
}
Though you might still use foreach, that’s array reduce pattern:
function check_against($carry, $mail, $blacklisted) {
return $carry ||= strpos($mail, $blacklisted) !== false;
};
var_dump(array_reduce($mails, "check_against", $email_to_check));
Hope it helps.
Yet another way to solve this. Works fine:
$blacklist = file_get_contents('blacklist.txt');
$email = "hendrik#x.ip6.li";
$domain = substr(trim($email), strpos($email, '#')+1);
if(strpos($blacklist, $domain)){
echo "Your email has been blacklisted!";
}else{
echo "You are all good to go! not blacklisted :-)";
}
Goodluck!

Does testing for a false statement execute the same statement if TRUE

The code block below actually executes when the whole script is run. What is not clear to me is that method write only test for the case of if data is not written to file. then the Exception should be thrown. It does say that if $data exist and writeable then write to it.
public function write($data) {
if (#!fwrite($this->_fp, $data . "\n")) {
throw new Exception('Could not write to the file.');
}
}
What am used to is this :
if( condition is true ) {
echo 'Run Code';
} else {
echo 'Throw Exception';
}
or something like this
public function query($sql) {
$result = mysql_query($sql, $this->connection);
if(!$result){
die("Database Query Failed : ". mysql_error());
}
return $result;
}
How is this possible ?
as mentioned in here if(expr) evaluates the expr to its Boolean value.. which means that in your example when calling the write function, the fwrite function always gets executed and then if checkes if it returns a falsy or truthy value..
and from the doc fwrite() returns the number of bytes written, or FALSE on error. hence #!fwrite($this->_fp, $data . "\n") evaluates to true on error, and the exception is thrown
I'm not good at explaining such kind of things, but let's try :)
I think you misunderstood how a condition works.
Let's use a simple example
if($x == 1) {
echo 'Run Code';
} else {
echo 'Throw Exception';
}
The if and what you put inside are independant. A condition is just a statement that returns a boolean, and a if just tests a boolean (whatever returned it). So you could transform this example like this :
$is_x_equal_to_one = ($x == 1); // $is_x_equal_to_one now contains true or false
if($is_x_equal_to_one) {
echo 'Run Code';
} else {
echo 'Throw Exception';
}
The ! operator negates an expression. If it's true, it will return false, and if it's false, it will return true.
So you could revert your condition like this :
$is_x_equal_to_one = ($x == 1);
if(!$is_x_equal_to_one) {
echo 'Throw Exception';
} else {
echo 'Run Code';
}
Now what if you don't need to run any code and you just want to say that "something is broken" if $x is not equal to 1 ? The else statement is always optional :
$is_x_equal_to_one = ($x == 1);
if(!$is_x_equal_to_one) {
echo 'Throw Exception';
}
fwrite not only writes to a file, it also returns false if it didn't worked. If it works, it returns a positive integer. And positive integers are evaluated as true with PHP.
That means you can use it like that :
$is_write_successful = fwrite($this->_fp, $data . "\n");
if(!$is_write_successful) {
echo 'Throw Exception';
}
And finally, you can shorten this code by removing a useless temporary variable :
if(!fwrite($this->_fp, $data . "\n")) {
echo 'Throw Exception';
}
You can rewrite the if as this:
$returnValue = #fwrite($this->_fp, $data . "\n");
if (!$returnValue) {
So it will always execute the fwrite function.

How could a PHP value contain a string of zero length not equal to the empty string or null?

I am retrieving some data from an in-house store and in case of failure, I get a very specific response. Calling strlen() on this variable returns the value of zero. It is also not equal to NULL or "". I'm using this code to test:
if ($data === NULL)
{
echo("data was null\n");
}
else if ($data === "")
{
echo("data was empty string\n");
}
else if (strlen($data) == 0)
{
echo("data was length zero\n");
}
This result is outputting data was length zero. What could the variable contain that is zero length, not null, and not the empty string?
Returned value must be false then.
echo strlen(false); // outputs 0
This may not being an answer. I can only answer if you present a var_dump($data); But I think also suprising for me is this:
$data = "\0";
if ($data === NULL)
{
echo("data was null\n");
}
else if ($data === "")
{
echo "data was empty string\n";
}
else if (strlen($data) == 0)
{
echo "data was length zero\n";
}
else
{
echo "something strange happened\n";
}
Output: something strange happened
:)
Try this :
$data = false;
I'm not sure why false has a strlen, but it does.

Check if page returns true or false

I am trying to verify a Minecraft username is paid or not.
By typing in the username at the end of the URL, it returns true or false.
$input = 'Notch';
function checkPlayer($player) {
$mcURL = 'http://www.minecraft.net/haspaid.jsp?user=';
$auth = file_get_contents($mcURL . $player);
if ($auth === true) {
echo $player. ' is valid';
} else {
echo $player. ' is not valid';
}
}
checkPlayer($input);
But it doesn't return true. By going to the page http://www.minecraft.net/haspaid.jsp?user=Notch, it does return true. How do I properly check? I think file_get_contents is the wrong function to use for this matter. I'm not sure though.
change this line :
if ($auth === true) {
with
if (trim($auth) == "true") {

Append json messages when multiple json arrays are echo'd with jQuery

I have 2 classes that return a json encoded array if an error message is added to the $_error array:
Validate.class.php:
public function showResponse()
{
if(!empty($this->_error)) {
return json_encode($this->_error);
}
else {
return true;
}
}
UserTools.class.php:
public function showResponse()
{
if(!empty($this->_error)) {
return json_encode($this->_error);
}
else {
return true;
}
}
Then in ajax.php I check if either of those classes return true, if so a new user can be added by a User class, then the user class will return a success response, if they don't return true, the json encoded errors in either UserTools.class.php or Validate.class.php are returned by either of those classes:
ajax.php
if($validate->showResponse() === true && $user_tools->showResponse() === true) {
$user = new User($username, $password, $email);
$user->save();
echo $user->showResponse();
}
else {
echo $user_tools->showResponse();
echo $validate->showResponse();
}
Firebug shows that everything get's returned as expected, UserTools.class.php returns the usernameexists error and Validate.class.php returns the others:
{"error":{"usernameexists":"Username already taken"}}
{"error":{"password":"This field is required","password_again":"This field is required","email":"This field is required"}}
Yet I can't display either of those messages via jQuery, if I remove 'echo $user_tools->showResponse();' from 'else' in ajax.php, the error messages do get appended correctly, when I want to display both errors, nothing get's appended.
jQuery file:
if(msg.error) {
if(msg.error['usernameexists']) {
$('#msg-username').show().html('<p></p>').addClass('error');
$('#msg-username p').append(msg.error['username']);
}
if(msg.error['username']) {
$('#msg-username').show().html('<p></p>').addClass('error');
$('#msg-username p').append(msg.error['username']);
}
if(msg.error['password']) {
$('#msg-password').show().html('<p></p>').addClass('error');
$('#msg-password p').append(msg.error['password']);
}
if(msg.error['password_again']) {
$('#msg-password_again').show().html('<p></p>').addClass('error');
$('#msg-password_again p').append(msg.error['password_again']);
}
if(msg.error['email']) {
$('#msg-email').show().html('<p></p>').addClass('error');
$('#msg-email p').append(msg.error['email']);
}
}
The reason its not working is because there are 2 seperate json objects
One way is to combine them, for that put this in your ajax.php
if($validate->showResponse() === true && $user_tools->showResponse() === true) {
$user = new User($username, $password, $email);
$user->save();
echo $user->showResponse();
}else {
$r1 = $user_tools->showResponse();
$r2 = $validate->showResponse();
if($r1 !== true && $r2 !== true){
$r1 = json_decode($r1);
$r2 = json_decode($r2);
foreach($r2['error'] as $k => $v)
$r1['error'][$k] = $v;
$r1 = json_encode($r1);
}else if($r1 === true){
$r1 = $r2;
}
echo $r1;
}
Other easier way would be to return the error object itself instead of json_encoded one from Validate.class.php and UserTools.class.php and combine them in ajax.php then output the json_encoded string. this would save the 2 json_decode calls in the above code.
Your return string contains two objects and i think that is what (rightly) confuses the json parser. Try prepending a { and appending a } to the else output, and separate the two objects with a comma

Categories