Problema caricamento immagini - refresh pagina

mattbt

Nuovo Utente
12 Apr 2011
2
0
0
Ciao a tutti, sono assolutamente nuovo di php, devo completare alcune pagine per un progetto di solidarietà. Sto cercando di creare una pagina per un'associazione in cui l'utente registrato possa caricare una propria immagine ed eventualmente sovrascriverla in seguito, mi da un errore apparentemente molto comune ma cercando su forum e articoli non sono riuscito a risolvere... non so bene come lavorare con sessioni e header.
in locale il caricamento immagine funziona bene. In remoto, mi da l'errore sull'header. Il codice di seguito potrebbe contenere orrori. Vi sono infinitamente grato per qualsiasi suggerimento, da alcuni giorni non riesco a ottenere risultati.

riporto l'inizio del file..

Codice:
<?php
 session_start();
	if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == ''))
	$ctr_sessione = "noses";
	$s_login=$_SESSION['SESS_LOGIN'];
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Camion del the | Partecipa</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/cufon-yui.js"></script>
<script type="text/javascript" src="js/arial.js"></script>
<script type="text/javascript" src="js/cuf_run.js"></script>
</head>
<body>
<?php
	if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
		echo '<ul class="err">';
		foreach($_SESSION['ERRMSG_ARR'] as $msg) {
			echo '<li>',$msg,'</li>'; 
		}
		echo '</ul>';
		unset($_SESSION['ERRMSG_ARR']);
	}
?>
<div class="main">
  <div class="header">
    <div class="header_resize">
      <div class="logo">
        <h1><a href="index.php"><span>Camion</span> del The <br /><small>  mettiamoci la faccia! </small></a></h1>
      </div>
      <div class="menu">
        <ul>
          <li><a href="index.php">Home</a></li>
          <li><a href="ilprogetto.php">Il progetto</a></li>
          <li><a href="partecipa.php" class="active">Partecipa</a></li>
          <li><a href="about.php">Chi Siamo</a></li>
          <li><a href="contact.php">Contatti</a></li>
        </ul>
      </div>
      <div class="clr"></div>
    </div>
    <div class="headert_text_resize_other">

e di seguito il div contenente la parte di upload immagine..

Codice:
    <div class="body_resize">
      <div class="left">
        <div class="resize_bg">
        <!-- if not login (significa che non ha pagato!!) -->
    
[... form di iscrizione...]
          
          <!-- if login -> pagina utente -->
          <?php
		} else {
		?>
          <h2> Grazie per aver contribuito al progetto!</h2>
          <p>
          <br /> Seleziona di seguito l'immagine che desideri mandare in Tanzania con il camion del The!
  </p>
  
  <!-- ###################### -->
  <!-- codice upload immagine -->
  <!-- ###################### -->
  <?php
  session_start;
  
  //Include database connection details
	require_once('config.php');
  	//Connect to mysql server
	$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
	if(!$link) {
		die('Failed to connect to server: ' . mysql_error());
	}
	
	//Select database
	$db = mysql_select_db(DB_DATABASE);
	if(!$db) {
		die("Unable to select database");
	}
  
//define a maxim size for the uploaded images in Kb
 define ("MAX_SIZE","100"); 

//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

//This variable is used as a flag. The value is initialized with 0 (meaning no error  found)  
//and it will be changed to 1 if an errro occures.  
//If the error occures the file will not be uploaded.
 $errors=0;
//checks if the form has been submitted
 if(isset($_POST['Submit'])) 
 {
 	//reads the name of the file the user submitted for uploading
 	$image=$_FILES['image']['name'];
 	//if it is not empty
 	if ($image) 
 	{
 	//get the original name of the file from the clients machine
 		$filename = stripslashes($_FILES['image']['name']);
 	//get the extension of the file in a lower case format
  		$extension = getExtension($filename);
 		$extension = strtolower($extension);
 	//if it is not a known extension, we will suppose it is an error and will not  upload the file,  
	//otherwise we will do more tests
 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
 		{
		//print error message
 			echo '<h1>Unknown extension!</h1>';
 			$errors=1;
 		}
 		else
 		{
//get the size of the image in bytes
 //$_FILES['image']['tmp_name'] is the temporary filename of the file
 //in which the uploaded file was stored on the server
 $size=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
	echo '<h1>You have exceeded the size limit!</h1>';
	$errors=1;
}

//we will give an unique name, for example the time in unix time format
$image_name=$s_login.'.'.$extension;//time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="uimages/".$image_name;
//we verify if the image has been uploaded, and print error instead
//Create INSERT query
	$qry = "UPDATE users SET urlpic = '$newname' WHERE member_id = '".$_SESSION['SESS_MEMBER_ID']."'";
	//echo $qry;
	$result = @mysql_query($qry);
	//Check whether the query was successful or not
	if($result) {
	    $_SESSION['SESS_PIC_URL'] = $newname;
		//header("location: register-success.php");
		//exit();
	}else {
		die("Query failed");
	}
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied) 
{
	echo '<h1>Copy unsuccessfull!</h1>';
	$errors=1;
}}}}

