PHP strcmp question - php

I have been writing a webcrawler program, and I am attempting to compare a previous url (for the last site visited) with a current url (the current or next site to visit). To do this I am using a strcmp function such as this:
array_push($currentsite, $source);
if (strcmp($currentsite[2], $currentsite[3])==0){
echo "redundancy";
crawlWebsite($originalsource);
}
where current site is an array of the previous sites and the current site. I am looping through new sites each time with recursion in the larger program.
However, every time I run a strcmp on the current site and the new site, even when the urls are identical, I get a result of -1. Does anyone know why this might consistently be happening?
Thanks.

even when the urls are identical,
If the two input strings are identical, strcmp returns 0, so your input strings are not identical. Check the contents of $currentsite.
BTW strcmp($a, $b) == 0 can be efficiently rewritten as $a == $b.

Probably the site you are testing contains something that makes it unique, like the current time or a hidden ID to save your session or something like this.
Anyway that will result in strcmp to not return 0. It would be bettor to have a function that gives you a percentage of equality so you can define a level above which you consider two sites as identical.

Related

PHP Post_method hacking

I ran into the snippet online
https://www.quora.com/Why-is-PHP-hated-by-so-many-developers
when I was doing some research about PHP, and I simply have no idea how the codes work.
Can anyone kindly explain what happens in the snippet and how one can log in without knowing the password?? or just give me some relevant articles to read. Thanks in advance.
See the manual:
Returns ... 0 if they [strings] are equal.
So, by the snippet logic, you should compare 0 to 0 in the end. But when you send password[]=wrong, you actually send an array, forcing strcmp to throw a warning, completely bypassing the function call and perceive the condition as true
You should always use strict comparison, just in case. So in the snippet above it would be enough to compare strictly by type and value (with ===):
if(strcmp($POST['password'], "sekret") === 0)
In this case password[]=wrong would not work anymore.

PHP : Sum up the result of some "echo do_shortcode"

I'v been searching all the website / web with to achieve that, with no luck. I'm not a developper at all also, so the few information that I could get, didn't help me either.
The situation : I have some Wordpress plugins, that allows me to generate some numbers with shortcode. For example I have [shortcode1] from one plugin, and [shortcode2] from another, each of them returning a dynamic number.
I'm using PHP in my pages, to display that number, by a simple "php echo do_shortcode('[shortcode1]');" , same for shortcode 2, and it works well.
I'm trying to sum up the value that is returning from these 2 shortocdes. Lets say shortcode1 = 10 and shortcode2 = 20, I need to display "30".
I tried sending the "do_shortcodes" into arguments, then using "sum", or use "+", but none of this worked, and actually it makes sense because when doing so, I am attributing the shortcode to this argument, not the actual result of it. Knowing that, I then tried to apply "echo do_shortcode" to the argument instead, to save the result instead of the actual shortcode. But apparently it's not correct to do it, or I don't have the way to do it.
I hope I could explained properly, any idea of how I could achieve this ? (Wishing there could be an answer as simple as 1+1=2 :) )
Thanks in advance
You can ensure numbers only like this, but do_shortcode() is the wrong approach for what you want to do in most cases. The following is not efficient in terms of programming but will do what you want. You could just generate a variable and use that but i suppose you have your reasons. Anyway...
$a = (int) preg_replace('/[^0-9]/','',do_shortcode('[whatever]'));
$b = (int) preg_replace('/[^0-9]/','',do_shortcode('[whateverb]'));
$c= $a + $b;
echo $c;

php evaluation sequence of if-statements

I'm having trouble with sanitizing user input, where I don't know, if POST-Data has been sent or not. When I just do this to check:
if ($_POST["somedata"] == 2)
DoSomething();
I will get an error notice with error_reporint = E_ALL, that $_POST["somedata"] may not be defined (e.g. when the page is loaded without the form).
So I do this check now:
if (isset($_POST["somedata"]) && $_POST["somedata"] == 2)
DoSomething();
This doesn't output an error but it looks very unstable to me. I'm not sure if I just have luck with my PHP-Version or the simplicity of the statement. Is it also safe to use, when the if-statement is more complex, as long as the order of these two items are the same? Is it safe to use with all PHP-Versions?
Using isset in combination with a lazy-and (&&) is relatively correct (it prevents strictness warnings). A more advanced way would be to have automatic input checking against a schema or model.
You could have:
$schema = array(
"somedata" => "number"
);
Using the schema approach requires a little bit of architecture but it removes the instability that you might be worried about.
One thing worth mentioning is that there is a difference between validating input on a syntax level (did I get all the required inputs) and input validation on a semantic level. Let's say you have a service called GetItem and you pass id = 3 the syntax checker will check for the presence of the id property and that it is a number. Then you need to check whether 3 actually exists.
So rather than returning invalid request (bad input) you might want to return no such item.
Your approach is functionally correct, as the && is short-circuited if the first term evaluates to false. Regarding stability, as you suspected, there is a small concern, related especially to code duplication, mainly you need to always pay care that both keys match the same string (it is appropriate to say this is a matter of code duplication).
One approach to this would be to define a function that does the check and returns the contents at the desired key if exist, like for example:
function arr(array $array, $key, $defaultValue=false) {
return isset($arrray[$key]) ? $array[$key] : $defaultValue
}
You pay a small performance penalty for calling a function (you can reduce it by removing the type hinting for the $array parameter), however you have a more stable code.
Usage example in your case:
if(arr($_POST, 'somedata') === 2)) {
// do your stuff
}
We've been using this at work for some time now, going back years in code. It's fine to use since it first checks it the variable is actually there, and only then checks if it has a value.
Your code snippet is correct.
if (isset($_POST["somedata"]) && $_POST["somedata"] == 2)
DoSomething();
I would highly encourage you to use the triple equals for your quality check. Check out How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ? for more info on equality checks.
The triple equal means it needs to be an integer and not just a string, good practice to get into doing this.

