I am trying to delete a string from a string, but the result of strstr is not finding the string. I will try to be as clear as I can here....
The problem is strpos() is not finding $deletTabHTML. I have alerted it in ajax and it is exactly the same as a line in the commonHTML, but obviously it isn't for some reason I cannot figure out. I am assuming I am missing something 'invisible'? My script works if I hardcode the html to be deleted, so the overall script works.
here is the php:
$commonHTML = file_get_contents($url);
if (!empty($_POST['action']) && $_POST['action'] == 'deleteTab') {
$deletTabHTML = trim($_POST['theHTM']);
if(strpos($commonHTML, $deletTabHTML) !== false) {
$is_deleted="deleted";
}else{
$is_deleted="NOT deleted, ERROR:".$deletTabHTML;
}
echo '{"is_deleted":"' . $is_deleted . '"}';
return;
}
MORE INFO:
jQuery is getting an element from the dom and sending it to a php script which is opening a file and deleting the element:
<li id="contact">Contact</li>
The data returned to ajax is:
<li id="contact">Contact</li>
but for some reason it is not finding it. Thos were copied and pasted from the actual file and a javascript alert. They look exactly the same.
I hope that is enough info.
strpos is case sensitive
Try
stripos()
Aside from attempting to make the text search case insensitive, you also might want to make sure that it contains no unicode characters by using utf8_decode() on it first.
Lastly, it couldn't hurt to do some sanity checks on $_POST['theHTM'] before attempting to use it. (It looks like it's missing an L at the end, but it's also worth using isset() to verify that it actually exists.)
Related
OK, so I shave my head, but if I had hair I wouldn't need a razor because I'd have torn it all out tonight. It's gone 3am and what looked like a simple solution at 00:30 has become far from it.
Please see the code extract below..
$psusername = substr($list[$count],16);
if ($psusername == $psu_value){
$answer = "YES";
}
else {
$answer = "NO";
}
$psusername holds the value "normann" which is taken from a URL in a text based file (url.db)
$psu_value also holds the value "normann" which is retrieved from a cookie set on the user's computer (or a parameter in the browser address bar - URL).
However, and I'm sure you can guess my problem, the variable $answer contains "NO" from the test above.
All the PHP I know I've picked up from Google searches and you guys here, so I'm no expert, which is perhaps evident.
Maybe this is a schoolboy error, but I cannot figure out what I'm doing wrong. My assumption is that the data types differ. Ultimately, I want to compare the two variables and have a TRUE result when they contain the same information (i.e normann = normann).
So if you very clever fellows can point out why two variables echo what appears to be the same information but are in fact different, it'd be a very useful lesson for me and make my users very happy.
Do they echo the same thing when you do:
echo gettype($psusername) . '\n' . gettype($psu_value);
Since i can't see what data is stored in the array $list (and the index $count), I cannot suggest a full solution to yuor problem.
But i can suggest you to insert this code right before the if statement:
var_dump($psusername);
var_dump($psu_value);
and see why the two variables are not identical.
The var_dump function will output the content stored in the variable and the type (string, integer, array ec..), so you will figure out why the if statement is returning false
Since it looks like you have non-printable characters in your string, you can strip them out before the comparison. This will remove whatever is not printable in your character set:
$psusername = preg_replace("/[[:^print:]]/", "", $psusername);
0D 0A is a new line. The first is the carriage return (CR) character and the second is the new line (NL) character. They are also known as \r and \n.
You can just trim it off using trim().
$psusername = trim($psusername);
Or if it only occurs at the end of the string then rtrim() would do the job:
$psusername = rtrim($psusername);
If you are getting the values from the file using file() then you can pass FILE_IGNORE_NEW_LINES as the second argument, and that will remove the new line:
$contents = file('url.db', FILE_IGNORE_NEW_LINES);
I just want to thank all who responded. I realised after viewing my logfile the outputs in HEX format that it was the carriage return values causing the variables to mismatch and a I mentioned was able to resolve (trim) with the following code..
$psusername = preg_replace("/[^[:alnum:]]/u", '', $psusername);
I also know that the system within which the profiles and usernames are created allow both upper and lower case values to match, so I took the precaution of building that functionality into my code as an added measure of completeness.
And I'm happy to say, the code functions perfectly now.
Once again, thanks for your responses and suggestions.
I got a problem I cant solve for 7 hours now.
this is my php script for creating user on openfire server:
$f = fopen("LINK","r");
$odpoved = fread($f, 1024);
in manual http://www.igniterealtime.org/projects/openfire/plugins/userservice/readme.html is written that my variable should contain either "OK" or "UserAlreadyExistsException". When i try to print $odpoved, it show good, when i view source of that page it contain tags as written in manual. My problem is, that i cant for gods sake find a way to use this variable in switch. This is how it looks now:
switch($odpoved){
case 'OK':
print("something");
break;
case 'UserAlreadyExistsException':
print("something2");
break;
default:
print("X");
}
fclose($f);
No matter what i do, it always print default. I dont understand what is wrong with it. I tried already to compare it to options with tags too, but it didnt help and it always end up in default.
Would you kindly help me please? Thanks for any help and if needed I will provide additional details.
The server will reply to all User Service requests with an XML result page. If the request was processed successfully the return will be a "result" element with a text body of "OK". If the request was unsuccessful, the return will be an "error" element with a text body of one of the following error strings.
The output is an XML file, so what you're looking at is using an XML parser to get the result element. simplexml will load it into an array (since this xml page is small you shouldn't have to worry about performance so more complicated xml parsers aren't worth the trouble)
$output = simplexml_load_string($odpoved)
switch($output->result) //check $odpoved to make sure the XML structure matches
Or, you can also pass the url using simplexml_load_file
the output will be the same.
for more information, see: http://www.sitepoint.com/parsing-xml-with-simplexml/
Your switch statement looks fine to me. I would question the content in your variable $odpoved. Use var_dump($odpoved) to see what it contains and be sure to check for leading and trailing spaces or hidden characters (newline chars are sometimes hard to spot).
For switch statement analysis check out http://www.php.net/manual/en/control-structures.switch.php
Edit: I think %27 is actually the wrong kind of quote. I am still stuck though, I cannot find a PHP function that does the conversion I want.
Edit (again): I found a solution where I stick %26rsquo%3bs into the URL and it turns into ’. It works so I posted it as an answer below but I'd still be interested in knowing how it'd be done with PHP functions.
I'm working on a website that uses a PHP tree as if it were a directory. For example, if someone types index.php?foo=visual programming (or index.php?foo=visual%20programming) then the website opens the item "Visual Programming" (I'm using strtolower()).
Another working example would be index.php?foo=visual programming&bar=animated path finder which opens "Animated Path Finder", a child of "Visual Programming".
The problem is that some of the items are named things like "Conway’s Game of Life" which uses a HTML entity. My guess of what someone should type to open this would be index.php?foo=visual%20programming&bar=conway%27s%20game%20of%20life. The problem is that ' is not === to ’.
What do I need to do to make this work? Here is my code that selects an item based on $_GET (the PHP is inside of <script type="text/javascript">):
<?php
function echoActiveDirectory($inTree) {
// Compare $_GET with PhpTree
$itemId = 0;
foreach ($_GET as $name) {
if ($inTree->children !== null) {
foreach ($inTree->children as $child) {
if (strtolower($child->title) === strtolower($name)) {
$itemId = $child->id;
$inTree = $child;
break;
}
}
}
}
// Set jsItems[$itemId].selected(), it will be 0 if nothing was found
echo "\t\tjsItems[".$itemId."].selected();\n";
}
echo "// Results of PHP echoActiveDirectory(\$root)\n";
echoActiveDirectory($root);
?>
The website is a work in progress, but it can be tested here to see $_GET working: http://alexsimes.com/index.php
The hex code %27 (39 decimal) will never translate to ’, since it is a completely different entity (Wikipedia). It could be translated to ', but PHP doesn't do that (although I don't know the reason for that).
Edit
While there is no standard for URL-encoding multibyte character sets, PHP will treat a string as just a set of bytes, and if those match an UTF-8 sequence, it will work:
php -r 'echo htmlentities(urldecode("%E2%80%99"), ENT_QUOTES|ENT_HTML401);'
should output
’
You can use html_entity_encode() and html_entity_decode() PHP functions to convert those characters to html entities or decode them back to desired characters before comparison.
You can try the htmlentities function to convert special characters to corresponding html entity. But in your case if data is already stored in db as html entity form, the data from $_GET parameter must be first passed through htmlentities before using it in your query.
I am trying to convert a drupal installation into a front end driven by Code Igniter. This is an experimental project to check the performance boost I can get. But the biggest problem I am facing is that few fields in Drupal store php string as it is. For example
<?php print "A"; ?>
This is normal
Now I am able to see the text "This is normal" which comes from the query that I run in Code Igniter, but I don't see the php function which is saved inside the table. I can see the text when I view the record through phpmyadmin. But somehow not inside the CI query result.
I hope U've got the solution. But just in case if you haven't try this:
I created a table with two columns
//$result Contains the data fetched from the table using a model.
foreach ($result as $key=>$val) {
if($key == 'code') {
$val = str_replace('<?php','',$val); //Remove PHP's opening tag.
$val = str_replace('?>','',$val); //Remove PHP's closing tag.
$val = rtrim($val); //Remove leading and trailing spaces.
echo $key.': ';
eval($val.';'); //Execute the PHP code using eval.
} else {
echo $key.': '.$val.PHP_EOL;
}
}
I tried
echo $result['code']
print_r($result)
var_dump($result)
highlight_string($result['code'])
eval($result['code'])
and finally str_replace followed by eval($result['code']).
Check the screen shot of the result obtained from: here
There you can see that the Result produced by 1,2, and 5 are empty. But when you inspect element against the empty space It'll clearly show that the string that's echoed/print is commented out.
Screen-Shot. This is has nothing to do with codeigniter. Its done by HTML Parser.
So the solution is to remove the opening and closing tags of PHP and then use eval. I hope this helps.
Thanks for the help. Yes, the last resort was the eval function and that is the one which helped me attain which I was wanting it to do.
The data which was inside the database had PHP function and only eval function was able to treat that part as a PHP code and execute it when I was getting the data inside my view.
I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:
$string = 'Hello <?php echo 'World';?>';
echo $string;
Output
Hello
Source Code
Hello <?php echo 'World';?>
When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.
One thing to consider is that the PHP could be located anywhere in the string at any given time.
* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. *
Thanks again for any help I may receive.
$str = "Hello
<?php echo 'World';?>";
$matches = array();
preg_match('/<\?php (.+) \?>/x', $str, $matches);
eval($matches[1]);
This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.
Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.
Edit: Would need adapting with preg_replace_callback to remove the source/interpolate correctly.
You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.
Answer to the edit:
Use preg_replace_callback to get the php part, eval it, replace the input to the output, then echo it.
But. If you should eval things come from database, i'm almost sure, it's a design error.
eval() should work fine, as long as the code is proper PHP and ends with a semicolon. How about you strip off the php tag first, then eval it.
The following example was tested and works:
<?php
$db_result = "<?php echo 'World';?>";
$stripped_code = str_replace('?>', '', str_replace('<?php', '', $db_result));
eval($stripped_code);
?>
Just make sure that whatever you retrieve from the db has been properly sanitized first, since you're essentially allowing anyone who can get content into the db, to execute code.