php foreach results - php

foreach ($flr_array as $flr) {
if (!($flr = trim($flr)))
continue;
//list($flr, $keyword) = explode('|', $flr, 2);
$ip = '';
$err_msg = isValidFLR($flr, $ip);
if (!$err_msg) {
list($randlink, $lastid, $scr) = addLink($flr, $ip);
$flr = stripslashes($flr);
$url_array[$i]['number'] = $i + 1;
$url_array[$i]['flr'] = $flr;
$url_array[$i]['flr_substr'] = (strlen($flr) > 33) ? substr($flr, 0, 33) . '...' : $flr;
$url_array[$i]['randlink'] = $randlink;
$url_array[$i]['fullrand'] = $config['indexurl'] . $config['mod_rewrite_char'] . $randlink;
$url_array[$i]['scr'] = $scr;
$url_array[$i]['id'] = $lastid;
$url_array[$i]['flr_length'] = strlen($flr);
$url_array[$i++]['randlink_length'] = strlen($config['indexurl'] . $config['mod_rewrite_char'] . $randlink);
////
//$smarty->assign("flr_length", strlen($_REQUEST['flr']));
//$smarty->assign("randlink_length", strlen($config['indexurl'] . $config['mod_rewrite_char'] . $randlink));
////
} else {
js_alert($err_msg);
}
}
In function isValidFLR these is part of captcha check:
if ($config['captcha_check']) {
if (verifyCaptcha() == false) {
return 'Wrong code!';
}
}
Let's say in textarea i enter:
google.com
google.de
google.net
and enter wrong captcha code, so it gives me 3 messages of Wrong code!
It's happen i think because of foreach. Any ideas how to make in foreach display only one error message ?

Your question is hard to understand but I think you are right (in the foreach)....
if err_msg <> '' then you should put a break in your code to get out of the foreach (if that is what you want).

else {
js_alert($err_msg);
break; //this will break out of for loop
//or return false if it a function
}

Related

Problem reading RSS feed programmatically using PHP

I have a newsfeed link from an Indian newspaper as follows:
https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml
I am trying to extract some information from it using PHP and simpleXML
$feedURL="https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml";
$array = get_headers($feedURL);
$statusCode = $array[0];
echo('<br>'.$statusCode.'<br>');
if (strpos($statusCode, "404")==FALSE) {
echo('Reading ' . $feedURL . '<br>');
$out = htmlspecialchars(file_get_contents($feedURL), ENT_QUOTES);
echo($out);
if (stripos($out, "<feed ") != FALSE) {
$feedType = 'ATOM';
$countATOM += 1;
} else if (stripos($out, "<rss") != FALSE) {
$feedType = 'RSS';
$countRSS += 1;
} else {
$feedType = 'UNREADABLE';
$countUNREADABLE += 1;
}
echo('<br>' . $feedType . '<br>');
echo('<br>-------------------------------------------------------------------------<br>');
if ($feedType == 'ATOM') {
$xmlOut = simplexml_load_string(file_get_contents($feedURL));
echo($xmlOut.'<br>-------------------------------------------------------------------------<br>');
if ($xmlOut === false) {
echo("Failed loading XML: ");
foreach (libxml_get_errors() as $error) {
echo ("<br>" . $error->message);
}
} else {
foreach ($xmlOut->entry as $entry) {
if (isset($xmlOut->entry->title) && isset($xmlOut->entry->link) && isset($xmlOut->entry->updated) && isset($xmlOut->entry->summary)){
$title=$xmlOut->entry->title;
$link=$title=$xmlOut->entry->link['href'];
$updated=$xmlOut->entry->updated;
$summary=$xmlOut->entry->summary;
if(isImportantNews($title) || isImportantNews($summary)){
$insertNewsCmd=$insertNewsCmd
."('".$link."',"
."'".stripSpecialChars($title)."',"
."'".setDate($updated)."'),";
}
}
echo($entry->updated . "<br>");
}
}
} elseif ($feedType == 'RSS') {
$xmlOut = simplexml_load_string(file_get_contents($feedURL));
print_r($xmlOut);
echo('<br>-------------------------------------------------------------------------<br>');
if ($xmlOut === false) {
echo("Failed loading XML: ");
foreach (libxml_get_errors() as $error) {
echo ("<br>" . $error->message);
}
} else {
foreach ($xmlOut->channel->item as $item) {
if (isset($item->title) && isset($item->link) && isset($item->description) && isset($item->pubDate)) {
$title = $item->title;
$link = $item->link;
$descr = $item->description;
$pubDate = $item->pubDate;
echo($title.'<br>'.$link.'<br>'.$descr.'<br>');
echo('<br>-------------------------------------------------------------------------<br>');
if(isImportantNews($title) || isImportantNews($descr)){
$insertNewsCmd=$insertNewsCmd
."('".$link."',"
."'".stripSpecialChars($title)."',"
."'".setDate($pubDate)."'),";
}
echo($entries->pubDate. "<br>");
}
}
}
} else {
continue;
}
break;
} else {
echo($feedURL . ' encountered problems being read...' . '<br>');
}
Basically what I am doing in the program is that I am using the above link (after determining if it is ATOM or RSS) to extract the news summary and description and determine if it is important news using the isImportantNews() method. If so, I store it in a database.
My problem is that if I open the above link in a browser directly, I can get to see the information without any issues but trying to read it using the above code returns a HTTP 403 Forbidden status code
Why is this happening and is there a way to get around this issue? Being able to open it directly tells me that the 403 maybe coming up due to programatic access attempt (?) But I am not certain about it. I also tried the following ways to read it with the same expected failure
echo('read file ####################################################################################################');
echo readfile("https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml"); //needs "Allow_url_include" enabled
echo('<br>include ####################################################################################################');
echo include("https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml"); //needs "Allow_url_include" enabled
echo('<br>file get contents ####################################################################################################');
echo file_get_contents("https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml");
echo('<br>stream get contents####################################################################################################');
echo stream_get_contents(fopen('https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml', "r")); //you may use "r" instead of "rb" //needs "Allow_url_fopen" enabled
echo('<br>get remote data ####################################################################################################');
echo get_remote_data('https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml');
$feedURL = "https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml";
$out = htmlspecialchars(file_get_contents($feedURL), ENT_QUOTES);
echo($out);
Any help or insight would be most appreciated.

