PHP mysql check inside a function - php

I have a function (which I did not write) inside an existing php tag in the head of a page that I've been using for several years the parses URL's and email addresses to make them clickable links:
function ParseURLs($str){
if(isset($str)){
$Output=strip_tags($str);
$Output=preg_replace("/(\swww\.)|(^www\.)/i"," http://www.",$Output);
$Output=preg_replace("/\b(((ftp|http(s?)):\/\/))+([\w.\/&=?\-~%;]+)\b/i"
,"<a href='$1$5' target='_blank' rel='nofollow'>$1$5</a>",$Output);
$Output=preg_replace("/\b([\w.]+)(#)([\w.]+)\b/i"
, "<a href='mailto:$1#$3'>$1#$3</a>",$Output);
return nl2br($Output);
}
}
I wanted to replace the rel='nofollow' with a php check of a MySQL dbase field and have it only put up the rel='nofollow' if the dbase field is empty. I tried to do it by replacing rel='nofollow' in the function with something like this which was my starting point:
<?php if (empty( $row_rswhatever['linkfollow'])) {echo "rel='nofollow'";}?>
or just this:
if (empty( $row_rswhatever['linkfollow'])) {echo "rel='nofollow'";}
I've tried it a hundred different ways (something good usually happens sooner or later) but cannot get it to work. I know from past experience that I am probably missing the boat on more than one issue, and would appreciate any help or guidance. Thanks.

A easy/lazy way to do it would be to continue doing it as you are doing now, however after the last $output=preg_replace add your if test and if you don't want the rel='nofollow', just use str_replace to remove it.
ie.
function ParseURLs($str)
{
if(isset($str)){
$Output=strip_tags($str);
$Output=preg_replace("/(\swww\.)|(^www\.)/i"," http://www.",$Output);
$Output=preg_replace("/\b(((ftp|http(s?)):\/\/))+([\w.\/&=?\-~%;]+)\b/i","<a href='$1$5' target='_blank' rel='nofollow'>$1$5</a>",$Output);
$Output=preg_replace("/\b([\w.]+)(#)([\w.]+)\b/i", "<a href='mailto:$1#$3'>$1#$3</a>",$Output);
if (empty( $row_rswhatever['linkfollow'])) {
$Output = str_replace(" rel='nofollow'", "", $Output);
}
return nl2br($Output);
}
}

Without knowing exactly what you'd be checking for in the database:
function ParseUrls($str) {
$sql = "SELECT ... FROM yourtable WHERE somefield='" . mysql_real_escape_string($str) ."'";
$result = mysql_query($sql) or die(mysql_error());
$rel = (mysql_num_rows($result) == 0) ? ' rel="nowfollow"' : '';
blah blah blah
}
Incidentally, the isset check is useless in your code. The function parameter does not have a default value (function x($y = default)), so if no parameter is specified in the calling code, it will cause a fatal error in PHP anyways.
This also assumes that you've already connected to MySQL elsewhere in your code, and are using the mysql library (not mysqli or pdo or db or whatever else).

Related

get all categories listing from database