//If no errors registred, print the success message
 if(isset($_POST['Submit']) && !$errors) 
 {
 	//echo "<h1>File Uploaded Successfully! Try again!</h1>";
 	header("refresh:1;url=partecipa.php");// "location: partecipa.php");
 	//exit;
 }

 ?>

 <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
 <?php 
          session_start();
          $test = $_SESSION['SESS_PIC_URL'];
			if(!isset($_SESSION['SESS_PIC_URL']) || (trim($_SESSION['SESS_PIC_URL']) == ''))
		  	//if(!isset($_SESSION['SESS_MEMBER_ID']))
		  {?>
			
			<?php
		} else {
		//print($test);
		?>
		<table>
		<tr><td><img src="<?php echo $test; ?>"></img></td></tr>
		</table>
		<?php
		}
		?>  
 
 <form name="newad" method="post" enctype="multipart/form-data"  action="">
 <table>
 	<tr><td><input type="file" name="image"></td></tr>
 	<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
 </table>	
 </form>
          <?php
		}
		?> 
          
        </div>
      </div>

L'errore che mi da in remoto al caricamento di un'immagine è

Warning: Cannot modify header information - headers already sent by (output started at /home/web/www.sangiu9.com/www/temp_teatruck/partecipa.php:14) in /home/web/www.sangiu9.com/www/temp_teatruck/partecipa.php on line 219


e la riga incriminata è
Codice:
//If no errors registred, print the success message
 if(isset($_POST['Submit']) && !$errors) 
 {
 	//echo "<h1>File Uploaded Successfully! Try again!</h1>";
 	[COLOR="red"]header("refresh:1;url=partecipa.php");// "location: partecipa.php");[/COLOR]
 	//exit;
 }

dove faccio il refresh della pagina se il caricamento non da errori.

Grazie per il vostro tempo,
Matteo
 

Eliox

Utente Attivo
25 Feb 2005
4.390
3
0
Non puoi inserire header() in questo modo, va posizionato prima di qualsiasi output HTML, potresti risolvere con un JavaScript.
 

alessandro1997

Utente Attivo
6 Ott 2009
5.302
1
0
26
Roma
alessandro1997.netsons.org
Se proprio vuoi stare tranquillo metti all'inizio della pagina:
PHP:
<?php
ob_start();
?>
Poi invia tutto l'output che vuoi. Metti alla fine:
PHP:
<?php
$content = ob_get_contents();
ob_end_clean();

// QUI INVIA GLI HEADER
// ...

echo $content;
?>
Così non avrai problemi.
 

borgo italia

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
4 Feb 2008
16.046
150
63
PR
www.borgo-italia.it
ciao
e se non vuoi usare l' ob_start sostituisci la riga dell'header con

echo "<meta http-equiv='Refresh' content='1; URL=partecipa.php'>";
 

mattbt

Nuovo Utente
12 Apr 2011
2
0
0
Grandi. Ho provato ad usare la soluzione di borgo italia e funziona, a parte un effetto doppio refresh che non disturba più di tanto.