Can anyone please explain me how is this happening?

I have created a page like account_details.php in which I'm counting the number of times the user visits the page. So for that I have created a file called count_session.php in which the code is like:
<?php
session_start();
if(!isset($_SESSION['counter'])){
$_SESSION['counter'] = 0;
}else{
$_SESSION['counter'] = $_SESSION['counter'] + 1;
}
?>
I include the above file in account_details.php page in which I want the user to see how many times he has visited and it works fine but I don't understand how does it work? I have checked using the echo message inside the first 'if' condition that is if(!isset) and it seems it does not enter that condition instead it enters the else part but then how come it's getting initialized by 0, but when the user visits the account_details.php page the message pops up like "You have visited this page for 1 times". How come it's calculating 0 + 1 when it's not yet initialized anywhere in the count_session.php file. Can anyone please tell me?
This has nothing to do with session variables, as it works the same way for regular variables.
If you write something like $a = $a + 1 and $a is not declared anywhere, PHP considers it as not set, which translates to 0 if cast to int (the same way it translates to false if cast to bool, but that's not relevant in this case). The reason why your variable is cast to int, is that PHP feels the need to, because you are trying to perform a mathematical operation on that variable.
To sum up: PHP detects that you want to add up 2 values, does something like intval($a) (but internally of course) and adds 1 to that. In addition, if you have notices enabled, this should throw you a notice.
Sessions are global to a site (as in hostname) because they are identified by an ID stored in cookies, which are by default sent back to to all URLs under a single domain name. You can restrict that further, but this is the default behavior.

Why isset() is more efficient to test than '==='?

Summarized, I made a loop with a few iterations to check the efficiency of each test:
$iterations = 99999999;
$var = null;
isset comparasion
if ( isset( $var ) )
{
}
'===' comparasion
if ( $var === null )
{
}
And i have this log, in microseconds:
'isset()': 1.4792940616608
'===': 1.9428749084473
For me, this is a little curious. Why isset() function is faster than one comparison operator as ===?
The === comparison is a strict check, meaning that the two objects you're comparing have to be of the same type. When you break it down in plain English, it's actually not that weird that === needs some more time. Consider the parser to do this:
if (isset($var)) {
// Do I have something called $var stored in memory?
// Why yes, I do.. good, return true!
}
if ($var === null) {
// Do I have something called $var stored in memory?
// Why yes, I do.. good! But is it a NULL type?
// Yes, it is! Good, return true!
}
As you can see, the === operator needs to do an additional check before it can determine if the variable matches the condition, so it's not that strange that it is a little bit slower.
Isset is not a function: it is a language built-in. Using isset is faster than using a function.
The other thing is that isset is used all over the place, so it makes sense that it's been profiled to death, whereas === maybe hasn't received as much love.
Other than that, you'd have to dig in the PHP source with a profiler to see exactly what's going on.
I'm not sure I would call 100 million "a few iterations". You appear to have accumulated about a half-second difference, divide that by 100 million and you get a whopping 5 nanosecond difference per iteration if my math is correct. With the difference being so small it may simply come down to the fact that isset only has one operand in this context and === has two.
It's impossible to even discuss the Zend engine's implementation details of the two examples without specifying a specific PHP version; source code is a moving target. Even minute changes to the implementations are going to effect the results over that many passes. I would not be surprised if you found the opposite to be the case on some versions of PHP and/or in a different context.
isset itself is covered by three different op-codes in the VM depending upon the context:
"Simple" Compiled Variables like your example: ZEND_ISSET_ISEMPTY_VAR
Arrays: ZEND_ISSET_ISEMPTY_DIM_OBJ (requires 2 operands, the var and the index)
Object properties: ZEND_ISSET_ISEMPTY_PROP_OBJ (also 2 operands, var and prop name)
It's an interesting question for curiosity's sake but we're in hair splitting territory and it's probably not a real-world optimization strategy.

Categories