Jump to content

Why str_replace doesnt replace anything?


rain13
 Share

Recommended Posts

$str value is: double \"quote\" single \'quote\'after these replacements $b value is double \"quote\" single \'quote\'It replaces singlequotes, but doesn't replace double quotes. Does anyone got any ideas about how to replace double quotes?

$str = htmlspecialchars($_POST['Editor']);$a = str_replace("\'","'",$str);$b = str_replace('\"','"',$a);

Also this didn't replace quoteshtmlspecialchars($_POST['Editor'], ENT_QUOTES);Also double \"quote\" single \'quote\' <sss> after those 2 replacements is double \"quote\" single 'quote' <sss> but still havent quotes encoded.Preview: http://autoit.net.ee/2010/ajaxpost.htmlHere's full php code

<?phpecho'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><style TYPE="text/css">blockquote {	background: #ebebeb none 6px 8px no-repeat;	border: 1px solid #dbdbdb;	font-size: 0.95em;	margin: 0.5em 1px 0 25px;	overflow: hidden;	padding: 5px;}a:link	{ color: #0000CC; text-decoration: none; }a:visited	{ color: #0000CC; text-decoration: none; }a:hover	{ color: #3333FF; text-decoration: underline; }a:active	{ color: #3333FF; text-decoration: none; }.postprofile {	margin: 5px 0 10px 0;	min-height: 80px;	color: #00;	border-left: 1px solid #000000;	width: 22%;	float: right;	display: inline;}.postbody {	padding: 0;	line-height: 1.48em;	color: #333333;	width: 76%;	float: left;	clear: both;}hr.divider {	float: none;	display: none;}</style></head><body><div style="overflow:auto;">';//~ die($_POST['Editor']);$a = htmlspecialchars($_POST['Editor']);echo $a."<br>";$a = str_replace("\'","'",$a);$a = str_replace('\"','"',$a);echo $a."<br>";if (strlen($a) >= 1){echo '<h3>Preview:</h3><div style="border:1px solid grey;">'.parsecode($a, true)."</div>";exit();}//if (strlen($a) >= 1){echo $a;}function GropuToString($GroupNR){	if ($GroupNR == 0){return "Banned";}	elseif ($GroupNR == 1){return "Registered user";}	elseif ($GroupNR == 2){return "Administrator";}}$singleQuete = "'";$dbuser="*****";$dbpassword="****";$database="***";$tblName = "Users";mysql_connect("localhost",$dbuser,$dbpassword);@mysql_select_db($database) or die( "Unable to select database");$loggedin = false;if(isset($_COOKIE['User'])){	//echo($_COOKIE['User']);	//exit();	$UserData = explode("waaaaaaaaaaaaw",$_COOKIE['User']);	//echo "cookie".$UserData;	$result = mysql_query("SELECT * FROM ".$tblName.' WHERE UserName = "'.$UserData[0].'"');	if(mysql_num_rows($result)){		if ($UserData[1] == mysql_result($result,0,"UserPassword"))		{			if(mysql_result($result,0,"UserGroup") == 0){die("Your account have been banned!<br>Reason: ".mysql_result($result,0,"UserBanReason"));}			$loggedin  = true;		}	}else{		setcookie("User", "", mktime(12,0,0,1, 1, 1990));	}}function FileRead($sFile){	$fd = fopen ($sFile , "r");	if ($fd) {		if (filesize($sFile) > 0){			$fstring = fread ($fd , filesize ($sFile));			fclose($fd);			return $fstring;		}else{			fclose($fd);			return "";			}	}	else{		echo '<font color="#FF0000">ERROR:</font> Can not read file '.$sFile;		return false;	}}function parsecode($Code, $preview = false){	global $database;	global $tblName;	global $UserData;	global $Title;	if ($preview == false){	$UserName = substr($Code,15);	$UserEnd = strpos($UserName,'"');	$UserName = substr($UserName,0,$UserEnd );	$DateStart = strpos($Code,'date="');	$PostDate = substr($Code, $DateStart+6 );	$DateEnd = strpos($PostDate,'"');	$PostDate = substr($PostDate, 0 ,$DateEnd);	$TextStart= $DateStart+6+$DateEnd+2;	$Code = substr($Code , $TextStart);	}	$bbarray = array("[b]","[/b]","[i]","[/i]","[u]","[/u]");	$htmlarray = array("<b>","</b>","<i>","</i>","<u>","</u>");	$Code = str_replace($bbarray,$htmlarray,$Code);		while (preg_match_all('`\[(.+?)=?(.*?)\](.+?)\[/\1\]`', $Code, $matches)) foreach ($matches[0] as $key => $match) {			list($tag, $param, $innertext) = array($matches[1][$key], $matches[2][$key], $matches[3][$key]);			switch ($tag) {				case 'size': $replacement = "<span style=\"font-size: $param;\">$innertext</span>"; break;				case 'color': $replacement = "<span style=\"color: $param;\">$innertext</span>"; break;				case 'center': $replacement = "<div class=\"centered\">$innertext</div>"; break;				case 'quote': $replacement = "<blockquote>$innertext</blockquote>";break;				case 'lnk': $replacement = '<a href="' . ($param? $param : $innertext) . "\">$innertext</a>"; break;				case 'url': $replacement = '<a href="' . ($param? $param : $innertext) . "\">$innertext</a>"; break;				case 'img':					list($width, $height) = preg_split('`[Xx]`', $param);					$replacement = "<img src=\"$innertext\" " . (is_numeric($width)? "width=\"$width\" " : '') . (is_numeric($height)? "height=\"$height\" " : '') . '/>';				break;				case 'video':					$videourl = parse_url($innertext);					parse_str($videourl['query'], $videoquery);					if (strpos($videourl['host'], 'youtube.com') !== FALSE) $replacement = '<embed src="http://www.youtube.com/v/' . $videoquery['v'] . '" type="application/x-shockwave-flash" width="425" height="344"></embed>';					if (strpos($videourl['host'], 'google.com') !== FALSE) $replacement = '<embed src="http://video.google.com/googleplayer.swf?docid=' . $videoquery['docid'] . '" width="400" height="326" type="application/x-shockwave-flash"></embed>';				break;			}			$Code = str_replace($match, $replacement, $Code);		}	$Code = str_replace("\n", "<br>", $Code);	$array[0] = $UserName;	$array[1] = $PostDate;	$array[2] = $Code;	if	(!$preview){$PosstString='<div class="postbody" style="background-color:#%topiccolor" >	<h3>%title</h3>	Posted by %user on %postdate	<div>%text</div></div><dl class="postprofile">	<dd style="margin: 0px 5px 0px 5px">%user<br> %group<br>%usravatar<br> Posts: %uposts<br> Joined: %joindate<br>MSN: %usrmsn<br>Email: %usrmail</dd></dl><hr class="divider" />';}else{	$PosstString='%text';	$PosstString = str_replace("%text",$array[2],$PosstString);	return $PosstString;	}	@mysql_select_db($database);	$result = mysql_query("SELECT * FROM ".$tblName.' WHERE UserName = "'.$array[0].'"');	$Group = mysql_result($result,0,"UserGroup");	$PostCount = mysql_result($result,0,"UserPostCount");	$Joindate = mysql_result($result,0,"UserJoinDate");	$UserAvatar = mysql_result($result,0,"UserAvatar");	if ($UserAvatar != ""){$UserAvatar = '<img src="'.$UserAvatar .'" alt="Not found"/>';}	$showemail = '';	$showmsn = '';	$showState = mysql_result($result,0,'UserShowMailMSN');	if	($showState == 3){$showemail = mysql_result($result,0,'UserEmail'); $showmsn = mysql_result($result,0,'UserMSN');}	elseif($showState == 2){$showmsn = mysql_result($result,0,'UserMSN');}	elseif($showState == 1){$showemail = mysql_result($result,0,'UserEmail');}	$showemail = str_replace("@","(at)",$showemail);	$showemail = str_replace(".","(dot)",$showemail);	$showmsn = str_replace("@","(at)",$showmsn);	$showmsn = str_replace(".","(dot)",$showmsn);	$PosstString = str_replace("%user",$array[0],$PosstString);	$PosstString = str_replace("%postdate",$array[1],$PosstString);	$PosstString = str_replace("%title",$Title,$PosstString);	$PosstString = str_replace("%group",GropuToString($Group),$PosstString);	$PosstString = str_replace("%uposts",$PostCount,$PosstString);	$PosstString = str_replace("%joindate",$Joindate,$PosstString);	$PosstString = str_replace("%usravatar",$UserAvatar,$PosstString);	$PosstString = str_replace("%usrmsn",$showmsn,$PosstString);	$PosstString = str_replace("%usrmail",$showemail,$PosstString);	$PosstString = str_replace("%text",$array[2],$PosstString);	return $PosstString."\n<!-- COMMENT END -->\n\n";}@mysql_select_db("Images");$result = mysql_query("SELECT * FROM ".'Images WHERE FileName = "file"');$comments = mysql_result($result,0,"Comment");$Title = mysql_result($result,0,"FileName");if ($comments == ""){echo "No one comments";}else{	$CommentsArray = explode("[/comment]",$comments);	$ColorToggle = true;	for ($i = 0; $i < count($CommentsArray) -1;$i++)	{		if ($ColorToggle){			$TopicColor = "f0f0f0";			$ColorToggle = false;		}else		{			$TopicColor = "ffffff";			$ColorToggle = true;		}		$PosstString  = ParseCode($CommentsArray[$i]);		$PosstString = str_replace("%topiccolor",$TopicColor,$PosstString);		echo $PosstString."<br>";	}}if ($loggedin){echo '</div>  <!-- closes the div with overflow:auto --><p style="float: none;"><br>'.FileRead("./ajaxpost.html").'<p>';}else{echo "<br>Login to reply";}echo '<body><html>';?>