avevo introdotto la riga header... semplicemente per ottenere un refresh della pagina. Come mi avete suggerito, header va prima di ogni non-php codice, quindi solitamente per fare un refresh su una pagina mista si usa un echo? o che altro?
Pensavo di mettere tutto il codice php su un file esterno: in tal caso conterrebbe solo php e potrei usare la riga header o rimane una soluzione contorta?

@alessandro1997: provo ad interpretare la tua soluzione di seguito,

inizio file
PHP:
<?php 
ob_start(); 
?>

Poi invia tutto l'output che vuoi.
[quindi inserisco il file di prima, misto html e php, contenente la riga header]

Metti alla fine: [del file?]

PHP:
<?php 
$content = ob_get_contents(); 
ob_end_clean(); 

// QUI INVIA GLI HEADER [COLOR="red"][di nuovo riga header?][/COLOR]
// ... 

echo $content; 
?>

mi sfugge come fa a sapere che voglio chiamare header al successo dell'upload immagine. Spero di non aver toccato il fondo con questa domanda.

E grazie infinite a tutti.
Lo so devo mettermi a studiare. :book: Sono stato preso in controtempo da questo progetto. 0:)
 
Discussioni simili
Autore Titolo Forum Risposte Data
giuseppe_123 [WordPress] problema installazione temi, plugin e caricamento immagini WordPress 5
P Problema caricamento/sostituzione immagini galleria php-jquery jQuery 2
LaKanka Problema caricamento immagini PHP 6
G Problema caricamento tabelle MySql da PhP PHP 0
A problema caricamento codice <iframe video youtube PHP 3
S Problema con il caricamento di un'immagine su aruba Hosting 11
B Problema caricamento files con FTP Hosting 5
P Problema: visualizzare a schermo una nuova pagina durante l'attesa di caricamento PHP 1
G problema caricamento condizionale slideshow FlexSlider Javascript 0
F Problema caricamento social plugin Javascript 0
A galleria jquery: problema nel caricamento di una immagine da un'anteprima HTML e CSS 10
Z Problema di caricamento Ajax su IE Ajax 11
G problema caricamento 2 js nella stessa pagina Javascript 0
G problema caricamento effetti jquery jQuery 0
B Problema caricamento dati .NET Framework 1
M Problema caricamento Flash 1
Dragon Problema di caricamento swf e img nella stessa pagina Flash 8
L ProgressBar - problema caricamento Flash 3
mythar Problema caricamento pagina ASP.NET 1
O Problema caricamento rete Reti LAN e Wireless 0
O Problema caricamento rete Reti LAN e Wireless 0
D Problema cache: forzare caricamento swf Classic ASP 1
M Problema programmi FTP e caricamento dati Discussioni Varie 3
I Sto progettando nuovi siti utilizzando bootstrap e devo dire funziona bene, l'unico problema e la maschera -moz- HTML e CSS 0
K Problema form update PHP 2
O problema con dvr dahua xvr5116 IP Cam e Videosorveglianza 0
S Problema nel ciclare un json Javascript 0
G Problema con Xampp Web Server 1
andrea barletta Problema con miniature comandi Photoshop 0
I problema con alice Posta Elettronica 0
K Problema Inner join PHP 1
F firefox problema http Linux e Software 0
N Problema con position absolute e overflow HTML e CSS 4
E Problema jquery Success jQuery 2
L Problema con inner join PHP 11
K [php] Problema con inner join PHP 4
E problema selezione sfumata Photoshop 2
K [PHP] Problema con variabili concatenate. PHP 1
A Problema filtro fluidifica Photoshop Photoshop 1
H Problema Bordi Scontorno Photoshop 1
O problema con query PHP 4
R Problema installazione Realtek WiFi USB rtl8821 Reti LAN e Wireless 1
I problema con 2 account Posta Elettronica 1
L problema collegamento file css con html HTML e CSS 1
Y Problema percorso file in rete PHP 1
N Problema SEO "L'URL non si trova su Google" SEO e Posizionamento 4
E Problema accesso a file con app sviluppata con MIT APP INVENTOR 2 Sviluppo app per Android 0
P Problema acquisizione clienti Webdesign e Grafica 1
F NetBeans problema creazione progetto Java Windows e Software 0
M Problema con Try Catch PHP 0

Discussioni simili