How to get a url from a database - php

So I have three pages one that is the index page. One that writes the data from a form inside the index page to the database. And one that gets data from the database and echos out a html table with the data inside.
Currently if you write a link in the form. It will just come out as text. I would like the whole link to be like [link].
so say if I wrote this onto the form:
Look at this: www.google.com or Look at this: https://www.google.com
it would come out like this in html
Look at this: www.google.com
How could I go about doing this?
Okay so the html is:
<form class="wide" action="Write-to.php" method="post">
<input class="wide" autocomplete="off" name="txt" type="text" id="usermsg" style="font-size:2.4vw;" value="" />
</form>
in which the user would write:
"Look at this: www.google.com or Look at this: https://www.google.com"
This would then get sent to the database through Write-to.php.
$sql="INSERT INTO social (comunicate)
VALUES
('$_POST[txt]')";
}
this then gets written back into the database:
$result = mysqli_query($con,"(select * from social order by id desc limit {$limit_amt}) order by id asc");
while($row = mysqli_fetch_array($result))
{
echo "<tr div id='".$i."' class='border_bottom'>";
echo "<th scope='col'>";
echo "<span class='text'>".htmlspecialchars($row['comunicate'])."</span><br />";
echo "</th>";
echo "</tr>";
}

Just try:
echo(''.$your_url_variable.'');
Update:
The OP really wanted to detect url's in a string. One possible solution could be filter it using a regular expression. This code could help:
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "{$url[0]} ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
Source: http://css-tricks.com/snippets/php/find-urls-in-text-make-links/

There are quite a few things you need to worry about when displaying user supplied (tainted) data.
You must ensure that all the data is sanitised -- never ever just echo the content, look into htmspecialchars and FILTER_VALIDATE_URL for example:
function validateUrl($url) {
return filter_var($url, FILTER_VALIDATE_URL);
}
What you are attempting to do is convert a string into a link, for example you can write a function like this:
function makeClickable($link) {
$link = htmlspecialchars($link);
return sprintf('%s', $link, $link);
}
You can use string concatenation as well, but I wouldn't do that in my view code. Just personal preference.
Take a look at the urlencode function, it will certainly come in handy.
I would also recommend you read about cross site scripting
Please note that I am not making any implementation recommendations, my aim is just to show you some contrived code samples that demonstrate making a string "clickable".
Update:
If you would like to make links clickable within text, refer to the following questions:
Best way to make links clickable in block of text
Replace URLs in text with HTML links

save the hyperlink in db and retrieve as a string by sql query
like:
select link from table_name where index = i
and save link as: whaatever here
and print it

Use this
echo '' . $res['url'] . '';

Related

How To Auto Detect Url Format ? And Auto Create The Right Secured Echo or Printf?