And here's editor code

<html><head><title>PHP using AJAX</title><script type="text/javascript">var time_variable;function getXMLObject()  //XML OBJECT{   var xmlHttp = false;   try {	 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers   }   catch (e) {	 try {	   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+	 }	 catch (e2) {	   xmlHttp = false   // No Browser accepts the XMLHTTP Object then false	 }   }   if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {	 xmlHttp = new XMLHttpRequest();		//For Mozilla, Opera Browsers   }   return xmlHttp;  // Mandatory Statement returning the ajax object created}var xmlhttp = new getXMLObject();	//xmlhttp holds the ajax objectfunction ajaxFunction() {  var getdate = new Date();  //Used to prevent caching during ajax call  if(xmlhttp) {	  var txtname = document.getElementById("Editor");	xmlhttp.open("POST","post.php",true); //calling testing.php using POST method	xmlhttp.onreadystatechange  = handleServerResponse;	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');	xmlhttp.send("Editor=" + txtname.value); //Posting txtname to PHP File  }}function handleServerResponse() {   if (xmlhttp.readyState == 4) {	 if(xmlhttp.status == 200) {	   document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element	 }	 else {		alert("Error during AJAX call. Please try again");	 }   }}function set(style) {	var StyleStart = "["+style+"]";	var StyleEnd = "[/"+style+"]";	if (style == "youtube")	{		var StyleStart = "[video host=youtube.com]";		var StyleEnd = "[/video]";	}	if (style == "google")	{		var StyleStart = "[video host=google.com]";		var StyleEnd = "[/video]";	}   var ta = document.getElementById("Editor");   if (document.selection) {	  str = document.selection.createRange().text	  document.selection.createRange().text = StyleStart + str + StyleEnd;	  return true;   }   else if (ta.selectionStart) {	  var startPos = ta.selectionStart;	  var endPos = ta.selectionEnd;	  var str = ta.value.substring(startPos, endPos);	  ta.value = ta.value.substring(0, startPos) + StyleStart + str + StyleEnd + ta.value.substring(endPos, ta.value.length);	  return true;   }   else {	  return false;   }}</script><div id="message" name="message"></div><br><input type="button" value="bold" onclick="set('b')" /> <input type="button" value="Italic" onclick="set('i')" /> <input type="button" value="Underline" onclick="set('u')" /> <input type="button" value="Image" onclick="set('img')" /> <input type="button" value="Link" onclick="set('lnk')" /> <input type="button" value="Quote" onclick="set('quote')" /> <input type="button" value="Youtube" onclick="set('youtube')" /> <input type="button" value="Google video" onclick="set('google')" /><br /><textarea id="Editor" style="height:300px; width:600px"></textarea><br><input type="button" value="Preview" onclick="ajaxFunction()" /><input type="submit" value="Submit" />