Javascript confirm() function cannot pass parameters properly

I'm using PHP and JavaScript, and I got a problem when deal with the confirm() function in JavaScript.
Say I have a page add.php, firstly I receive some parameters passed from another page, and I check to see if they are valid or not. If yes, I just insert the data into db and return to another page, if they are not valid, there'll be a confirm() window popped up and let the user to choose whether to continue or not. If the user still choose to continue, I want the page to be reloaded with all the parameters sent again. But the problems is that I cannot get the parameter the second time add.php is loaded.
Previously I didn't use a window.onload function and confirm() pop up, but an < a href> link instead, everything worked fine (Please see the attached code at the end). But when I tried to use the following code, the same url stopped working
echo "<script type=\"text/javascript\">";
echo "window.onload = function() {
var v = confirm(\"$name is not alive, do you want to add it into system?\");
if (v) {
window.location.href= \"add.php?type=room&name=$name&area\"
+ \"=$area&description=$description&\"
+ \"capacity=$capacity&confirm=Y\";
} else {
window.location.href= \"admin.php?area=$area\";
}
}";
echo "</script>";
Following is the previous version, instead of using window.onload(), I used < a href="..." /> link, everything worked fine at that time. get_form_var is a function in functions.inc, which is to get the parameter using $_GET arrays.
<?php
require_once "functions.inc";
// Get non-standard form variables
$name = get_form_var('name', 'string');
$description = get_form_var('description', 'string');
$capacity = get_form_var('capacity', 'string');
$type = get_form_var('type', 'string');
$confirm = get_form_var('confirm','string');
$error = '';
// First of all check that we've got an area or room name
if (!isset($name) || ($name === ''))
{
$error = "empty_name";
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location: $returl");
}
// we need to do different things depending on if its a room
// or an area
elseif ($type == "area")
{
$area = mrbsAddArea($name, $error);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location: $returl");
}
elseif ($type == "room")
{
if (isset($confirm)){
$dca_osi = getOsiVersion($name);
$room = mrbsAddRoom(
$name,
$area,
$error,
$description,
$capacity,
$dca_osi,
1
);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location:$returl");
}
else {
$dca_status= pingAddress($name);
$dca_osi = getOsiVersion($name);
if( $dca_status == 0){
$room = mrbsAddRoom(
$name,
$area,
$error,
$description,
$capacity,
$dca_osi,
0
);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location:$returl");
}
else {
print_header(
$day,
$month,
$year,
$area,
isset($room) ? $room : ""
);
echo "<div id=\"del_room_confirm\">\n";
echo "<p>\n";
echo "$name is not alive, are you sure to add it into system?";
echo "\n</p>\n";
echo "<div id=\"del_room_confirm_links\">\n";
echo "<a href=\"add.php?type=room&name"
. "=$name&area=$area&description"
. "=$description&capacity=$capacity&confirm"
. "=Y\"><span id=\"del_yes\">"
. get_vocab("YES") . "!</span></a>\n";
echo "<a href=\"admin.php?area=$area\"><span id=\"del_no\">"
. get_vocab("NO") . "!</span></a>\n";
echo "</div>\n";
echo "</div>\n";
}
}
}
function pingAddress($host)
{
$pingresult = exec("/bin/ping -c 1 $host", $outcome, $status);
if ($status==0) {
return $status;
}
else {
return 1;
}
}
function getOsiVersion($host)
{
$community = 'public';
$oid = '.1.3.6.1.4.1.1139.23.1.1.2.4';
$sysdesc = exec("snmpwalk -v 2c -c $community $host $oid");
$start = strpos($sysdesc, '"');
if ($start!==false) {
$sysdesc = substr($sysdesc, $start+1,$sysdesc.length-1);
return $sysdesc;
}
else {
return "not available";
}
}
I've solved the problem, just simply by using "&" instead of " & amp;" in the url link... it works fine now...
You try location.reload() javascript call?

