I always have trouble mixing languages and I recently started with MYSQL. In this case I have this code:
<?php
$data = mysql_query("SELECT * FROM Badges")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "http://www.google.com/s2/favicons?domain=".$info['Website'] . "";
}
?>
And I need it to print an image instead of the link it's printing.
http://www.google.com/s2/favicons?domain=".$info['Website'] . " being the image's url
How would that be written? Thanks a lot
print '<img src="http://www.google.com/s2/favicons?domain=' . $info['Website'] . '" alt="" />';
Some other tips...
mysql_* are old functions, PDO is much better to use now it is available.
or die() is old too - have you considered exceptions?
echo is more commonly used than print, and you should use the case that is stated in the manual, e.g. print instead of Print.
You should learn about separation of concerns, e.g. you should do your query and data management on a different layer where you pass the relevant data to your view which would consist solely of HTML and some PHP constructs used to generate it.
i usually find it easier to try and express what differs from case to case in an abstract manner. in your case it's the website (after ?domain=) that differs, all the rest is the same. so the url to the image could abstractly be expressed as http://www.google.com/s2/favicons?domain={website} where {website} is a place holder for future replacement.
replacement would then be performed using the function
$result = str_replace($what_to_replace, $what_to_replace_with, $original_string);
the advantage of this is that you're never mixing languages on one line, and this makes the code easier to develop :) just look at this quite easily read piece of code:
<?php
$img = '<img src="http://www.google.com/s2/favicons?domain={website}" />';
$data = mysql_query("SELECT * FROM Badges")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$concrete_img = str_replace("{website}", $info['Website'], $img);
print $concrete_img;
}
?>
Related
I can't seem to get a URL into echo. I want to make a link to open Google Maps:
I can't figure out what's wrong with my code:
$query = mysql_query("SELECT * FROM cev")or die(mysql_error());
while($row = mysql_fetch_array($query))
{
$name = $row['sitecode'];
$lat = $row['latitude'];
$lon = $row['longitude'];
$type = $row['sitetype'];
$city = $row['city'];
$id = $row['id'];
echo("addMarker($lat, $lon,'<b>$name</b>View<br><br/>$type<br/>$city');\n");
You have to fix the quotes:
echo "addMarker($lat, $lon,'<b>$name</b>View<br><br/>$type<br/>$city');\n";
Alternative ways
Here document
echo <<<EOS
addMarker($lat, $lon, '<b>$name</b>View<br><br/>$type<br/>$city');
EOS;
Concatenation
echo "addMarker($lat, $lon, '<b>$name</b>" .
"View" .
"<br><br/>$type<br/>$city)";
Using addshashes
The addMarker looks like a JavaScript function. You might pre-process the HTML string by means of addslashes:
$html = <<<EOS
<b>$name</b>View<br><br/>$type<br/>$city
EOS;
$html = addslashes($html);
echo "addMarker($lat, $lon, '$html');\n";
Recommendations
I recommend using an editor with support of syntax highlighting.
Read about PHP strings. Especially the matter of escaping.
Finally, I wouldn't recommend writing any HTML/JavaScript within a PHP code. Use template engines such as Smarty or Twig instead.
It seems like you are trying to use method inside the echo statement. If you want to use methods, variables or some php stuffs you should not use quotes at most case unless it is an eval featured object or method.
Try like this
echo addmarker($lat, $lon,
'<b>'.$name.'</b> <a href="'.editcev.php?id=.' '.$row['id'].
".'>View</a><br><br/>'
.$type.
'<br/>'
.$city.');'."\n");
I don't know your exact situation but i think this works
echo("addMarker(".$lat.",".$lon.",<b>".$name."</b>View<br><br/>".$type."<br/>".$city.");\n");
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 have been coding for a while now but just can't seem to get my head around regular expressions.
This brings me to my question which is the following: is it bad practice to use PHP's explode for breaking up a string of html code to select bits of text? I need to scrape a page for various bits of information and due to my horrific regex knowledge (In a full software engineering degree I had to write maybe one....) I decided upon using explode().
I have provided my code below so someone more seasoned than me can tell me if it's essential that I use regex for this or not!
public function split_between($start, $end, $blob)
{
$strip = explode($start,$blob);
$strip2 = explode($end,$strip[1]);
return $strip2[0];
}
public function get_abstract($pubmed_id)
{
$scrapehtml = file_get_contents("http://www.ncbi.nlm.nih.gov/m/pubmed/".$pubmed_id);
$data['title'] = $this->split_between('<h2>','</h2>',$scrapehtml);
$data['authors'] = $this->split_between('<div class="auth">','</div>',$scrapehtml);
$data['journal'] = $this->split_between('<p class="j">','</p>',$scrapehtml);
$data['aff'] = $this->split_between('<p class="aff">','</p>',$scrapehtml);
$data['abstract'] = str_replace('<p class="no_t_m">','',str_replace('</p>','',$this->split_between('<h3 class="no_b_m">Abstract','</div>',$scrapehtml)));
$strip = explode('<div class="ids">', $scrapehtml);
$strip2 = explode('</div>', $strip[1]);
$ids[] = $strip2[0];
$id_test = strpos($strip[2],"PMCID");
if (isset($strip[2]) && $id_test !== false)
{
$step = explode('</div>', $strip[2]);
$ids[] = $step[0];
}
$id_count = 0;
foreach ($ids as &$value) {
$value = str_replace("<h3>", "", $value);
$data['ids'][$id_count]['id'] = str_replace("</h3>", "", str_replace('<span>','',str_replace('</span>','',$value)));
$id_count++;
}
$jsonAbstract = json_encode($data);
echo $this->indent($jsonAbstract);
}
I highly recommend you try out the PHP Simple HTML DOM Parser library. It handles invalid HTML and has been designed to solve the same problem you're working on.
A simple example from the documentation is as follows:
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
It's not essential to use regular expressions for anything, although it'll be useful to get comfortable with them and know when to use them.
It looks like your scraping PubMed, which I'm guessing has fairly static mark-up in terms of mark-up. If what you have works and performs as you hope I can't see any reason to switch over to using regular expressions, they're not necessarily going to be any quicker in this example.
Learn regular expressions and try to use a language that has libraries for this kind of task like perl or python. It will save you a lot of time.
At first they might seem daunting but they are really easy for most of the tasks.
Try reading this: http://perldoc.perl.org/perlre.html
I am using TinyMCE to allow users to edit the content of certain pages, the problem is that I should store html tags, along with class="" -es and ..etc.
How should I defend the application against SQL injection, and store the html tags? (main problem is the " -s, It is messing up the mysql query)
In nutshell, I don't know how to add the $_POST (which is a text) to the insert_to_content() function.
$html = "";
$url = "";if (isset($_GET["page"])) {$url = safesql($_GET["page"]);}
$sqlSelectPageText = mysql_query('SELECT * FROM content WHERE name="'.$url.'" LIMIT 1');
$pageText = mysql_fetch_array($sqlSelectPageText); /**/ $sqlSelectPageText = "";
if (isset($_GET["edit"]) and isset($_POST["text"])) {
insert_to_content($url,I_SHOULD_DO_SOMTHG_WAAA($_POST["text"]));
header('Location: admin.php?page='.$url);
}
$html .= '<div id="editor1div">';
$html .= '<form action="admin.php?page='.$url.'&edit" method="post">';
$html .= ' <input class="formsSubmit" type="image" src="images/yep2.png" alt="Save" />';
$html .= '<p>Content:</p>';
$html .= ' <textarea id="editor1" name="text">';
$html .= ' '.$pageText["text"]; /**/$pageText = "";
$html .= ' </textarea>';
$html .= '</form>';
$html .= '</div>';
echo $html;
function insert_to_content($whatPage, $text) {
if (mysql_query('UPDATE content SET text="'.$text.'", lastdate=NOW() WHERE name="'.$whatPage.'"')) {
return true;
} else {
return false;
}
}
function I_SHOULD_DO_SOMTHG_WAAA($text) {
//what should i do with it?
}
EDIT:
#CaNNaDaRk:
I am trying to use your work, but never used PDO (or OOP PHP) so. So, is it possible that I don't have this function? :D "Class 'PDO' not found in.." `
$db = new PDO("mysql:host=$sqlHost;dbname=$sqlDb;$sqlUser,$sqlPass");
$stmt = $db->prepare('UPDATE content SET text=:text, lastdate=NOW() WHERE name=:name');
$stmt->execute( array(':text' => $html, ':name' => $whatPage ) );
Its not only the tinyMCE text but rather your whole script that may lead to SQL injections. Either use mysql_real_escape_string for every parameter you insert into your query or think of using prepared statements such as PDO.
Use of prepared statements can prevent injection and help you with the " issue.
A little example based on your code:
$stmt = $db->prepare('UPDATE content SET text=:text, lastdate=NOW() WHERE name=:name');
$stmt->execute( array(':text' => $html, ':name' => $whatPage ) );
Execute method also returns bool so you don't have to change your code much.
use mysql_real_escape_string() as suggested
when displaying content, use htmlspecialchars() when adding content into the textarea to prevent XSS.
You basically need different quoting for html/sql target formats. There is nothing like "universal quoting". When quoting, you always quote text for some particular output, like:
string value for mysql query
like expression for mysql query
html code
json
mysql regular expression
php regular expression
For each case, you need different quoting, because each usage is present within different syntax context. This also implies that the quoting shouldn't be made at the input into PHP, but at the particular output! Which is the reason why features like magic_quotes_gpc are broken (never forget to handle it, or better, assure it is switched off!!!).
So, what methods would one use for quoting in these particular cases? (Feel free to correct me, there might be more modern methods, but these are working for me)
mysql_real_escape_string($str)
mysql_real_escape_string(addcslashes($str, "%_"))
htmlspecialchars($str)
json_encode() - only for utf8! I use my function for iso-8859-2
mysql_real_escape_string(addcslashes($str, '^.[]$()|*+?{}')) - you cannot use preg_quote in this case because backslash would be escaped two times!
preg_quote()
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).