Edited by SoItBegins
Link to comment
Share on other sites

after you used htmlspecialchars($_POST['Editor') it will translate the double quotes to its entity value and leave single quotes alone.so every \" will be change to \"so there is no \" which can be replaced literaly.you can echo out the $str and see the source code to check how does it manupulated.if you put ENT_QUOTES it will trnaslate single quotes too.

Link to comment
Share on other sites

when I insert this code into my text area ( linked to my first post) 'a',"b" <b> I get this 'a',"b" <b> which shows that" and ' are not being replaced.i think it's java that makes \" instead of "so my new code looks like that.

$a = $_POST['Editor'];$a = str_replace("\'","'",$a);$a = str_replace('\"','"',$a);$a = htmlspecialchars($a,ENT_QUOTES);
if you look at my php code do you think having ' and " not encoded my page could be exploited? or how safe does that code look? Edited by SoItBegins
Link to comment
Share on other sites

If we're talking about security, then all that matters is where the data from $_POST['Editor'] is going to. The data must be escaped accordingly for each destination, and one escape isn't applicable in other contexts.If the data in the text area must be displayed as plain text, as is, on an HTML page, using htmlspecialchars() is the only thing you need.If the data in the text area is to be part of a string in a MySQL query, using mysql_real_escape_string() is the only thing you need.Using both functions on the data doesn't make it good for both destinations.Same goes for other functions, str_reaplace() included.

Link to comment
Share on other sites

but this didnt replace qouble quote for some reason htmlspecialchars($_POST['Editor'],ENT_QUOTES); I dont know whats ther reason but only quotes i managed to change was single quotes. I have no good explanation. It just doesnt replace double quotes. Does anyone know how line end works? is it always \n or does it depend on operating system?

$a = $_POST['Editor']; //get data (for some reason slashes are added next to (double)quote$a = str_replace("\'","'",$a); //remove slashes$a = str_replace('\"','"',$a);$a = htmlspecialchars($a,ENT_QUOTES); //encode

go to http://autoit.net.ee/2010/ajaxpost.html and type '" and click preview. and then look at source then you see that nothing happens to quotes

Edited by SoItBegins
Link to comment
Share on other sites

probably your magic quote is on in your php.ini. so that user input has been escaped. to be sure you can check your php.ini settings by using http://php.net/function.phpinfo .if you are (if it is the purpose of your code) wanting to workaround that. you can use http://php.net/function.stripslashes or make it magic_quote_* off in your php.ini magic_quote_gpc off magic_quote_runtime off. you can also use http://php.net/function.ini_set to change it in runtime

Edited by birbal
Link to comment
Share on other sites

Aha, finally found the problem. Since I used ajax for preview, I wasn't able to see page source by using "View page source" Instead I had to use "View selection source", but when I directed output to txt file, I finally saw that it outputs what I want.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...