I am using PHP DOMNode hasAttributes to retrieve all of the elements' attributes. So far, everything is working great. My code is below. However, this line else if($imageTags->hasAttributes() == false) is where I can't get it to work, it displays error on my page instead redirecting the user to index php when code failed to work. What I really want is if ($imageTags->hasAttributes() == true) does not equal TRUE. Redirect the user to index.php and don't display the errors instead.
function get_iframe_attr($string){
$doc = new DOMDocument();
$doc->loadHTML("$string");
$imageTags = $doc->getElementsByTagName('iframe')->item(0);
if ($imageTags->hasAttributes() == true) {
foreach ($imageTags->attributes as $attr) {
$name = $attr->nodeName;
$value = $attr->nodeValue;
$attr_val[] = "$name=\"$value\" ";
}
echo $implode_str = implode(" ", $attr_val);
}else if($imageTags->hasAttributes() == false){
header("Location: index.php");
}
}
get_iframe_attr('<iframe src="" scrolling="no" width="600" height="438" marginheight="0" marginwidth="0" frameborder="0"></iframe>');
Note: if you remove the '<iframe' tags on the string. You will get the error
...
} else if($imageTags->hasAttributes() == false){
header("Location: index.php");
die; // needed here to prevent code below, if any from executing
}
...
also on your edit note about removing iframe and getting error, you need to check if $doc->getElementsByTagName('iframe') has actually grabbed anything, example:
$imageTags = $doc->getElementsByTagName('iframe')
if ($imageTags->length > 0) {
$imageTags = $imageTags->item(0);
...
Instead of using $imageTags->hasAttributes() I solved it by using $imageTags instanceof DOMNode
Related
im trying to check two variables in a url, U and TAG. i keep getting whitescreen or no results. i want to check U and the preg replace works and everything, but! i also want to check the variable TAG to make sure it isnt blank, and if it is blank then go to website.com
here is a url
http://www.website.com/hashtag.php?u=frank&tag=#my
here is the code
if(isset($_GET["u"]))
{
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
header("location: http://www.website.com");
exit();
}
if (isset($_GET['tag']) && $tag == "")
{
header("location: http://www.website.com");
exit();
}
f (isset($_GET['tag']) && $tag == "")
-> $tag isn't an existing var for now, if you want to call $tag you should previously do :
$tag = $_GET['tag'];
I've been having an issue getting one PHP statement to work with WordPress.
Basically, what I want is this:
Return an output based on user selection
Now I have managed to get most of my stuff working, but when I try to return PHP code from my plugin to wordpress it gets commented out straightaway.
This is my code for the function I'm using.
function display($type, $status) {
$html ='';
if($type == null) {
$html = "<?php echo do_shortcode[contact-form-7 id='7' title='Campaign monitor']');?>";
}else if($type == "ios") {
if ($status == "y")
$html = "IOS";
}else if($type == "android") {
if ($status == "y")
$html = "ANDROID";
}
echo $html;
}
So as you can see depending on what is picked e.g.
<?php echo display(ios, y); ?>
It displays the IOS on my website, however things get interesting when the type is null e.g.
<?php echo display(); ?>
This returns the following
<!--?php echo do_shortcode[contact-form-7 id='7' title='Campaign monitor']');?-->
Straightaway my PHP is commented out and I can't do anything to get it working.
Although, I do understand it's not the best practise to do it this way (by returning raw php) I have no other way to do it.
Is there anyway to overcome this issue?
I have tried EXEC-PHP plugin as well as PHP Code for Posts and Pages plugins.
not really sure what the effect you want is but you were saving a string into html from your do_shortcode. I assume you are confusing php resolving variables inside double quotes with functions being resolved. Not so. This should be what you are looking for.
function display($type, $status) {
$html ='';
if($type == null) {
$html = do_shortcode('[contact-form-7 id="7" title="Campaign monitor" ]');
}else if($type == "ios") {
if ($status == "y")
$html = "IOS";
}else if($type == "android") {
if ($status == "y")
$html = "ANDROID";
}
echo $html;
}
Try this, as it helps cut down on code, and helps the function be a bit more clear. It assumes that if the device type is not listed above, that you want to display the default case. It assumes that if your device is not listed, in this case, anything other than android and ios, that it should display the default case, which is your CF7 shortcode. IF you want to specify other options, they need to be done ABOVE 'default'. As stated in comments elsewhere, this is PHP, so it's server-side processing..
<?php
function display($type, $status){
switch ($type){
case "ios":
$html = "IOS";
break;
case "android":
$html = "Android";
break;
default:
$html = "do_shortcode[contact-form-7 id='7' title='Campaign monitor']";
break;
}
if($status == "active"){
echo $html;
}
}
?>
Having one of those brain fade moments this morning. I have the following php:
$imgset = $result->fields[6];
if ($imgset = '')
{
$imgset = 'logo';
}
else
{
$imgset = $result->fields[6];
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
$imgset = '';
Where it looks to see if the result from the database is blank and if so, should put in logo.jpg instead of whatever the result is. For some reason though, it just does not want to work and I am probably being completely blind, but cannot see why not. I still get blank images in the HTML and filenames of "/img/.jpg" as though $imgset is still passing through a blank. The values are not NULL in the SQL either, they are most definitely blank entries inputted from an inputbox using a _POST in a form elsewhere.
This:
if ($imgset = '') {
Is always setting $imgset to empty. Use comparison instead:
if ($imgset == '') {
Your else is also not needed since in that case $imgset is already set as $result->fields[6];.
Try to verify if the image exists in your path as well
<?php
$imgset = $result->fields[6];
if ($imgset) {
$imgset = $result->fields[6];
$path ='pathtoimages';
if(!file_exists($path.'/'.$imageset.'.jpg'){
$imgset = 'logo';
}
}
else
{
$imgset = 'logo';
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
?>
You forgot to compare on the if condition and instead you are assigning an empty value to $imgset. if ($imgset = '') should be if ($imgset == '')
$imgset = $result->fields[6];
if ($imgset == '')
{
$imgset = 'logo';
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
$imgset = '';
you do not need the else part as the value is already assigned in the first statement.
Using a ternary operator it can be done like this:
echo '<img id="imgdisp" src="/img/'.(empty($imgset)?'logo':$imgset).'.jpg" />';
Shorter code at the cost of readability.
This is the reason why it's better to reverse the condition:
if ('' = $imgset)
would have lead to an error.
The answer:
if ('' == $imgset)
//or
if (empty($imgset))
If you are selecting from MYSQL, you can use something like
SELECT *,COALESCE(image,"logo") AS image FROM ....
This way when the results come back and some rows have a NULL image, it will be replaced by "logo" so you don't need the IF logic in your PHP :)
I am trying to make a script to check if a webpage has a back link to my page. I have found this script but the problem is that it returns the error message "No back link found" even if there is a backlink. Could someone tell me what is wrong with this script?
Here is the script I am using:
require('simple_html_dom.php');
function CheckReciprocal( $targetUrl, $checkLinkUrl, $checkNofollow = true )
{
$html = file_get_html($targetUrl);
if (empty($html))
{
//# Could not load file
return false;
}
$link = $html->find('a[href^='.$checkLinkUrl.']',0);
if (empty($link))
{
//# Link not found
return false;
}
if ( $checkNofollow && $link->hasAttribute('rel') )
{
$attr = $link->getAttribute('rel');
return (preg_match("/\bnofollow\b/is", $attr) ? false : true);
}
return true;
}
$targetUrl = 'http://example.com/test.html';
$checkLinkUrl = 'http://mysite.com';
if ( CheckReciprocal($test, $checkLinkUrl) )
{
echo 'Link found';
}
else { echo 'Link not found or marked as nofollow'; }
Thank you!
I don't know how does that simple_html_dom.php's $html->find() works cos never used it, but it seems that your problem is there. I would trust the good ol' DOMDocument + regex.
Just wrote a function and tested it, just use on the $url the plain domain + whatever you want, don't worry about the http(s) or www and stuff like that:
function checkBackLink($link, $url, $checkNoFollow = true){
$dom = new DOMDocument();
$dom->loadHTMLFile($link);
foreach($dom->getElementsByTagName('a') as $item){
if($checkNoFollow){
if(preg_match('/nofollow/is', $item->getAttribute('rel'))) continue;
}
if($item->hasAttribute('href') === false) continue;
if(preg_match("#^(https?\://)?(www\.)?$url.*#i", $item->getAttribute('href'))) return true;
}
}
if(checkBacklink('the link', 'example.com')){
echo "link found";
} else {
echo "Link not found or marked as nofollow";
}
If you don't like it and still want to use the simple_html_dom just make sure how that find() works, because if it only match exact values that could be troublesome.
I have created a piece of code that checks files for a user-submitted string within a set of files. The code searches a directory, returns the file, then searches for the string in the file. The user will input the custom string through an input field and then clicking a submit button.
I have successfully been able to create a condition where, if the user does not enter any information, the output will say, "Your search produced no results". However, I have not been able to figure out how to create a condition where, if the user enters a string that isn't found within the files, that the output will also be, "Your search produced no results".
The code for the existing conditional I have as of now is this:
if ((isset($query)) && (empty($query))) {
echo "Your search produced no results";
}
The code that searches for the files and also searches for the string is found here (this is the entire PHP file, actually, and it includes the conditional I posted above.) I need help on how to create another conditional that throws a message if the user-input isn't found in any of the files.
If this seems unclear, I apologize and will clarify any information you need if you think it will help.
Calling Code
$query = $_POST['query'];
if ((isset($query)) && (empty($query))) {
echo "Your search produced no results.";
}
else {
find_files('.');
}
find_files()
function find_files($seed)
{
if (! is_dir($seed))
return false;
$files = array();
$dirs = array($seed);
while(NULL !== ($dir = array_pop($dirs)))
{
if($dh = opendir($dir))
{
while( false !== ($file = readdir($dh)))
{
if($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if (is_dir($path)) {
$dirs[] = $path;
}
else {
if (preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path)) {
check_files($path);
}
}
}
}
closedir($dh);
}
}
check_files()
function check_files($this_file)
{
$query = $_POST['query'];
$str_to_find = $query;
if(!($content = file_get_contents($this_file))) {
echo("Could not check $this_file");
}
else {
if (stristr($content, $str_to_find)) {
echo("$this_file -> contains $str_to_find");
}
}
unset($content);
}
If the query is not empty the find_files function is simply executed with no instructions of doing something if it returns false, hence you need to evaluate the result of calling find_files. For example you could do:
if ((isset($query)) && (empty($query))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
elseif (!find_files('.'))
{
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
with the condition that you update you find_files function to return false for all cases that fail.
or you could update the find_files function to return a string in case of errors and a string empty for succesful execution
if ((isset($query)) && (empty($query))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
else
{
$result = find_files('.');
if (!empty($result))
{
echo "<p style=\"color:darkgray; font-family:arial\">".$result."</p>";
}
}
A couple of notes regarding your code that will improve the readability and code quality:
proper indentation will save a lot of time spent in maintenance;
when using if else imbrications ALWAYS use curly braces even if it is only one instructions. Improves readability and avoids errors.
when accessing a variable declared outside a function (in procedural code) use global keyword. For example for accessing the query variable inside the check_files function use global $query; instead of retrieving the variable again from the post.
use $_REQUEST instead of $_POST or $_GET unless there is a special reason for doing otherwise. Unifies code, makes for more readable code and changing from GET to POST or vice-versa can be done without changing code.
You may make your find_files function to return a boolean value: true if at least one matching file was found, false otherwise. Then update your if condition:
if ((isset($query)) && (empty($query)) && !find_files('.')) {
echo "<p style=\"color:darkgray...";
}
Because && is lazily evaluated, find_files will be called only if $query isn't empty.