read file with ip range and see if supplied IP matches any range in file

I am trying to read a file with ip/mask ranges and if the supplied IP matches any range in the file it will return with TRUE or similar function. Here is the code I have below
function myip2long($ip) {
if (is_numeric($ip)) {
return sprintf("%u", floatval($ip));
} else {
return sprintf("%u", floatval(ip2long($ip)));
}
}
function ipfilter($ip) {
$match = 0;
$ip_addr = decbin(myip2long($ip));
if (file_get_contents('./countryip/all-zones/us.zone')) {
$source = file('./countryip/all-zones/us.zone');
foreach ($source as $line) {
$network = explode("/", $line);
$net_addr = decbin(myip2long($network[0]));
$cidr = $network[1];
if (substr($net_addr, 0, $cidr) == substr($ip_addr, 0, $cidr)) {
$match = 1;
break;
}
}
}
return $match;
}
$user_ip = $_SERVER['REMOTE_ADDR'];
if (ipfilter($user_ip) == 1) echo "<br />allowed! Your IP is a United States IP!";
else echo "deny!";
An example file (like the one in the example above) is available here
http://www.ipdeny.com/ipblocks/data/countries/us.zone
Not sure if the code above is correct, I got it from here'
http://www.php.net/manual/en/function.ip2long.php#86793
Probably you should add some debug code, just to understand what is going on.
Just like this:
if (substr($net_addr, 0, $cidr) == substr($ip_addr, 0, $cidr)) {
echo "My IP: $ip\n";
echo "IP to check: $network[0]\n";
echo "CIDR: $cidr\n"
echo "ip digits, my: $ip_addr, check: $net_addr\n";
$match = 1;
break;
}
So you'll see what is going wrong.

if else simple beginner issue

Good day guys,
I've made a sweet favorites function with php mysql and ajax, and its working great. Now I want to show 'favorite' when favorite = 0 and show 'unfavorite' when favorite = 1
if ($favorites == 0) {
$favorite = 'Favorite';
}
if ($favorites == 1) {
$unfavorite = 'unFavorite';
}
and echo it in the row as :
<div id="favorites">' .($favorite). ' ' .($unfavorite). '</div>
The problem is: when favorite = 0, both $favorite and $unfavorite are being shown. When favorite = 1 only $unfavorite is being shown correctly. Of course it should be $favorite OR $unfavorite. I assume the problem is clear and simple to you, please assist :)
Thanks in advance
It's easier to use just one variable:
$text = ''
if ($favorites == 0) {
$text = 'Favorite';
} else {
$text = 'unFavorite';
}
...
echo $text;
If you want to check $favorite, you are using the wrong variable in your control statement. Also, it is better coding practice to use elseif rather than if for that second if. One more thing: it's easier to manage one resulting variable.
$output = "";
if ($favorite == 0) {
$output = 'Favorite';
}
elseif ($favorite == 1) {
$output = 'unFavorite';
}
...
echo $output; // Or whatever you want to do with your output
Is $favorites an integer?
Anyway try using three equal signs (===) or else instead of the second if:
if ( $favorites === 0 )
{
// ...
}
else // or if ($favorites === 1)
{
// ...
}
You're making a toggle, so you only need one variable:
if(empty($favourites)){
$fav_toggle = 'Favorite';
} else {
$fav_toggle = 'unFavorite';
}
echo $fav_toggle;
Same code is working on me if I assigned $favorites = 0; or $favorites = 1;
You can also use if else
$favorites = 1;
if ($favorites == 0) {
$favorite = 'Favorite';
}
else if ($favorites == 1) {
$unfavorite = 'unFavorite';
}

Add substr max length to my function

