Foros del Web » Programando para Internet » PHP »

ejecutar un codigo que aparece varias veces

Estas en el tema de ejecutar un codigo que aparece varias veces en el foro de PHP en Foros del Web. Esto trabajando en un proyecto y tengo un codigo que se repite varias veces y para ahorrar unas lineas y claridad he pensado a ver ...
  #1 (permalink)  
Antiguo 22/04/2010, 01:53
 
Fecha de Ingreso: julio-2007
Mensajes: 58
Antigüedad: 16 años, 8 meses
Puntos: 1
ejecutar un codigo que aparece varias veces

Esto trabajando en un proyecto y tengo un codigo que se repite varias veces y para ahorrar unas lineas y claridad he pensado a ver si se podia simplificar de alguna manera. Se me han ocurrido varios metodos y he estado buscando informacion pero no he sacado nada en claro, asi que a ver si podeis echarme una manecita. Se agradeceria.

Se podria hacer un archivo "codigo.php" y ejecutarlo en el php en el que quiero que se ejecute.
  #2 (permalink)  
Antiguo 22/04/2010, 02:06
 
Fecha de Ingreso: junio-2006
Ubicación: Antofagasta
Mensajes: 216
Antigüedad: 17 años, 10 meses
Puntos: 7
Respuesta: ejecutar un codigo que aparece varias veces

podrías crear una funcion con dicho codigo, esa funcion puedes colocarla en otro archivo para que asi lo incluyas en las paginas que sean necesarias, luego en el lugar donde necesitas ejecutar ese codigo mandas a llamar a la funcion, si es que necesita parametros, le encias los parametros necesarios.

Puedes postear tu código que necesitas ejecutar varias veces para darte mas detalles.

Saludos
  #3 (permalink)  
Antiguo 22/04/2010, 02:40
 
Fecha de Ingreso: julio-2007
Mensajes: 58
Antigüedad: 16 años, 8 meses
Puntos: 1
Respuesta: ejecutar un codigo que aparece varias veces

archivo captcha.php
Código PHP:
<?php   

    
require_once('captcha.class.php');
    
$captcha = new Captcha;
    
$captchaImage $captcha->create();
    
      
//verificamos si variables POST estan declaradas   
      
if(isset($_POST[$captcha->captchaInputName])){        
      
//verificamos el captcha        
      
$verified $captcha->verify($_POST[$captcha->captchaInputName]);        
      if(
$verified){                
      
$message='Correcto';        
      }else{                
      
$message='Incorrecto';        
      }   
      }
?>
      <html>
      <head>
      <title>Captcha</title>
      </head>
      <body>
      <?php        
      
