Foros del Web » Programando para Internet » PHP »

PHP OO BBCode (¡En que me equivoque?)

Estas en el tema de BBCode (¡En que me equivoque?) en el foro de PHP en Foros del Web. Necesto ayuda urgente para implementar BBCode en mi sistema de noticias, bien me pone en negritas las palabras que yo deseo, pero para poner imagenes ...
  #1 (permalink)  
Antiguo 01/09/2012, 11:05
Avatar de RobCo  
Fecha de Ingreso: julio-2012
Mensajes: 50
Antigüedad: 11 años, 9 meses
Puntos: 1
Pregunta BBCode (¡En que me equivoque?)

Necesto ayuda urgente para implementar BBCode en mi sistema de noticias, bien me pone en negritas las palabras que yo deseo, pero para poner imagenes y url se me dificulta. (Ojo: estos Scripts no los hice yo los saque de páginas web mientras investigaba, solo los tengo para aprender de ello y mejorar mi experiencias de programacion). Bien cuando subo la imagen en el boton Imagen, me tira el siguiente error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '://[/url'>', '����\0JFIF\0\0\0d\0d\0\0��\0Ducky\0\0\0\0\0 (\0\0��\0Adobe\0' at line 3

que podria ser

Este es funciones2.php

Código PHP:
<?PHP
function bbcode($detalle) {
    
$detalle str_replace("\n","<br>",$detalle); //Saltos de Linea
    
$detalle str_replace("[b]","<b>",$detalle); //Negrita
    
$detalle str_replace("[/b]","</b>",$detalle); //Negrita
    
$detalle str_replace("[i]","<i>",$detalle); //Italic
    
$detalle str_replace("[/i]","</i>",$detalle); //Italic
    
$detalle str_replace("[u]","<u>",$detalle); 
    
//imagen
    
$detalle str_replace("[/u]","</u>",$detalle); 
    
$detalle str_replace("[img=","<img src='",$detalle); 
    
$detalle str_replace("]","'>",$detalle);
    
//Link
    
$detalle str_replace("[noparse][url]","<a href='$detalle'>",$detalle); 
    
$detalle str_replace("[/url][/noparse]","</a>",$detalle); 
    
    
$detalle str_replace(':S','<img src="smilies/confundido.gif">'$detalle);
    
$detalle str_replace(':)','<img src="smilies/lloron.gif">'$detalle);
    
$detalle str_replace('8)','<img src="smilies/pijo.gif">'$detalle);
    
$detalle str_replace(':D','<img src="smilies/sonrisa.gif">'$detalle);
    
$detalle str_replace(':O','<img src="smilies/sorprendido.gif">'$detalle);

return 
$detalle;
}

function 
filtro_palabras($detalle) {
    
$palabras = array("pudrete","maldito","mamaguevo","mierda","coño de la pepa","concha de la lora","concha","polla","verga","joder","joda","Marico","marico","coño","coño de la madre","tonto""feo""*****");
    
$division explode(" "$detalle);
    foreach (
$division as $key => $valor) {
        foreach (
$palabras as $palabra) {
            if (
strtolower($valor) == $palabra) {
                
$division[$key] = "@&%#";
            }
        }
    }
    
$detalle implode(" ",$division);
return 
$detalle;
}
?>
informacion.php
este es el de postear la informacion
Código HTML:
<html>
<head>
<title>Noticias</title>
</head>
<body>
<script type="text/javascript">
function instag(tag){
var input = document.frmimage.detalle;
if(typeof document.selection != 'undefined' && document.selection) {
var str = document.selection.createRange().text;
input.focus();
var sel = document.selection.createRange();
sel.text = "[" + tag + "]" + str + "[/" +tag+ "]";
sel.select();
return;
}
else if(typeof input.selectionStart != 'undefined'){
var start = input.selectionStart;
var end = input.selectionEnd;
var insText = input.value.substring(start, end);
input.value = input.value.substr(0, start) + '['+tag+']' + insText + '[/'+tag+']'+ input.value.substr(end);
input.focus();
input.setSelectionRange(start+2+tag.length+insText.length+3+tag.length,start+2+tag.length+insText.length+3+tag.length);
return;
}
else{
input.value+=' ['+tag+']Reemplace este texto[/'+tag+']';
return;
}
}
function inslink(){
var input = document.frmimage.detalle;
if(typeof document.selection != 'undefined' && document.selection) {
var str = document.selection.createRange().text;
input.focus();
var my_link = prompt("Enter URL:","http://");
if (my_link != null) {
if(str.length==0){
str=my_link;
}
var sel = document.selection.createRange();
sel.text = "[noparse][url]" + my_link + "[/url][/noparse]";
sel.select();
}
return;
}else if(typeof input.selectionStart != 'undefined'){
var start = input.selectionStart;
var end = input.selectionEnd;
var insText = input.value.substring(start, end);
var my_link = prompt("Enter URL:","http://");
if (my_link != null) {
if(insText.length==0){
insText=my_link;
}
input.value = input.value.substr(0, start) +"[noparse][url]" + my_link + "[/url][/noparse]"+ input.value.substr(end);
input.focus();
input.setSelectionRange(start+11+my_link.length+insText.length+4,start+11+my_link.length+insText.length+4);
}
return;
}else{
var my_link = prompt("Ingresar URL:","http://");
var my_text = prompt("Ingresar el texto del link:","");
input.value+=" [a href=\"" + my_link + "\"]" + my_text + "[/a]";
return;
}
}
</script>

[PHP]
<?php
include("funciones2.php");[/PHP]
header ('Content-type: text/html; charset=utf-8');
// Verificamos que el formulario no ha sido enviado aun
$postback = (isset($_POST["enviar"])) ? true : false;
if($postback){
// errores
error_reporting(E_ALL);
# Altura de el thumbnail en píxeles
define("ALTURA", 100);
# Nombre del archivo temporal del thumbnail
define("NAMETHUMB", "/tmp/thumbtemp");
define("DBHOST", "$servidor");
define("DBNAME", "$database");
define("DBUSER", "$usuario");
define("DBPASSWORD", "$password");
$mimetypes = array("image/jpeg", "image/pjpeg", "image/gif", "image/png");
$name = $_FILES["foto"]["name"];
$type = $_FILES["foto"]["type"];
$tmp_name = $_FILES["foto"]["tmp_name"];
$size = $_FILES["foto"]["size"];
if(!in_array($type, $mimetypes))
die("Seleciones una Imagen o El archivo que subiste no es una Imagen válida");
switch($type) {
case $mimetypes[0]:
case $mimetypes[1]:
$img = imagecreatefromjpeg($tmp_name);
break;
case $mimetypes[2]:
$img = imagecreatefromgif($tmp_name);
break;
case $mimetypes[3]:
$img = imagecreatefrompng($tmp_name);
break;
}
$datos = getimagesize($tmp_name);
$ratio = ($datos[1]/ALTURA);
$ancho = round($datos[0]/$ratio);
$thumb = imagecreatetruecolor($ancho, ALTURA);
imagecopyresampled($thumb, $img, 0, 0, 0, 0, $ancho, ALTURA, $datos[0], $datos[1]);
switch($type) {
case $mimetypes[0]:
case $mimetypes[1]:
imagejpeg($thumb, NAMETHUMB);
break;
case $mimetypes[2]:
imagegif($thumb, NAMETHUMB);
break;
case $mimetypes[3]:
imagepng($thumb, NAMETHUMB);
break;
}
# foto original
$fp = fopen($tmp_name, "rb");
$tfoto = fread($fp, filesize($tmp_name));
$tfoto = addslashes($tfoto);
fclose($fp);
# thumbnail
$fp = fopen(NAMETHUMB, "rb");
$tthumb = fread($fp, filesize(NAMETHUMB));
$tthumb = addslashes($tthumb);
fclose($fp);
// Borra archivos temporales
@unlink($tmp_name);
@unlink(NAMETHUMB);
//proceso de almacenamiento
$fuente = $_POST["fuente"];
$categoria = $_POST["categoria"];
$titulo = (ucfirst($_POST["titulo"]));
$subtitulo = $_POST["subtitulo"];
$detalle = bbcode(filtro_palabras(nl2br(htmlspecialchars(urldecode($_POST["detalle"])))));
$link = mysql_connect(DBHOST, DBUSER, DBPASSWORD) or die(mysql_error($link));;
mysql_select_db(DBNAME, $link) or die(mysql_error($link));
$sql = "INSERT INTO noticias(fuente, categoria, titulo, subtitulo, detalle, foto, thumb, mime)
VALUES
('$fuente', '$categoria', '$titulo', '$subtitulo', '$detalle', '$tfoto', '$tthumb', '$type')";
mysql_query($sql, $link) or die(mysql_error($link));
echo " Archivos Guardados, correctamente ";
exit();
}
?>

<form name="frmimage" id="frmimage" method="post"
enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label>Titulo:</label>
<input name="titulo" type="text" class="text" id="titulo" />
<br /><br />

<label>Subtitulo</label>
<input name="subtitulo" id="subtitulo" cols="60" rows="5" tabindex="4"><br /><br />


<label> Detalle:</label>
<br /><br />

<input type="button" name="Submit" value="Imagen" onClick="inslink()" id="imagen">
<input type="button" name="Submit" value="B" onClick="instag('b')" id="B">
<br /><br />


<textarea name="detalle" id="detalle" cols="60" rows="10" tabindex="4"></textarea>
<br /><br /><br />


<label>Seleciones una imagen</label>

<input name="foto" type="file" class="text" id="foto" />

<p>
</p>
<label>Fuente:</label> <br>
<input name="fuente" type="text" class="text" id="fuente" value="http://" />
</p>
<p>
<label>Categoria:</label><br>
<select name="categoria" id="categoria"> 
<option selected="selected" value="">Seleccionar categor&iacute;a</option>
<optgroup label="-"></optgroup>
<option>Programacion</option>
<option>Informatica</option>
<option>Computacion</option>
<option>Arte</option>
<option>Noticias</option>
<option>Musica</option>
</select>
</p>
<p>
<input name="fecha" type="hidden" id="fecha" />
<input name="enviar" type="submit" id="enviar" value="Publicar" />
</p>
</form>
</body>
</html> 
aqui esta la tabla de datos MySQL

Código:
CREATE TABLE IF NOT EXISTS `noticias` (
`id` int(3) NOT NULL auto_increment,
`titulo` varchar(255) NOT NULL default '',
`subtitulo` text NOT NULL,
`detalle` text NOT NULL,
`fuente` varchar(255) NOT NULL default '',
`categoria` varchar(10) NOT NULL,
`foto` blob NOT NULL,
`thumb` blob NOT NULL,
`mime` varchar(40) NOT NULL default '',
`fecha` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ;
  #2 (permalink)  
Antiguo 01/09/2012, 12:06
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: BBCode (¡En que me equivoque?)

Tienes varios problemas en ese código, pero el causante del error es que no estás escapando los datos antes de incluirlos en la consulta.

$dato = mysql_real_escape_string($dato);

Con eso debes poder insertar sin problemas.

Por cierto, la librería mysql será obsoleta en un futuro cercano, por lo que te convendría usar en su lugar mysqli.
__________________
- León, Guanajuato
- GV-Foto
  #3 (permalink)  
Antiguo 01/09/2012, 12:28
Avatar de RobCo  
Fecha de Ingreso: julio-2012
Mensajes: 50
Antigüedad: 11 años, 9 meses
Puntos: 1
Respuesta: BBCode (¡En que me equivoque?)

Ah! o.k gracias. Estare al tanto con MySQLI para cambiar mi sistema

Etiquetas: bbcode, sistema+de+noticias
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 23:23.