Below is a code snippet from the file I am working with. I will start by saying I have attempted to find out on my own many times with failure, I am not a coder but I wish I knew more. I need some help figuring out how to add a substr length to the string $forum
This function outputs the latest 5 forum topics. The problem I'm having is the topic titles are to long for where the widget is being placed, so I wanted to truncate it to max 35 characters displayed. Can you help me? I know I'm a newb!
function sf_recent_posts_tag($limit=5, $forum=false, $user=true, $postdate=false, $listtags=true, $forumids=0, $posttime=false, $avatar=false, $size=25)
{
global $wpdb, $current_user, $sfvars;
$limit = sf_esc_int($limit);
if (empty($limit)) return;
sf_initialise_globals($sfvars['forumid']);
$out = '';
$forum_ids = '';
# are we passing forum ID's?
if ($forumids != 0)
{
$flist = explode(",", $forumids);
foreach($flist as $thisforum)
{
if (sf_can_view_forum($thisforum))
{
$forum_ids[] = $thisforum;
}
}
} else {
# limit to viewable forums based on permissions
if($current_user->forumadmin == false)
{
$allforums = sf_get_forum_memberships($current_user->ID);
if ($allforums)
{
foreach ($allforums as $thisforum)
{
if (sf_can_view_forum($thisforum->forum_id))
{
$forum_ids[] = $thisforum->forum_id;
}
}
} else {
return '';
}
}
}
# get out if nothing to see
if($current_user->forumadmin == false && empty($forum_ids)) return '';
# create where clause based on forums that current user can view
if ($forum_ids != '')
{
$where = ' AND '.SFPOSTS.".forum_id IN (" . implode(",", $forum_ids) . ") = 1 ";
} else {
$where = '';
}
$sfposts = $wpdb->get_results("SELECT DISTINCT topic_id
FROM ".SFPOSTS."
WHERE post_status = 0 ".$where."
ORDER BY post_id DESC
LIMIT ".$limit);
if($sfposts)
{
foreach($sfposts as $sfpost)
{
$postdetails = sf_get_last_post_in_topic($sfpost->topic_id);
$thisforum = sf_get_forum_record($postdetails->forum_id);
$p=false;
# Start contruction
if($listtags) $out.="<li class='sftagli'>\n";
if ($avatar)
{
if ($postdetails->user_id)
{
$icon = 'user';
if (sf_is_forum_admin($postdetails->user_id)) $icon='admin';
} else {
$icon = 'guest';
}
$out.= sf_render_avatar($icon, $postdetails->user_id, sf_filter_email_display($postdetails->user_email), sf_filter_email_display($postdetails->guestemail), false, $size);
}
$out.= sf_get_topic_url_newpost($thisforum->forum_slug, $sfpost->topic_id, $postdetails->post_id, $postdetails->post_index);
if($forum)
{
if ($p == false) $out.="<p class='sftagp'>";
$out.= __("posted in forum", "sforum").' '.sf_filter_title_display($thisforum->forum_name)." "."\n";
$p=true;
}
if($user)
{
if($p == false) $out.="<p class='sftagp'>";
$poster = sf_build_name_display($postdetails->user_id, sf_filter_name_display($postdetails->display_name));
if(empty($poster)) $poster = sf_filter_name_display($postdetails->guest_name);
$out.=__("by", "sforum").' '.$poster.' '."\n";
$p=true;
}
if($postdate)
{
if($p == false) $out.="<p class='sftagp'>";
$out.=__("on", "sforum").' '.sf_date('d', $postdetails->post_date)."\n";
if ($posttime)
{
$out.=' '.__("at", "sforum").' '.sf_date('t', $postdetails->post_date)."\n";
}
$p=true;
}
if($p) $out.="</p>\n";
if($listtags) $out.="</li>\n";
}
} else {
if($listtags) $out.="<li class='sftagli'>\n";
$out.='<p>'.__("No Topics to Display", "sforum").'</p>'."\n";
if($listtags) $out.="</li>\n";
}
echo($out);
return;
}
I can't find where you get the post titles in your code, but to truncate a string to 35 chars you simply need something like $truncated = substr($title, 0, 35)
You may find it helpful to append '...' to the truncated titles:
$truncated = substr($title, 0, 35).'...';
EDIT:
without seeing a lot of code that you have omitted it's hard to say, but I suspect it's a matter of changing
$out.= sf_get_topic_url_newpost($thisforum->forum_slug, $sfpost->topic_id, $postdetails->post_id, $postdetails->post_index);
to
$out.= substr(sf_get_topic_url_newpost($thisforum->forum_slug, $sfpost->topic_id, $postdetails->post_id, $postdetails->post_index), 0, 35).'...';

Categories