if(isset($message)){                
      echo 
$message;        
      }else{
      
?><form name="formulario" method="post" action="captcha.php">
      <?php echo $captchaImage?>
      <input type="submit" value="Verificar" />
      <?php ?>
      </form>
      
      </body>
      
      </html>


Este es el codigo que quiero que se ejecute en otra pagina dependiendode los envios de formularios se que hacen y otras cosas.
  #4 (permalink)  
Antiguo 22/04/2010, 03:56
 
Fecha de Ingreso: julio-2007
Mensajes: 58
Antigüedad: 16 años, 8 meses
Puntos: 1
Respuesta: ejecutar un codigo que aparece varias veces

Se puede incluir el codigo html dentro de la funcion?? estoy intentando crear la funcion pero no consigo meter el codigo html
  #5 (permalink)  
Antiguo 22/04/2010, 04:03
 
Fecha de Ingreso: marzo-2010
Ubicación: Barcelona
Mensajes: 657
Antigüedad: 14 años
Puntos: 26
Respuesta: ejecutar un codigo que aparece varias veces

el codigo html dentro de php se hace con echos:

Código PHP:
echo '<table><tr>';
echo 
'<td>fila 1 col 1</td>';
echo 
'<td>fila 1 col 2</td>';
echo 
'</tr></table>'
  #6 (permalink)  
Antiguo 22/04/2010, 05:07
 
Fecha de Ingreso: julio-2007
Mensajes: 58
Antigüedad: 16 años, 8 meses
Puntos: 1
Respuesta: ejecutar un codigo que aparece varias veces

Gracias Vallu, lo he intentado pero parece que saltan un par de errores, pongo todo el codigo porque ya no se de donde saltan los errores. jejeje



captcha.class.php
Código PHP:
<?php
    
/*
        File: captcha.class.php
        Author: Jamie McConnell
        Email: jamie[at]blue44.com
        URL: http://nodstrum.com/2007/09/23/captcha/
        Date: 22/09/2007
        License: GPL
        
        If you do use this script, please reference me: http://nodstrum.com
        
        Usage Instructions:
            1.    On your form page add the following lines:
                require_once('captcha.class.php');
                $captcha = new Captcha;
                $captchaImage = $captcha->create();
            
            2.    In your form, where you want the Captcha displayed add this:
                <?= $captchaImage; ?>
            
            3.    On the processing page add this:
                require_once('captcha.class.php');
                $captcha = new Captcha;
                $verified = $captcha->verify($_POST[$captcha->captchaInputName]);
                
            4.    In your processing check for $verified being true/false.
                if($verified) {
                    // Captcha was correct
                } else {
                    // Captcha was incorrect
                }
                
            5.    Thats it! :)
                Enjoy.
    */
    
class Captcha {
        
/* Variables */
        
var $imageDirectory 'imgs'// No forward slash - must be writable, chmod 777
        
var $imageURL 'http://miweb/imgs'// No forward slash.
        
var $captchaLabel 'Please complete the Captcha:'// This is what is shown just above the captcha image.
        
var $captchaBoxStyle 'border: 1px solid #ccc; padding: 3px; margin: 3px; width: 210px; font-family: verdana; font-size: 11px;'// This is the style for the captcah box.
        
        /* Advanced Users Variables */
        
var $captchaLength 5;
        var 
$imageWidth 130;
        var 
$imageHeight 30;
        var 
$imageTextColor = array(0,0,0); // RGB (Black)
        
var $imageLineColor = array(255,20,147); // RGB (Black)
        
var $imageBGColor = array(176,226,255); // RBG (Light Blue)
        
var $captchaInputName 'captcha_input';
        var 
$cookieName 'NodstrumCaptcha';
        var 
$cookieTimeout 300// 5 mins.
        
var $cleanupImages true;
        
        
// Check the directories exist and are writeable.
        
        
function create() {
            
// Cleanup before doing anything.
            
$this->cleanup();
            
            
// Define the dataset and set the key.
            
$dataset = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','p','q','r','s','t','u','v','w','x','y','z',1,2,3,4,5,6,7,8,9);
            
shuffle($dataset);
            
$key ''// Initialise key.
            
for($i=0$i<$this->captchaLength$i++) {
                
$key .= $this->strtoupper_modified(trim($dataset[rand(0count($dataset))]));
            }
                        
            
// Prep and generate the key hash - sha1.
            
$key trim($key);
            
$keyHash sha1($key);
            
            
// Generate the image.
            
$imageName $this->generateImage($key);
            if(!
$imageName) {
                die(
'There was an error generating the Captcha - Check your directory path and permissions.');
            } else {
                
// Set the cookie.
                
$cookie setcookie($this->cookieName$keyHash, (time()+$this->cookieTimeout), '/');
                if(!
$cookie) {
                    die(
'Unable to set the cookie - Cookies must be enabled to use this form.');
                } else {
                    
// Return the captcha and input box.
                    
$captchaBox '<div style="'.$this->captchaBoxStyle.'">
                                        '
.$this->captchaLabel.'<br>
                                        <img src="'
.$this->imageURL.'/'.$imageName.'" width="'.$this->imageWidth.'" height="'.$this->imageHeight.'" style="border: 1px solid #000; margin: 2px;" alt="CAPTCHA Image"><br>
                                        <input type="text" size="22" name="'
.$this->captchaInputName.'" value="">
                                    </div>'
;
                    return 
$captchaBox;    
                }
            }
        } 
// Create :: Function.
        
        
function generateImage($key) {
            
// Create the image.
            
$imageName 'CAPTCHA_'.(time()+$this->cookieTimeout).'_'.rand(1,101).'_'.rand(201,9007).'.png';
            
$imageFilename ''.$this->imageDirectory.'/'.$imageName.'';
            
$image imagecreate($this->imageWidth$this->imageHeight);
            
$background imagecolorallocate($image$this->imageBGColor[0], $this->imageBGColor[1], $this->imageBGColor[2]);
            
            
// Set the text colour.
            
$textColor imagecolorallocate($image$this->imageTextColor[0], $this->imageTextColor[1], $this->imageTextColor[2]);
            
$lineColor imagecolorallocate($image$this->imageLineColor[0], $this->imageLineColor[1], $this->imageLineColor[2]);
            
            
// Add some lines to screw over the form hackers.
            
imageline($image0,0,120,20$lineColor); 
            
imageline($image1,0,121,21$lineColor); 
            
imageline($image40,0,80,50$lineColor);
            
imageline($image41,0,81,51$lineColor);
            
imageline($image90,0,80,50$lineColor);
            
            
// Put spaces in between the letters.
            
$keySplit $this->str_split_php4($key);
            
$formattedKey ''// Initialise it.
            
for($i=0$i<$this->captchaLength$i++) {
                
$formattedKey .= ''.$keySplit[$i].' ';
            }
            
            
// Add the text to the image.
            
imagestring($image52010$formattedKey$textColor); 
                        
            
// Save the image.
            
$saveImage imagepng($image$imageFilename9);
            
imagedestroy($image);
            if(
$saveImage) {
                return 
$imageName;
            } else {
                return 
false;
            }
        } 
// GenerateImage :: Function.
        
        
function verify($userInput) {
            if(isset(
$_COOKIE[$this->cookieName])) {
                
// Get the cookie and hash the user input.
                
$cookieDataHash trim($_COOKIE[$this->cookieName]);
                
$userInputF $this->strtoupper_modified(trim($userInput));
                
$userInputHash sha1($userInputF);
                
                
// Cleanup - the form has been submitted.
                
$this->cleanup();
                
                
// Verfiy that the cookie data length is 40 characters long - SHA1 standard - it might have been tampered with.
                
if(strlen($cookieDataHash) == 40) {
                    if(
$cookieDataHash == $userInputHash) {
                        return 
true;
                    } else {
                        return 
false;
                    } 
// Cookie and user inputs match.
                
} else {
                    
// The cookie data has been tampered with, dont verify.
                    
return false;
                } 
// CookieDataLength.
            
} else {
                
// No cookie was found, probably deleted, dont verify.
                
return false;
            } 
// Cookie exists.
        
// Verify :: Function.
        
        
function cleanup() {
            
setcookie($this->cookieName'', (time()-900000000), '/');
            if(
$openedDir opendir($this->imageDirectory)) {
                while((
$file readdir($openedDir)) !== false) {
                    if(
$file != "." && $file != "..") {
                        
$filenameE explode('_'$file);
                        
$fileExpires $filenameE[1];
                        if(
$fileExpires <= time()) {
                            
unlink($this->imageDirectory.'/'.$file);
                        } else {
                            
// Not expiring yet.
                        
}
                    } else {
                        
// Skip it.
                    
}
                } 
// while - reading directory.
            
// Directory opened.
        
// Cleanup :: Function.
        
        
function str_split_php4($text$split 1) {
            if (!
is_string($text)) return false;
            if (!
is_numeric($split) && $split 1) return false;
            
$len strlen($text);
            
$array = array();
            
$s 0;
            
$e=$split;
            while (
$s <$len) {
                
$e=($e <$len)?$e:$len;
                
$array[] = substr($text$s,$e);
                
$s $s+$e;
            }
            return 
$array;
        } 
// str_split_php4 :: Function - php.net (kjensen - http://uk3.php.net/str_split)
        
        
function strtoupper_modified($string) {
            
$splitString $this->str_split_php4($string);
            
$fString ''// Initialise it.
            
foreach($splitString as $value) {
                if(
is_numeric($value)) {
                    
$fString .= $value;
                } else {
                    
$fString .= strtoupper($value);
                }
            }
            
            return 
$fString;
        } 
// strtoupper_modified :: Function
        
    
// Captcha :: Class.

?>






fun.captcha.php
Código PHP:
<?php   

   
function autocaptcha(){ 

   

    require_once(
'captcha.class.php');
    
$captcha = new Captcha;
    
$captchaImage $captcha->create();
    
      
//verificamos si variables POST estan declaradas   
      
if(isset($_POST[$captcha->captchaInputName])){        
      
//verificamos el captcha        
      
$verified $captcha->verify($_POST[$captcha->captchaInputName]);        
      if(
$verified){                
      
$message='Correcto';        
      }else{                
      
$message='Incorrecto';        
      }   
      }
      
      echo 
'<html>';
      echo 
'<head>';
      echo 
'<title>Captcha</title>';
      echo 
'</head>';
      echo 
'<body>';
             
      echo 
'if(isset($message)){';          
      echo 
'echo $message;';  
      echo 
'}else{';
      echo 
'<form name="formulario" method="post" action="fun.captcha.php">';
      echo 
'echo $captchaImage;';
      echo 
'<input type="submit" value="Verificar" />';
      echo 
' }';
      echo 
'</form>';
      echo 
'</body></html>';
   
   
   

?>




muestra.php

Código PHP:
<html>
<head>
    <title>Formulario Web</title>
</head>
<body>


  <?php
require_once('fun.captcha.php');
echo 
autocaptcha();
?>



</body>
</html>

Esos son los 3 archivos que componen el codigo. Con el archivo muestra quiero que se muestre el captcha, pero la funcion me devuelve lo siguiente.


Código HTML:
Warning: Cannot modify header information - headers already sent by (output started at Miweb\muestra.php:8) in MiWeb\captcha.class.php on line 160

Warning: Cannot modify header information - headers already sent by (output started at MiWeb\muestra.php:8) in MiWeb\captcha.class.php on line 79
Unable to set the cookie - Cookies must be enabled to use this form.
Aclarar que el codigo de la funcion captcha lo ejecuto sin ponerlo en la funcion y funciona correctamente.
  #7 (permalink)  
Antiguo 23/04/2010, 01:42
 
Fecha de Ingreso: julio-2007
Mensajes: 58
Antigüedad: 16 años, 8 meses
Puntos: 1
Respuesta: ejecutar un codigo que aparece varias veces

creo que el error esta en --> echo autocaptcha();
ya que cuando lo quito, no salta el error, pero, lo que necesito es mostrarlo,

lo estoy mostrando bien??
o se muestra de alguna otra manera??
  #8 (permalink)  
Antiguo 26/04/2010, 11:10
 
Fecha de Ingreso: julio-2007
Mensajes: 58
Antigüedad: 16 años, 8 meses
Puntos: 1
Respuesta: ejecutar un codigo que aparece varias veces

bueno creo que he encontrado el error pero no se como solucionarlo, parece que esta en el setcookie() parece que hace algo raro que no me deja hacer funcionar.
Por favor si sabeis como solucionarlo lo agradeceria muchisimo

Etiquetas: ejecutar
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 09:09.