Main purpose is to get all categories listing from database by passing variables to url and show it to the main page.here i have omitted some code bt i tried to clarify.
1.can I exclude encodeHtml() method, too difficult for me to understand
2.i am not getting specially this part of code and having my head for 4 days
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";//here id is 'category id' from database. this full line will echo what?
echo Helper::getActive(array('category' => $cat['id']));//it will output what ?
echo ">";
echo Helper::encodeHtml($cat['name']);//as from ur answer can we omit encodeHTML() method and use htmlspecialchars($cat['name']); instead ?
echo "</a>
3.any easier solution will be more appreciated
in our database we have 'id' and 'name' of catagory listing
please check below for reference
/*below is the code in header section of template */
<?php
$objCatalogue = new Catalogue();// creating object of Catalogue class
$cats = $objCatalogue->getCategories(); // this gets all categories from database
<h2>Categories</h2>
<?php
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";
echo Helper::getActive(array('category' => $cat['id']));
echo ">";
echo Helper::encodeHtml($cat['name']);
echo "</a></li>";
}
?>
/*below is the helper class which is Helper.php */
public static function getActive($page = null) {
if(!empty($page)) {
if(is_array($page)) {
$error = array();
foreach($page as $key => $value) {
if(Url::getParam($key) != $value) //getParam takes name of the parameter and returns us the value by $_GET
{
array_push($error, $key);
}
}
return empty($error) ? " class=\"act\"" : null;
}
}
//CHECK THIS LINE BROTHER
return $page == Url::currentPage() ? " class=\"act\"" : null;// url::currentPage returns the current page but what is 'class =act ' :(
}
public static function encodeHTML($string, $case = 2) {
switch($case) {
case 1:
return htmlentities($string, ENT_NOQUOTES, 'UTF-8', false);
break;
case 2:
$pattern = '<([a-zA-Z0-9\.\, "\'_\/\-\+~=;:\(\)?&#%![\]#]+)>';
// put text only, devided with html tags into array
$textMatches = preg_split('/' . $pattern . '/', $string);
// array for sanitised output
$textSanitised = array();
foreach($textMatches as $key => $value) {
$textSanitised[$key] = htmlentities(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
}
foreach($textMatches as $key => $value) {
$string = str_replace($value, $textSanitised[$key], $string);
}
return $string;
break;
}
}
Firstly, in your URL (/?page=catalogue&category=) you don't need to put &, as this is an HTML entity for actually displaying an ampersand in a web page. Just use /?page=catalogue&category=.
Secondly, you can use urlencode() to prepare strings for sending in the URL, and urldecode() on the other end.
In answer to your first point you just need to make sure that ANYTHING from the user (whether via $_POST or $_GET) is sanitized, prior to being used in code, output to a web page, or used in database queries. Use htmlspecialchars() for cleaning before outputting to a web page, and prepared statements prior to entering user input into a query.
In answer to your second point please read the documentation in the links I have provided above. Just reading the documentation on htmlspecialchars() will help you a lot.
Hope this helps.
Alright then.
<?php
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";
echo Helper::getActive(array('category' => $cat['id']));
echo ">";
echo Helper::encodeHtml($cat['name']);
echo "</a></li>";
}
?>
Im just going to kindof skim through it, because honestly if you really want to learn all this you should probably google the shit out of every piece of code you don't understand, it's the way we all learn things.
< ?php announces some php script to follow. And as you can see, there does follow some php code after.
foreach is a way of getting each element from an array or list and doing something to that element.
echo sends whatever string comes after it to the page, or whatever is listening to its output. In this case, it looks like the echo's are printing some <li> list item with an <a> anchor in it.
Helper::getActive(): Helper is some class that is defined somewhere, :: is syntax for calling a static function that belongs to the class (Helper in this case). getActive is the function name.
array('category' => $cat['id'] is a piece of code that creates an array with 1 element in it, being one with key 'category' and a value of whatever is in $cat['id'].
By looking at getActive: it looks like it's a function that checks the url for some value so it can determine which page to display. It also checks if the url contains errors.
By lookingat encodeHtml(): it looks like it's a function that makes sure that whatever text you're trying to put on the screen, isn't something that could cause harm. In some situations, people will try to make your server print javascript that could harm the user (by sending personal data to somewhere). The encodeHtml() will ensure that no such thing can be done by stripping certain characters from the text you're about to send to the page.
USE GOOGLE.

Get attribute with file_get_contents PHP

I have a sql query that I store in a variable and I displayed. I get the contents of this with file_get_contents from another file, I would like to recover some of this code (which is html) in order to make link. More precisely retrieve the id.
My api.php
$base = mysql_connect ('localhost','root','');
mysql_select_db('administrations', $base);
if(isset($_GET['cp']))
{
$sql = 'SELECT NOM_organisme, ID_organisme
FROM organismes
WHERE code_postal LIKE "%'.$_GET['cp'].'%"
ORDER BY NOM_organisme;';
$req = mysql_query($sql) or die('SQL Error !<br>'.$sql.'<br />'.mysql_error());
}
while ($data = mysql_fetch_array($req))
{
echo '<p id="'.$data['ID_organisme'].'"'.
$data['NOM_organisme'].'</br>'.
$data['ID_organisme'].'</p></br>';
}
I want to get the id="I WANT THIS".
And my index.php (part of my code that retrieves the contents).
if(isset($_POST['cp']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_POST['cp'];
$var = file_get_contents($api);
echo $var;
}
How can I get the id="" in my index.php ?
please look at php get documentation. you need to link to your script with url parameters and access them in your php code.
http://php.net/manual/en/reserved.variables.get.php
echo ''.$data['NOM_organisme'].'</br>'.$data['ID_organisme'].'</br>';
php
if(isset($_GET['id']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_GET['id'];
$var = file_get_contents($api);
echo $var;
}
if you dont want to use url parameter you can use post values
http://php.net/manual/en/reserved.variables.post.php
I understand what your trying to do, but dont find it logical without knowing the purpose of this tiny code :)
Do you have a link or some sort?
Basicly what i should do is:
$base = mysql_connect ('localhost','root','');
mysql_select_db('administrations', $base);
if(isset($_POST['cp']))
{
$sql = 'SELECT NOM_organisme, ID_organisme FROM organismes WHERE code_postal LIKE "%'.$_GET['cp'].'%" ORDER BY NOM_organisme;';
$req = mysql_query($sql) or die('SQL Error !<br>'.$sql.'<br />'.mysql_error());
while ($data = mysql_fetch_array($req))
{
echo '<p id="'.$data['ID_organisme'].'"'.$data['NOM_organisme'].'</br>'.$data['ID_organisme'].'</p></br>';
}
} else {
echo 'show something else';
}
If I get you correctly, you are
Sending a GET request in index.php using file_get_contents() to your website.
The website (api.php) performs an SQL query and prints the result in HTML.
index.php takes this HTML output and stores it in the variable $var.
You want to retrieve all values contained inside the id attribute of the paragraph.
In this case, you probably want to use regular expressions. preg_match_all seems to be appropriate. It should work for you like this:
$out = array();
preg_match_all("/id=\"([^\"]*?)\"/U", $var, $out);
foreach ($out as $value) {
echo 'I found some id ' . htmlspecialchars($out[$value][2]) . '<br />';
}
And additionally:
A decent HTML parser would be much more appropriate in this case (eg. it would not match id="X" in flow text).
Your PHP code is vulnerable to SQL injections.
You should sanitize plain text to HTML appropriately.
First of all, you should try to display your API reply as a JSON-string, this is much more convenient.
If you still want to use your api.php, you first need to close your opening paragraph! You did forget a '>'!
echo '<p id="'.$data['ID_organisme'].'">'.
$data['NOM_organisme'].'</br>'.
$data['ID_organisme'].'</p></br>';
Then you need to parse your paragraph.
You can do it like that:
if(isset($_POST['cp']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_POST['cp'];
$var = file_get_contents($api);
preg_match("#<p id='(.*)'#", $var, $matches);
id = $matches[1];
echo $id;
}

I need help sorting out an if statement in a simplexml statement

Some basic background ...
I have a form that enters data to an xml file and another page that displays the data from teh xml depending that it meets the requirements . All of this I have managed to get done and thanks to a member on here I got it to show only the data as long as it has todays date and status is out . But I am left with the problem of trying to sort an if statement which needs to show data if it has it or show another div if not .
My Code ...
$lib = simplexml_load_file("sample.xml");
$today = date("m/d/y");
$query = $lib->xpath("//entry[.//date[contains(., '$today')]] | //entry[.//status[contains(., 'out')]]");
foreach($query as $node){
echo "<div id='one'>$node->name</div>
<div id='two'>$node->notes</div>
<div id='three'><div class='front'>$node->comments</div></div>";
}
So to reiterate if query returns matched data do the foreach else show another div
I only wish to know the right code for the if else statement if soneone could help with this I would be very grateful and will up vote any answer as soon as I have the reputation in place . I also apologise in advance if the question has been asked before or if it is too vague thanks again .
If xpath fails to resolve the path, it will return false (see here). Wrap the foreach loop in a simple check:
if( $query ) {
foreach($query as $node){
...
}
}
else {
// Echo the special div.
}
Since PHP is loose typed, if xpath happens to return an empty array, this check will also handle that case. Be aware that if the xpath call does return false, there may be a separate error at play that may require additional or alternative handling.

Always get an empty array in foreach loop

There are two columns in the database table "system". I have the systemId and want to get the mobileSystemId. But the variable $mobileSystemIds which I already defined as global is always empty.
EDIT: Now array_map doesn´t work. I always get my Exception output "Arrayfehler ArrayMap"
I have the following code :
$mobileSystemIds=array();
function getMobileSystemId($systemId)
{
global $mysqli;
global $mobileSystemIds;
$query="SELECT mobileSystemId FROM system WHERE systemId ='" .$systemId ."'";
if(!$result=$mysqli->query($query))
{
echo "Datenbankfehler DB-QUery";
exit(0);
}
if (!$mobileSystemId=$result->fetch_assoc())
{
echo "Datenbankfehler DB-Fetch";
exit(0);
}
$mobileSystemId=$mobileSystemId["mobileSystemId"];
echo "mobile System ID: " .$mobileSystemId ."<br />";
return $mobileSystemId;
}
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
In this case, using a return in your function would be much cleaner.
Nothing to do with your problem, but is your $systemId var trusted ? (To prevent SQL injection).
Update:
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
ought to read (just checked; it works for me):
$mobileSystemIds = array_map('getMobileSystemId', $systemsList);
if (empty($mobileSystemIds))
{
if (empty($systemsList) || !(is_array($systemsList)))
echo "OK: no mobile IDs, but no systems either";
else
echo "THIS now is strange :-(";
}
else
{
echo "Alles OK";
var_dump($mobileSystemIds);
}
I tried this by returning a dummy value based on input; if it does not work for you, there must be something strange in the database.
(Update: the text below refers to your original code, which did not use array mapping)
Your code ought to be working as it is. You put several $mobileSystemId 's into a single $mobileSystemId.
It works: I tested with a simpler code, removing the DB calls but leaving your code, and spelling, untouched.
So, the error must be elsewhere. I would guess that this code is included into something else, and:
the $mobileSystemIds = array(); declaration gets executed more than once, thereby losing all its data;
the $mobileSystemIds = array(); declaration is itself included in a more local scope and you read it from outside, reading an empty value or a totally different value.
Try replacing the first part of your code with:
GLOBAL $mobileSystemsIds;
if (defined($mobileSystemsIds))
trigger_error("mobileSystemsId defined more than once", E_USER_ERROR);
else
$mobileSystemsIds = array();
and also, in the function body:
if (!defined($mobileSystemsId))
trigger_error("mobileSystemsId should have been defined", E_USER_ERROR);

PHP EOF showing only one result [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
PHP EOF shows only one result from loop
Hello
Seems like I can not find the solution for such problem.
I am using the following code.
it should display all the results given by the mySQL loop in the EOF.
But it is showing only the first results, nothing else.
What I am doing wrong?
Please help me
function getYiBAdminBanner() {
global $site;
global $dir;
$queryYiBmenu = "SELECT * FROM `(YiB)_cPanel_Menu` WHERE Type = 'top'";
$resultYiBmenu=mysql_query($queryYiBmenu) or die("Errore select menu: ".mysql_error());
$countYiBmenu = mysql_num_rows($resultYiBmenu);
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
$menu .= "<div id=\"menu\" style=\"display:none;\"><li><img class=\"imgmenu\" src=\"".$site['url'].$rowYiBmenu['linkIcon']."\">".$rowYiBmenu['linkTitle']."</li></div>";
}
if($countYiBmenu <= 0){
$menu = "No Modules Installed";
}
$bannerCode .= <<<EOF
<div style="width:520px; background-color: #EEE; height:30px;">
{$menu}
</div>
EOF;
return $bannerCode;
}
Though this won't fix your issue, I see you are using mysql_fetch_array(). This is rather pointless, as you are doing associative matching afterwards ($rowYiBmenu['linkHref'], for example). It will work for you, but it's a waste of resources, as the results will be loaded in a numeric array as well (making the $rowYiBmenu array twice as large, just wasting memory).
Also, you didn't declare the $menu variable, you just 'added on'. Before the while statement, put $menu = ''; (or anything else that will declare an empty string for that variable).
Lastly, use single quotes around html strings. That way you don't have to keep escaping double quotes for when adding an attribute. For example, the $menu line in the while statement should look like this:
$menu .= '<div id="menu" style="display:none;"><li><img class="imgmenu" src="'.$site['url'].$rowYiBmenu['linkIcon'].'">'.$rowYiBmenu['linkTitle'].'</li></div>';
I'm not sure if I helped you with your problem at all, but I thought this would help you clean up your code a bit (the cleaner the code, the less prone to errors and the easier it is to spot errors).
I have tried helping in the other duplicate question.
i feel you need to implement (learn?) some basic debugging on the data coming from the database. This should be very simple to solve.
I suggest changing your while() code to something like this to help debug whats happening:
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
print "linkTitle: " . $rowYiBmenu['linkTitle'] ."<BR>";
print "linkHref: " . $rowYiBmenu['linkHref'] ."<BR><BR>";
}
exit;
You should see output of all results from the database (not just the first or last). After establishing that the correct data is being retrieved and looped through. you can get that $menu variable concatenation and $bannerCode + HereDoc EOF code sorted out.

Categories