Trying in building a Searchengine.
Need to echo user submitted links on Searchengine Result Pages. Problem is, different submitted urls will be in different php format.
Q1. How to auto detect the format ?
Q2. My searchengine will be opening the iFrame (of user submitted links) to other users (keyword searchers). How will my php script automatically know which part of the url to run htmlentities() and which parts to run the urlencode() ?
I can't be manually check the url format on a million link each day that my users submit to me everyday.
I mean, if I was opening an iFrame to my own link then no problem as I know my own link's format:
Example:
$url = 'http://localhost/test/pagination.php';
$search = $domain;
$tbl = 'linking_histories';
$col= 'domain';
$i = 1;
$limit = 2;
printf(
"<iframe src='%s?mysql_tbl=%s&mysql_column=%s&keyword_search=%s&result_limit_per_page=%d&page_number=%d'></iframe><br>",
htmlentities($url),
urlencode($tbl),
urlencode($col),
urlencode($search),
$limit, // %d place-holder will force integer
$i,
urlencode($limit),
urlencode($i)
);
I mean, a user might submit a normal static link like so:
A.
'http://localhost/test/pagination.php';
Or, a dynamic one, like these:
B.
'http://localhost/test/pagination.php?keyword=cars'; //%s (printf).
C.
'http://localhost/test/pagination.php?page=4'; //%d (printf).
D.
'http://localhost/test/pagination.php?keyword=cars&page=4';
//%s (printf) & %d (printf).
For example A, this php code is ok to echo the url in the iFrame:
$url = 'http://localhost/test/pagination.php';
printf(
"<iframe src='%s'></iframe><br>",
htmlentities($url),
);
For the example B submitted link, this particular php code is fine to echo the url in the iFrame:
$url = 'http://localhost/test/pagination.php';
$search = $domain;
printf(
"<iframe src='%s?keyword_search=%s'></iframe><br>",
htmlentities($url),
urlencode($search),
);
For example C, this particular php code is correct to echo the url in the iFrame:
$url = 'http://localhost/test/pagination.php';
$i = 1;
printf(
"<iframe src='%s?page_number=%d'></iframe><br>",
htmlentities($url),
$i,
urlencode($i)
);
For D, this particular php code is correct:
$url = 'http://localhost/test/pagination.php';
$search = $domain;
$i = 1;
printf(
"<iframe src='%s?mysql_tbl=%s&mysql_column=%s&keyword_search=%s&page_number=%d'></iframe><br>",
htmlentities($url),
urlencode($search),
$i,
urlencode($i)
);
As you can see from the above, notall the 4 links on the 4 iframes are in same url format.
One uses just htmlentities and no urlencode,
another uses the htmentities plus one urlencode ONLY
while another uses the htmlentities and TWO urlencode
and so on.
Some links have INT while others don't.
Now since each user submitted link will be different to each other, then I can't use one set of printf to echo all url formats.
So how to detect the url format on auto to generate the right printf with the right data type on the printf (eg. '%s', '%d") for that particular url the user submits ?
Is there any function in php that can detect the url type to tell me which functions (htmlentities, urlencode(), %s, %d, etc.) to use on which part of the url ? You know the var_dump() tells you the data type. Something like that I am looking for.
Care to show an code example how to achieve my purpose ?
Remember, I need to secure the link outputs so nobody can inject any link in the iFrames ?
**EDIT:
Do I use htmentities() or urlencode() here ?
Or both ?
Imagine url is either this:
$url = 'http://localhost/test/pagination.php?tbl=links&col=domain&search=elvanja.com&page=1&limit=5';
Or, this:
$url = http://www.elvanja.com/contactus.php;
Example 1:
printf("<iframe src='%s'></iframe><br>",
htmlentities($url));
Example 2:
printf("<iframe src='%s'></iframe><br>",
urlencode($url));
Example 3:
printf("<iframe src='%s?tbl=%s&col=%s&search=%s&limit=%d&page=%d'></iframe><br>",
htmlentities($url),
urlencode($url));
I going for EXAMPLE 3, what you say ?**

basic php 'if then' URL link in wordpress

I'm trying to write code that will display a URL link if there one present from a form sumbmission;
If > [a link exists]
then [display the text 'more info' with the href link wrapped around it]
I've confused myself mixing wordpress and php, and can't quite get it. Any help would be great.
This question isn't very specific, but the pseudo-code I can offer is this:
<?php if (isset($_GET['url'])): ?>
Read more
<?php endif; ?>
Are you looking to do something like this to the comments displayed on a post?
Comment: "I like https://www.google.com/" becomes "I like more info".
If that's the case, perhaps adding a filter to functions.php to search for and replace URL might do the trick:
// define the get_comment_text callback
function filter_get_comment_text( $comment_comment_content, $comment, $args ) {
// Regular expression to find URL
$pattern = '/(https?):\/\/(www\.)?[a-z0-9\.:].*?(?=\s)/i';
// Replace url with linked "more info"
$replacement = 'more info';
// Find matches & replace
$newcomment = preg_replace($pattern, $replacement, $comment_comment_content);
// Return the comment
return $newcomment;
};
// add the filter
add_filter( 'get_comment_text', 'filter_get_comment_text', 10, 3 );

Extracting link from a href and putting it within brackets

I have searched and couldn't find what I was looking for.
This is how it will normally be:
<p>
Hi how are you? Have you checked Google or YouTube?
</p>
But what I would love to have, because I'm willing to apply this on a print or PDF page is the following:
<p>
Hi how are you? Have you checked Google (http://www.google.com)
or YouTube (http://www.youtube.com)?
</p>
Now, I understand that there should be some work with regex, but I don't know how to use that. The text will be taken from the variable $content which has the article in it, and what I would like to have is that all links within $content remain as they are plus the content of href be as an additional hyperlink within brackets "()" so that, hypothetically when someone reads a printed article where hyperlinks are they would be able to see the actual URL.
Use a pseudo element to add the href after your links, something like:
a[href]:after
{
content: " (" attr(href) ") ";
}
Here is a handy little Function that may suffice.
<?php
/**#var string $strInput THE STRING TO BE FILTERED */
function doubleUpOnURL($strInput){
$arrAnchorSplit = preg_split("#<\/a>#", $strInput);
$strOutput = "";
$anchorRegX = '(<a\s*href=[\'\"])(.+)([\'\"]>)(.*)';
foreach($arrAnchorSplit as $anchoredString){
$strOutput .= preg_replace("#" . $anchorRegX . "#si" , "$1$2$3$4</a> ($1$2$3$2</a>)", $anchoredString);
}
return $strOutput;
}
$strInput = '<p>Hi how are you? Have you checked Google or YouTube?</p>';
echo(doubleUpOnURL($strInput));
//OUTPUTS:
// Hi how are you? Have you checked Google (http://www.google.com) or YouTube (http://www.youtube.com)?
I hope you find it helpful...

php look for string in address bar, replace body contents accordingly

I am looking for the php "header" code and in-html-body-phpsnippet which will look for an exact string such as "redwidget" or "bluewidget" "greenwidget" etc in the address bar, and modify the output of the in-body <phpsnippet> based on which of those strings is there in the address bar
... in other words, I can define a list of parameters to look for in the address bar, and the <phpsnippet> will modify the in-body html output based on which it finds
ALSO if it finds none of them, there is a default or "fallback" output
What would the header script and also the in-body be?
My goal is to change the image displayed on a page based on which parameter it finds in the address bar
***Begin Example listing of outputs:
exact string "redwidgets" found in address bar -> <phpsnippet> outputs "/images/redwidget.jpg"
or exact string "greengoblin" found in address bar -> <phpsnippet> outputs "/images/greengoblin.jpg"
or exact string "bluewidgets" found in address bar -> <phpsnippet> outputs "/images/bluesteel.jpg"
or None of the above exact strings found in address bar -<phpsnippet> outputs "/images/defaultplaceholderimagethingy.jpg"
***End example
Thanks in advance!
<?php
$validKeywords = array("a", "b");
//ternary if/else: condition ? this if true : otherwise this;
$keyword = isset($_GET['keyword']) && in_array($_GET['keyword'], $validKeywords) ? $_GET['keyword'] : "defaultplaceholderimagethingy";
//format the output with sprintf and store it for later use
$output = sprintf("<img src='images/%s' alt='%s' />", $keyword.".jpg", "descriptive text");
print $output;
?>
Hope this helps.
Why don't you use GET parameters?
http://myurl/?phpsnippet=redwidget
In your code:
if (isset($_GET['phpsnippet']) {
// use $_GET['phpsnippet'] which, in this case, equals 'redwidget'
} else {
// display default
}
Ok I ALMOST figured this one out...
Here is my header code:
if (isset($_GET['keyword'])) {
$keyword = $_GET['keyword'];
}
And my in-body html/php which replaces the image based on the keyword parameter:
<img alt="" src="http://takeherhometonight.net/wp-content/uploads/<?php echo $keyword; ?>.jpg" border="0" width="300" height="314" />
The only thing I can't get with the above is a DEFAULT image, should a keyword parameter not be present.... any ideas?

How do I call an iframe or something similar in PHP?

Hey how do I call an iframe or something similar in PHP?
I have found some code but I might be setting up wrong, this is the code that I found, code:
<iframe id="frame" src="load.php?sinput="<?php echo $_GET["sinput"]; ?> > </iframe>
Does anybody know any iframe PHP codes or something similar for PHP?
Some people are saying not to use iframes what is there from PHP?
There is no function to generate an iframe in PHP.
What you're doing is fine, but allow me to make a suggestion:
<?
$input = "";
if(isset($_GET['sinput'])) {
$input = htmlspecialchars($_GET['sinput']);
}
?>
<iframe id="frame" src="load.php?sinput="<?php echo $input; ?>">Your browser does not support iframes</iframe>
EDIT: actually
<?
$url = "load.php";
// Query Building Logic
$querys = array();
if(isset($_GET['sinput'])) {
$queries[] = "sinput=".htmlspecialchars($_GET['sinput']);
}
// Generate full URL
if(count($queries) > 0) {
$url .= "?" . implode("&", $queries);
}
?>
<iframe id="frame" src="<? echo $url; ?>">Your browser does not support iframes</iframe>
I think is better quality overall, but ill let that up to my peers to judge. This is just another suggestion, to generate the full usable URL to use in your HTML in a full logic block, rather than relying on information to be present and usable in the template (because if the element ['sinput'] in the $_GET array is not set for whatever reason, the page will outright snap on you.

Categories