html form
<html><body>
<form action="process.php" method="post">
Headline:<input type="text" name="head"><br>
Content:<Textarea rows="4" cols="50" name="cont"></textarea>
</form>
</html>
my table structure
two fields are headline,content.
Filling the form:
Headline- "this is crazy"
Content- "here i want to put image like this..
<img src="$image" /> "
Process.php
in this i get Headline and content from form in two php variable
$headline=$_POST['head'];
$content=$_POST['cont'];
here i have one variable $image which contains address of image like: $image contains "img\thumb\2.jpg"
i've to insert $headline and $content into table.
problem
whenever i insert headline and content into table... headline goes fine into table..but in content it shows: "here i want to put image like this..
<img src="$image" /> "
why $image actual value is not getting parsed?
any solution?
You're not actually "in PHP" when you're attempting to output it.
In other words, you have to open a PHP section to echo the variable:
<?php echo $image; ?>
or, with your image tag:
<img src="<?php echo $image; ?>" />
It's because when you write $image into HTML textarea, it's treated as a string not as variable.
So, you should write the full image URL to your database, something like img\thumb\2.jpg and then read it to the browser.
Use html_entity_decode Convert all HTML entities to their applicable characters
html_entity_decode($content);
Example
$b = html_entity_decode("I'll "walk" the <b>dog</b> now");
echo $b; // I'll "walk" the <b>dog</b> now
See when you are trying to input special characters like <, >, & etc. they are converted into their HTML formats like < is converted into <, similarly > is converted into >. Thats why when you are trying to insert < or > symbol in database it is inserting it like < and >. You shouldn't use them like this. But if you really need them you can replace < with < and > with > just before Insert query.
$qry = "INSERT INTO TEST (HEAD, CONTENT) VALUES (" . $head . ", " . $content . ")";
$qry = str_replace("<", "<", $qry);
$qry = str_replace(">", ">", $qry);
and then you can use $qry for insertion.
Related
I have a string saved in a database as <b>hello</b>
When I get the string from the database using a query, the text isn't bold (which should be caused by the <b> tags). Instead, it simply displays as 'hello'.
How can I apply the html tags to the text ?
<?php
$stmt = $con->prepare("SELECT * FROM posts");
$stmt->execute();
$text = $row['text'];
echo $text;
?>
I have tried using htmlentities as well as html_entity_decode, but the result is the same.
I'm unable to use html tags in the output ($text = "<b>" . $row['text'] . "</b>";) as I'm getting multiple strings from the database, each with different html tags.
#Fred-ii- Hi Fred, just to let you know that I tried htmlspecialchars_decode(stripslashes($row['text'])) again and out of the blue, it strangely worked. – The Codese
As stated in comments:
htmlspecialchars_decode(stripslashes($row['text']))
is what should have been used.
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'] . '';
This question already has answers here:
php - insert a variable in an echo string
(10 answers)
Closed 4 years ago.
I am trying to do something I know is probably simple, but I am having the worst time.
I have functioning so far:
1.Script to upload image files to server
2. write the image file names to the database
3. I want to retrieve the image filename from the db and add it to the img src tag
here is my retrieval script
<?php
$hote = 'localhost';
$base = 'dbasename';
$user = 'username';
$pass = '******';
$cnx = mysql_connect ($hote, $user, $pass) or die(mysql_error ());
$ret = mysql_select_db ($base) or die (mysql_error ());
$image_id = mysql_real_escape_string($_GET['ID']);
$sql = "SELECT image FROM image_upload WHERE ID ='$image_id'";
$result = mysql_query($sql);
$image = mysql_result($result, 0);
header('Content-Type: text/html');
echo '<img src="' $image'"/>';
?>
I was trying to pass the Value through image.php?ID=2 but no luck
The PHP script successfully returns the filename, but I cannot for the life of me get it to print it to the html
Any suggestions, please and thank you very much :)
OK, it does return the proper tag, but now it seems as though the script doesnt run to generate the tag.
I have tried two ways:
<div class="slides">
<div class="slide">
<div class="image-holder">
<?php
include ("image.php?ID=2");
?>
</div>
and:
<img src="image.php?ID=2" alt="" />
but neither one will insert the filename...
I need to identify each img src by the primary key, so I was passing it the ID from each image src location
but alas, my PHP ninja skills need to be honed.
Just to clarify: I am uploading images to the server, recording the filenames in a DB and calling that filename in an HTML doc...there are several in each one so I need to pass the ID (i.e. 1,2,3 ) to correspond to the primary key in the table.
But I cant get the script to process the tag first.
If I go to view source, I can click the script and get the proper result...
Thanks again, you guys and girls are very helpful
You're missing the concatenation operator: .:
echo '<img src="' . $image . '"/>';
You can do it as you did but you had the single quotes in twice, (unless you were meaning to use concatenation - which is unnecessary - if you want this see the other answer).
echo "<img src=\"$image\"/>";
Or the longer form with braces if you need to embed inside text.
echo "<img src=\"${image}\"/>";
I'd recommend using heredoc syntax for this if you're doing lots of HTML. This avoids the need to have lots of echo lines.
echo <<< EOF
<div class="example">
<img src="$image" />
</div>
EOF;
Try using this syntax:
echo "<img src=\"$imagePath\" />";
It works with double quotes provided you escape the quotes in the src attribute. Still not sure why the singles don't work.
there are 2 major flaws with your design
There is no image.php?ID=2 file on your disk.
There is absolutely no point in including image.php file. You have to get the name right in the file you are working with. don't you have this row already selected from the database? Why not just print the image name then?
And yes, you are using single quotes where double ones needed.
Hi so i was wondering how do i get a load of string from a mysql database and put them in a input area with a return between each value such as
Hi
My
Name
Is
Joris
Thanks,
Joris
When you're creating a <textarea> in a form, the text between the <textarea> and </textarea> tags is the default text for the text area. You just need to build a pair of these with the string you want between them, like this: <textarea>$string</textarea>. Do the query and the concatenating in PHP using \n for newlines.
You can simply add a carriage return after each string and then output this within the required textarea.
For example:
<?php
$cr = "\n";
$bigString = 'Hello' . $cr . 'there.';
echo '<textarea>' . $bigString . '</textarea>';
?>
In my PHP project I have a value containing special characters like ",', etc. (" 5 " inches, '3.5' inches, etc.). But it does not appear in a text field. How can I display this?
Is it possible to display this value in a text box?
Use htmlentities:
<input value="<?php echo htmlentities($value);?>">
I suppose your "text box" is an HTML <input> element?
If so, you are displaying it using something like this:
echo '<input name="..." value="' . $yourValue . '" />';
If it's the case, you need to escape the HTML that's contained in your variable, with htmlspecialchars:
echo '<input name="..." value="' . htmlspecialchars($yourValue) . '" />';
Note that you might have to add a couple of parameters, especially to specify the encoding your are using.
This way, considering $yourValue has been initialized like this :
$yourValue = '5 " inches';
You'll get from this generated HTML:
<input name="..." value="5 " inches" />
To that one, which works much better:
<input name="..." value="5 " inches" />
For UTF-8 I went for htmlspecialchars($value, ENT_QUOTES, "UTF-8") which did the trick.
stack source
When using character set UTF-8, I use the code below to get Iñtërnâtiônàlizætiøn and double (or single) quotes right:
<input type="text" name="title" value="<?php echo htmlentities(stripslashes(utf8_decode($title))); ?>" />
PS: This is useful after someone submitted the form, but when the input is not validated.
I've found if you have double quotes in a variable in JavaScript (from Ajax/database whatever) and you want to put it in a field - if you build the whole field/form HTML content and then swap that into a div using innerHTML, the double quotes in the value will cause problems. I was doing this and I couldn't figure a way around it by escaping either.
You should build the HTML content with the field and swap it in first, and then do a document.getElementById('myfieldid').value = thevalue; instead and it works fine.
I needed to apply htmlspecialcars() to the query result array. I found a useful solution from here (see the comment by sean).
// Create a cleaning function
function _clean(&$value) {
$value = htmlspecialchars($value);
//$value = htmlspecialchars($value, ENT_QUOTES); // Alternative
}
// Fetch the data from DB somehow (sqlQ is a custom function)
$q = "...";
$r = $d->sqlQ($q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
//...call the function recursively (not always necessary) to the resultset row
array_walk_recursive($row, '_clean');
It does quite a bit unnecessary work if you fetch only a few text columns, but at least you don't need to write the htmlspecialchars() function to the HTML form multiple times.
Try this
echo '<input name="..." value="' . htmlspecialchars(stripslashes($yourValue)) . '" />';
or
<input name="..." value="<?php echo htmlspecialchars(stripslashes($value)); ?>">
Good luck ;)
Personally, I use this trick:
$s = str_replace("& amp ;", "&", (htmlentities(stripslashes($s), ENT_QUOTES, 'UTF-8')));
It looks like the best way to manage single and double quotes (and other special chars) with HTML input is mimicking it via textarea field.
So just create a textarea instead of input field and give some styles to make it look like a native input.
<textarea class="fake-input"> quote's and other quote"s </textarea>
<style>
.fake-input {
height: 20px; /* based on your font-size */
resize: none;
overflow: hidden;
white-space: nowrap;
width: /* your input width */
}
</style>