Précédent   Forum des professionnels en informatique > PHP > Langage > Contribuez
Contribuez Proposez vos articles, cours, tutoriels, FAQ, sources, etc. pour PHP
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse Proposer ce sujet en actualité
 
Outils de la discussion
Publicité
'
Vieux 14/08/2009, 09h26   #81
Candidat au titre de Membre du Club
 
Homme
Étudiant
Inscription : juillet 2008
Messages : 48
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 23
Localisation : France

Informations professionnelles :
Activité : Étudiant

Informations forums :
Inscription : juillet 2008
Messages : 48
Points : 13
Points : 13
Envoyer un message via MSN à Passarinho44
Par défaut Changer un attribut dans la barre d'adresse

Voici une petite fonction permettant de changer la valeur d'un attribut dans la barre d'adresse

Un code qui peut être pratique pour faire de la pagination ou des tris plus efficacement sans avoir à modifier le lien dès qu'on rajoute un attribut de tri.

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * Retourne l'url actuelle en ajoutant le type voulu
 * Le type est remplacé s'il existait déjà
 * @example sur la page index.php?page=1&request=1 => actual_url('page', '2') retournera index.php?request=1&page=2
 * @param $type : le type à changer
 * @param $value : la valeur à mettre
 * @return $url, l'url modifié
 */
function actual_url( $type, $value ) {
	// On récupère le lien de la page actuelle 
	$a_url = explode("/", $_SERVER['PHP_SELF']);
	// Ici $url contient quelque chose de la forme : page.php
	$url = $a_url[sizeof($a_url) - 1];
 
	// S'il y a des paramètres déjà initialisés 
	if ( $_SERVER['QUERY_STRING'] != "" ) {
		// On récupère tous les paramètres dans un tableau
		$a_query_string = explode("&", $_SERVER['QUERY_STRING']);
		$url_temp = "";
		// On parcourt tous les paramètres
		for ( $k = 0 ; $k <= sizeof($a_query_string) ; $k++ ) {
			// On les coupe au niveau du =
			$a_query_type = explode("=", $a_query_string[$k] );
			// On récupère le type
			$query_type = $a_query_type[0];
 
			// Si le type est différent du type passé en paramètre dans la fonction et qu'il n'est pas null (sinon on ne fait rien)
			if ( $query_type != $type and $query_type != "" ) {
				// On l'ajoute à la fin de l'url
				$url_temp .= $a_query_string[$k] . '&';
			}
 
		}
		// Si il y a d'autres paramètres que celui passé dans la fonction
		if ( $url_temp != "" ) {
			$url .= '?' . $url_temp . $type . '=' . $value;
		} else {
			$url .= '?' . $type .'=' . $value;
		}
	// S'il n'y a pas de paramètres initialisés
	} else {
		$url .= '?' . $type . '=' . $value;
	}
 
	return $url;
}
Bien sur ce code peut surement être optimisé, n'hésitez pas à me le dire si vous trouvez des erreurs.
Passarinho44 est déconnecté   Envoyer un message privé Réponse avec citation 02
Vieux 14/08/2009, 14h19   #82
Modérateur
 
Avatar de ThomasR
 
Homme Thomas Rambaud
Développeur Web
Inscription : décembre 2007
Messages : 2 140
Détails du profil
Informations personnelles :
Nom : Homme Thomas Rambaud
Âge : 25
Localisation : France

Informations professionnelles :
Activité : Développeur Web
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : décembre 2007
Messages : 2 140
Points : 2 885
Points : 2 885
Bonjour,

Voici une classe qui permet de générer des miniatures d'une image. Elle permet le recadrage, la découpe proportionnelle, d'écrire du texte sur les miniatures, de mettre une icone, etc..

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
<?php
 
/**
 * @author Thomas Rambaud
 * @copyright 2009
 * @version 1.3
 */
 
class thumbs_builder {
 
    protected $_source,
        $_background_src,
        $_thumbs_quality,
        $_save_directory,
        $_border,
        $_text,
        $_icon,
        $_current_thumb,
        $_allowed_position;
 
    public function __construct($source_src, $save_directory, $thumbs_quality = 100){
        $this->set_source_src($source_src);
        $this->set_save_directory($save_directory);
        $this->set_thumbs_quality($thumbs_quality);                
        $this->_allowed_position = array('top','bottom','left','right','center');        
    }
 
    //-----------
    // PROPERTIES
    //-----------
 
      // Getters
 
      public function get_source_path(){
          return $this->_source['src'];
      }
 
      public function get_source_width(){
          return $this->_source['sizes'][0];
      }
 
      public function get_source_height(){
          return $this->_source['sizes'][1];
      }
 
      public function get_save_directory(){
          return $this->_save_directory;
      }
 
      public function get_current_thumb(){
          return $this->_current_thumb['img'];
      }
 
      public function get_current_thumb_width(){
          return $this->_current_thumb['sizes'][0];
      }
 
      public function get_current_thumb_height(){
          return $this->_current_thumb['sizes'][1];
      }
 
      public static function get_random_string($chars_count = 4){
          $caracteres = "123AaBbCcDdEe456fGgHhIiJjKkLlMmNn789PQqRrSsTtUuVvWwXxYyZz0";
          $chaine = '';
          srand(time());
          for ($i=0;$i<$chars_count;$i++){
              $chaine.=substr($caracteres, rand()%(strlen($caracteres)), 1);
          }
          return $chaine;
      }
 
      public static function get_image_extension($fn_or_path){
          return strtolower(substr($fn_or_path, strrpos($fn_or_path, '.') + 1));
      }
 
      public static function get_rgb_from_hexa($hex){
          if($hex[0] == '#') $hex = substr($hex,1);
          $nb_cars = strlen($hex);
          if($nb_cars == 6) list($r, $g, $b) = array($hex[0].$hex[1], $hex[2].$hex[3], $hex[4].$hex[5]);
          elseif($nb_cars == 3) list($r, $g, $b) = array($hex[0].$hex[0], $hex[1].$hex[1], $hex[2].$hex[2]);
          else return false;          
          $r = hexdec($r); $g = hexdec($g); $b = hexdec($b);
          return array($r, $g, $b);
      }
 
      // Setters
 
      public function set_source_src($source_src){
          if(file_exists($source_src)){
              $this->_source['src'] = $source_src;
              $this->_source['sizes'] = getimagesize($source_src);
              $this->_source['img'] = $this->build_image_from_path($source_src, $this->_source['sizes'][2]);
              $this->_current_thumb =& $this->_source;
          }
          else{
             die('L\'image source définie n\'existe pas : <span style="color:red">'.$source_src.'</span>');
          }
      }
 
      public function set_save_directory($save_directory){
          if(is_dir($save_directory))
              $this->_save_directory = $save_directory;
          else
              die('Le dossier d\'enregistrement des miniatures n\'existe pas : <span style="color:red">'.$save_directory.'</span>');
      }
 
      public function set_thumbs_quality($quality){
          $this->_thumbs_quality = ($quality >= 0 && $quality <= 100) ? $quality : 100;
      }
 
      public function set_icon($icon_src, $position_top, $position_left, $alpha=null){
         if(file_exists($icon_src)){
             $this->_icon['src'] = $icon_src;
             $this->_icon['sizes'] = getimagesize($icon_src);             
             $this->_icon['img'] = $this->build_image_from_path($icon_src, $this->_icon['sizes']);
             $this->set_icon_position($position_top, $position_left);
             if($alpha != null) $this->set_icon_alpha($alpha);
         }
         else{
             die('Le fichier image de l\'icône est inexistant ou n\'est pas un fichier : <span style="color:red">'.$icon_src.'</span>');
         }
      }
 
      public function set_icon_alpha(int $alpha){
          $this->_icon['alpha'] = $alpha;
      }
 
      public function set_icon_position($position_top, $position_left){
          $this->_icon['position_top'] = $position_top;
          $this->_icon['position_left'] = $position_left;
      }
 
      public function set_icon_autoresize(bool $bool){
          $this->_icon['autoresize'] = $bool;      
      }
 
      public function set_text($text, $position_top, $position_left, $hex_color, $size = 20){
          $this->_text['text'] = $text;
          $this->_text['position_top'] = $position_top;
          $this->_text['position_left'] = $position_left;
 
          $this->set_text_size($size);
          $this->set_text_font(3);
          $this->set_text_color($hex_color);
          $this->reload_text_sizes();
      }
 
      public function set_text_color($hex){
          $this->_text['color'] = self::get_rgb_from_hexa($hex);   
      }
 
      public function set_text_font($font){
          $this->_text['font'] = $font;
          $this->reload_text_sizes();
      }
 
      public function set_text_size($size){
          $this->_text['size'] = $size;
          $this->reload_text_sizes();   
      }    
 
      public function set_text_autoresize(bool $bool){
          $this->_text['autoresize'] = $bool;   
      }
 
      public function set_text_shadow(bool $bool){
          $this->_text['shadow'] = $bool;       
      } 
 
      public function remove_icon(){
          $this->_icon = null;
      }
 
      public function remove_text(){
          $this->_text = null;
      }
 
    // ----------------
    // PUBLIC FUNCTIONS
    // ----------------
 
       public function resize($thumb_width, $thumb_height, $background_color, $filename = null){
           $this->clear_current_thumb();
 
           $this->_current_thumb['img'] = $this->create_image($thumb_width, $thumb_height);
           $this->_current_thumb['sizes'][0] = $thumb_width;
           $this->_current_thumb['sizes'][1] = $thumb_height;
 
           $color = self::get_rgb_from_hexa($background_color);
           $color = imagecolorallocate($this->_current_thumb['img'],$color[0],$color[1],$color[2]);
           imagefill($this->_current_thumb['img'], 0, 0 , $color);
 
           $ratio_source = $this->_source['sizes'][0] / $this->_source['sizes'][1];
           $ratio_x = $this->_source['sizes'][0] / $thumb_width;
           $ratio_y = $this->_source['sizes'][1] / $thumb_height;
 
           $margin_left = 0;
           $margin_top = 0;
 
           if ($ratio_x > $ratio_y){
               $img_width = $thumb_width;
               $img_height = $thumb_width / $ratio_source;
               $margin_top = $thumb_height / 2 - $img_height / 2;
           }
           elseif($ratio_x < $ratio_y){
               $img_height = $thumb_height;
               $img_width = $thumb_height * $ratio_source;
               $margin_left = $thumb_width / 2 - $img_width / 2;
           }
           else{
               $img_width = $thumb_width;
               $img_height = $thumb_height;
           }
 
           $thumb = $this->create_image($img_width,$img_height);
           imagecopyresized($thumb, $this->_source['img'], 0, 0, 0, 0, $img_width, $img_height, $this->_source['sizes'][0], $this->_source['sizes'][1]);
           imagecopymerge($this->_current_thumb['img'], $thumb, $margin_left, $margin_top, 0, 0, $img_width, $img_height, 100);
 
           return !is_null($filename) ? $this->save($filename) : true;
       }
 
       public function resize_crop($thumb_width, $thumb_height, $filename = null){
           $this->clear_current_thumb();
 
           $this->_current_thumb['img'] = $this->create_image($thumb_width, $thumb_height);
 
           $this->_current_thumb['sizes'][0] = $thumb_width;
           $this->_current_thumb['sizes'][1] = $thumb_height;
 
           $ratio_x = $this->_source['sizes'][0] / $thumb_width;
           $ratio_y = $this->_source['sizes'][1] / $thumb_height;
 
           $mid_height = $thumb_height / 2;
           $mid_width = $thumb_width / 2;
 
           if($ratio_x > $ratio_y){
               $final_width = $this->_source['sizes'][0] / $ratio_y;
               $int_width = ($final_width / 2) - $mid_width;
               imagecopyresampled($this->_current_thumb['img'],$this->_source['img'],-$int_width,0,0,0,$final_width,$thumb_height,$this->_source['sizes'][0],$this->_source['sizes'][1]);
           }
           elseif($ratio_x < $ratio_y){
               $final_height = $this->_source['sizes'][1] / $ratio_x;
               $int_height = ($final_height / 2) - $mid_height;
               imagecopyresampled($this->_current_thumb['img'],$this->_source['img'],0,-$int_height,0,0,$thumb_width,$final_height,$this->_source['sizes'][0],$this->_source['sizes'][1]);
           }
           else{
               imagecopyresampled($this->_current_thumb['img'],$this->_source['img'],0,0,0,0,$thumb_width,$thumb_height,$this->_source['sizes'][0],$this->_source['sizes'][1]);
           }
 
           return !is_null($filename) ? $this->save($filename) : true;
       }
 
       public function resize_width($thumb_width, $filename = null){
           $this->clear_current_thumb();           
           return $this->resize_side($thumb_width, 0, $filename);
       }
 
       public function resize_height($thumb_height, $filename = null){
           $this->clear_current_thumb();           
           return $this->resize_side($thumb_height, 1, $filename);           
       }
 
       private function resize_side($size, $side = 0, $filename = null){
              $this->clear_current_thumb();              
 
           $other_side = $side == 0 ? 1 : 0;
           $ratio = $this->_source['sizes'][$side] / $size;         
              $other_size = $this->_source['sizes'][$other_side] / $ratio;
 
              $width = $side == 0 ? $size : $other_size;                                   
           $height = $side == 1 ? $size : $other_size;
 
           $this->_current_thumb['img'] = $this->create_image($width, $height);                   
           $this->_current_thumb['sizes'] = array(0 => $width, 1 => $height);
 
           imagecopyresampled($this->_current_thumb['img'],
                   $this->_source['img'],
                0,0,0,0,
                $width,
                $height,
                $this->_source['sizes'][0],
                $this->_source['sizes'][1]
            );           
 
           return !is_null($filename) ? $this->save($filename) : true;    
       }
 
       function save($filename){
           $this->put_icon_if_needed();
           $this->put_text_if_needed();
 
           return $this->save_thumb_image($this->_current_thumb['img'], 
                   $this->_save_directory.$filename, 
                $this->_thumbs_quality
           );
       }
 
       public function clean(){           
           $this->destroy_image($this->_source['img']);
           $this->destroy_image($this->_current_thumb['img']);
           $this->destroy_image($this->_icon['img']);
           $this->destroy_image($this->_text['img']);    
       }
 
    // -----------------
    // PRIVATE FUNCTIONS
    // -----------------
 
        private function create_image($width, $height){
            $img = imagecreatetruecolor($width, $height);
           $this->manage_transparency($img);
           return $img;     
        }
 
       private function destroy_image($img){
           if(!is_null($img)){
               @imagedestroy($img);
               unset($img);                
           }
       }    
 
       private function clear_current_thumb(){
           $this->destroy_image($this->_current_thumb);
       }
 
       private function manage_transparency(&$toimage){    
              $type = $this->_source['sizes'][2];            
              if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_PNG) {
                $index = imagecolortransparent($this->_source['img']);     
               if ($index >= 0) {     
                   $color = imagecolorsforindex($fromimage, $index);     
                   $index = imagecolorallocate($toimage, $color['red'], $color['green'], $color['blue']);     
                   imagefill($toimage, 0, 0, $index);     
                   imagecolortransparent($toimage, $index);
               } 
               elseif($type == IMAGETYPE_PNG) {     
                   $this->transparent_background($toimage);
               }
           }
       }
 
       private function transparent_background(&$img){           
           imagealphablending($img, false);
           $black = imagecolorallocate($img, 0, 0, 0);
           imagefill($img, 0, 0, $black);
           imagecolortransparent($img, $black);
       }
 
       private function build_image_from_path($path, $type){
          switch($type){
              case IMAGETYPE_GIF:
                   return imagecreatefromgif($path); 
              break;
              case IMAGETYPE_PNG:
                   return imagecreatefrompng($path);
              break;
              case IMAGETYPE_JPEG:
              default :
                   return imagecreatefromjpeg($path); 
              break;
          }          
       }
 
       private function save_thumb_image($thumb, $path, $quality){
          switch(self::get_image_extension($path)){
              case 'gif':
                   imagegif($thumb, $path);
              break;
              case 'png':
                   imagepng($thumb, $path);
              break;
              case 'jpeg':
              case 'jpg':
              case 'jfif':
              case 'jpe':
              default :
                   imagejpeg($thumb, $path, $quality); 
              break;
          } 
       }        
 
       private function put_icon_if_needed(){
           if(!is_null($this->_icon)){
               $left = 0;
               $top = 0;
               $icon_width = $this->_icon['sizes'][0];
               $icon_height = $this->_icon['sizes'][1];
               $right = $this->_current_thumb['sizes'][0] - $icon_width;
               $bottom = $this->_current_thumb['sizes'][1] - $icon_height;
               $center_left = $right / 2;
               $center_top = $bottom / 2;
 
               if(is_int($this->_icon['position_left'])){
                    $this->_icon['margin_left'] = $this->_icon['position_left'];
               }else{
                   switch($this->_icon['position_left']){
                       case 'left' : $this->_icon['margin_left'] = $left; break;
                       case 'right' : $this->_icon['margin_left'] = $right; break;
                       case 'center' : $this->_icon['margin_left'] = $center_left; break;
                       default : $this->_icon['margin_left'] = 0; break;
                   }                
               }
 
               if(is_int($this->_icon['position_top'])){
                    $this->_icon['margin_top'] = $this->_icon['position_top'];
               }else{
                   switch($this->_icon['position_top']){
                       case 'top' : $this->_icon['margin_top'] = $top; break;
                       case 'bottom' : $this->_icon['margin_top'] = $bottom; break;
                       case 'center' : $this->_icon['margin_top'] = $center_top; break;
                       default : $this->_icon['margin_top'] = 0; break;
                   } 
               }
 
               if(!isset($this->_icon['is_built']) || !$this->_icon['is_built']){                   
                   $this->transparent_background($this->_icon['img']);
                   $this->_icon['is_built'] = true;
               }               
 
               imagecopymerge($this->_current_thumb['img'], $this->_icon['img'], $this->_icon['margin_left'], $this->_icon['margin_top'], 0, 0, $icon_width, $icon_height, $this->_icon['alpha']);
           }
       }
 
       private function put_text_if_needed(){
           if(!is_null($this->_text)){
                if(!isset($this->_text['color']) || $this->_text['color'] == null)
                    $this->_text['color'] = Array(255,255,0);     
 
                $left = 0;
                $top = 0;
                $right = $this->_current_thumb['sizes'][0] - $this->_text['sizes'][0];
                $bottom = $this->_current_thumb['sizes'][1] - $this->_text['sizes'][1];
                $center_left = $right / 2;
                $center_top = $bottom / 2;
 
                if(is_int($this->_text['position_left'])){
                    $this->_text['margin_left'] = $this->_text['position_left'];
                }else{
                    switch($this->_text['position_left']){
                        case 'left' : $this->_text['margin_left'] = $left; break;
                        case 'right' : $this->_text['margin_left'] = $right; break;
                        case 'center' : $this->_text['margin_left'] = $center_left; break;
                        default : $this->_text['margin_left'] = 0; break;
                    }
                }
 
                if(is_int($this->_text['position_top'])){
                    $this->_text['margin_top'] = $this->_text['position_top'];
                }else{
                    switch($this->_text['position_top']){
                        case 'top' : $this->_text['margin_top'] = $top; break;
                        case 'bottom' : $this->_text['margin_top'] = $bottom; break;
                        case 'center' : $this->_text['margin_top'] = $center_top; break;
                        default : $this->_text['margin_top'] = 0; break;
                    }     
                }  
 
                $color = imagecolorallocate($this->_current_thumb['img'], $this->_text['color'][0], $this->_text['color'][1], $this->_text['color'][2]);        
                $shadow_grey = imagecolorallocate($this->_current_thumb['img'], 128, 128, 128);
 
                if(is_int(intval($this->_text['font']))){
                    if(isset($this->_text['shadow']) && $this->_text['shadow'] == true)
                        imagestring($this->_current_thumb['img'], $this->_text['font'], $this->_text['margin_left'] + 1, $this->_text['margin_top'] + 1, $this->_text['text'], $shadow_grey);       
                    imagestring($this->_current_thumb['img'], $this->_text['font'], $this->_text['margin_left'], $this->_text['margin_top'], $this->_text['text'], $color);
                }
                else{
                    if(isset($this->_text['shadow']) && $this->_text['shadow'] == true)
                        imagettftext($this->_current_thumb['img'], $this->_text['size'], 0, $this->_text['margin_left'] + 1, $this->_text['margin_top'] + 1, $shadow_grey, $font, $this->_text['text']);        
                    imagettftext($this->_current_thumb['img'], $this->_text['size'], 0, $this->_text['margin_left'], $this->_text['margin_top'], $color, $this->_text['font'], $this->_text['text']);           
                }            
           }           
       }
 
       private function reload_text_sizes(){
           $this->_text['sizes'][0] = imagefontwidth($this->_text['size']) * strlen($this->_text['text']);
           $this->_text['sizes'][1] = imagefontheight($this->_text['size']) * 1;    
       }
 
}
 
?>
Voici comment utiliser la classe à travers divers exemples :

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<html>
  <head>
    <style type="text/css">
        body {width:800px;margin:auto;}
        div {background:#eee;margin:0 10px 10px 0;float:left;}
    </style>
  </head>
  <body>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
        <input type="file" name="source"/>
        <input type="submit" name="valid" value="Valid"/>
    </form>
 
    <?php
    require_once 'thumbsbuilder.class.php'; 
    if(isset($_FILES['source']['name'])){
        $source_image_extension = thumbs_builder::get_image_extension($_FILES['source']['name']);
        $source_image_path = 'images/background.'.$source_image_extension;
 
        if(move_uploaded_file($_FILES['source']['tmp_name'], $source_image_path)){
            $thumbs_saving_path = 'images/';
            $thumbs_image_quality = 95;
 
            $tb = new thumbs_builder($source_image_path, $thumbs_saving_path, $thumbs_image_quality);
 
            echo '<h1>Source image path : '.$tb->get_source_path().'</h1>';
            /* EXAMPLE 1 1 */
            $tb->resize_crop(70,70,'1.jpeg');
            echo '<div>RESIZE CROP <br/><img src="images/1.jpeg"/></div>';
 
            /* EXAMPLE 2 */
            // $tb->set_icon('imageS/icon.png','top','left');
            $tb->resize_width(100,'2.jpeg');
            echo '<div>RESIZE ON WIDTH <br/><img src="images/2.jpeg"/></div>';
 
            /* EXAMPLE 3 */
            $tb->resize_height(250,'3.jpeg');
            echo '<div>RESIZE ON HEIGHT <br/><img src="images/3.jpeg"/></div>';
 
            /* EXAMPLE 4 */
            $tb->resize(200,50,"FFCC33",'4.jpeg');
            echo '<div>RESIZE NOCROP 1 <br/><img src="images/4.jpeg"/></div>';
 
            /* EXAMPLE 5 */
            $tb->resize(300,300,"a12");
            // $tb->remove_icon();
            // $tb->remove_text();
            $tb->save('5.jpeg');
            echo '<div>RESIZE NOCROP 2 <br/><img src="images/5.jpeg"/></div>';
 
            $tb->clean(); // clean memory usage     
        }
    } 
    ?>
  </body>
</html>
Elle n'est pas optimale je pense, il y a toujours des améliorations à faire évidemment, mais c'est toujours pratique de l'avoir sous la main
__________________
Développeur Web, accessoirement geek (ou l'inverse)
http://thomasrambaud.com
ThomasR est déconnecté   Envoyer un message privé Réponse avec citation 10
Vieux 14/08/2009, 14h40   #83
Modérateur
 
Avatar de ThomasR
 
Homme Thomas Rambaud
Développeur Web
Inscription : décembre 2007
Messages : 2 140
Détails du profil
Informations personnelles :
Nom : Homme Thomas Rambaud
Âge : 25
Localisation : France

Informations professionnelles :
Activité : Développeur Web
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : décembre 2007
Messages : 2 140
Points : 2 885
Points : 2 885
Bonjour,

Je vous fait juste profiter d'un minuscule code qui permet de sécuriser les données envoyées par méthode GET / POST lorsqu'elle sont destinées à être utilisées dans une requête SQL.

La fonction nécessite d'être préalablement connecté à mysql :

Code :
1
2
3
4
5
 
function secureDatas(){
    $_POST = array_map('mysql_real_escape_string', $_POST);
    $_GET = array_map('mysql_real_escape_string', $_GET);
}
__________________
Développeur Web, accessoirement geek (ou l'inverse)
http://thomasrambaud.com
ThomasR est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 27/11/2009, 06h55   #84
Invité régulier
 
Inscription : janvier 2009
Messages : 23
Détails du profil
Informations forums :
Inscription : janvier 2009
Messages : 23
Points : 7
Points : 7
Bonjour,
Je vais bientôt vous proposer ma classe de gestion de formulaires, le temps que j'écrive la doc.
En attendant, voici un petit code (que j'utilise pour rédiger ma doc ) qui m'est très utile, et qui sert à colorer grâce à highlight_string les codes contenus dans les balises <code></code>.
Ça ne marche malheureusement que pour le code PHP.
Code :
1
2
3
4
 
<?php
/* A mettre en fin de page. Pensez à mettre un ob_start() en début de script */
echo preg_replace_callback('#<code>(.+)</code>#isU', create_function('$matches', 'return "<div class=\"code\">".highlight_string("<?php\n".$matches[1], true)."</div>";'), 									ob_get_clean());
Exemple simple d'utilisation :

Code :
1
2
3
<code>if($age < 18) {
    echo 'Bienvenue !';
}</code>
christophetd est déconnecté   Envoyer un message privé Réponse avec citation 01
Vieux 04/01/2010, 02h38   #85
Membre chevronné
 
Avatar de hornetbzz
 
Homme
Directeur commercial
Inscription : octobre 2009
Messages : 475
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 44
Localisation : France

Informations professionnelles :
Activité : Directeur commercial

Informations forums :
Inscription : octobre 2009
Messages : 475
Points : 680
Points : 680
Envoyer un message via Skype™ à hornetbzz
Par défaut Bargraph en dégradé rvb et texte dans la barre

Petite fonction pour générer des barres graphiques avec un dégradé de couleur (rvb) et un texte dans la barre. Pratique pour afficher les résultats de sondage par exemple.

NOTA: Nécessite la librairie GD, images au format png

Exemple d'appel de la fonction depuis votre source php:
Code :
1
2
3
4
5
6
7
8
9
10
11
12
$percent=60;
$text="salut";
$file_img='ben_ta_directory_img/ton_filename.png';
$img = CreateImageFade($base_x=550, $ratio_x=$percent, $base_y=25, $ratio_y=100, 
// color 1 for fading source
$red1=230, $green1=230, $blue1=255, 
// color 2 for fading target
$red2=0, $green2=0, $blue2=255,
// fade_direction=1 <=> horizontal fade, 2<=>vertical fade, 3<=>diag fade
$fade_direction=3,
$text, $offset_x= 40, $offset_y=20, $text_size=2, $file_img, $debug=false);
echo '<br/><img src="'. $img . '"/></br>';
Le code: rien de transcendant en soi mais c'est pratique et paramétrable
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function CreateImageFade(
$base_x=550, $ratio_x=100, $base_y=25, $ratio_y=100, 	// bar length and height for 100% with a reduction ratio (for example, $percent result of the poll)
$red1, $green1, $blue1,									// color 1 for fading source
$red2, $green2, $blue2,									// color 2 for fading target
$fade_direction,										// 1 for horizontal fade (direction x), 1 for vertical fade (direction y), 1 for diagonal fade (direction xy)
$text, $text_offset_x, $text_offset_y, $text_size=2,	// text content and size/position parameters
$path_to_root_file_img, $debug=false) {					// image file (format png) to be saved as result
// -----------------------------------------------
	// File.extension
	$file_img_bar	= $path_to_root_file_img ;
 
	// Init: vérif des min/max des couleurs rvb et ratio
	$red1	= (($red1 <= 255) && ($red1 >= 0))?		$red1	: 255 ;
	$green1	= (($green1 <= 255) && ($green1 >= 0))?	$green1	: 255 ;
	$blue1	= (($blue1 <= 255) && ($blue1 >= 0))?	$blue1	: 255 ;
 
	$red2	= (($red2 <= 255) && ($red2 >= 0))?		$red2	: 23 ;
	$green2	= (($green2 <= 255) && ($green2 >= 0))?	$green2	: 23 ;
	$blue2	= (($blue2 <= 255) && ($blue2 >= 0))?	$blue2	: 230 ;
 
	$ratio_x = (($ratio_x > 0) && ($ratio_x <= 100))? $ratio_x : 5 ;
	$ratio_y = (($ratio_y > 0) && ($ratio_y <= 100))? $ratio_y : 5 ;
 
 
	$c1		= array('r' => $red1, 'v' => $green1, 'b' => $blue1);
	$c2		= array('r' => $red2, 'v' => $green2, 'b' => $blue2);
 
	$bar_x	= $ratio_x * $base_x / 100 ;
	$bar_y	= $ratio_y * $base_y / 100 ;
 
	 switch ($fade_direction)  {
		 case 1 : $t = $bar_x; 			break;
		 case 2 : $t = $bar_y;			break;
		 case 3 : $t = $bar_x + $bar_y; break;
		 default: $t = $bar_x; 			break;
	 }
 
	 // DEBUG
	 if ($debug) {
		echo "<br/>DEBUG: long_x = $bar_x, long_y = $bar_y";
	 }
 
	// Création de l'image
	$img	= imagecreatetruecolor($bar_x, $bar_y);
	$white	= imagecolorallocate($img, 255, 255, 255);		// couleur du fond
 
	// Dégradé : on dessine une ligne verticale, horizontale ou diagonale pour chaque pixel entre 0 et $t
	for ($i=0; $i < $t ; $i++)  {
 
		$r = $c1['r'] + $i * ($c2['r'] - $c1['r']) / $t;
		$v = $c1['v'] + $i * ($c2['v'] - $c1['v']) / $t;
		$b = $c1['b'] + $i * ($c2['b'] - $c1['b']) / $t;
 
		$c = imagecolorallocate($img, $r, $v, $b);
 
		switch ($fade_direction) {
			case 1 : imageline($img, $i, 0, $i, $bar_y, $c); break;
			case 2 : imageline($img, 0, $i, $bar_x, $i, $c); break;
			case 3 : imageline($img, max(0,($i-$bar_y)), min($i,$bar_y), min($i,$bar_x), max(0,($i-$bar_x)), $c); break;
		}
	}
 
	// Ajout du texte
	$white	= imagecolorallocate($img, 255, 255, 255);			// couleur du texte affiché sur l'image
	imagestring($img, $text_size,  $bar_x - $text_offset_x , $bar_y - $text_offset_y , $text , $white);
 
	 // Sauvegarde de l'image au format png
	 imagepng($img, $file_img_bar);
	 imagedestroy($img);
 
 return $file_img_bar;
 
} /* fin de CreateImageFade */
hornetbzz est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 16/03/2011, 16h12   #86
Invité régulier
 
Inscription : juillet 2010
Messages : 10
Détails du profil
Informations forums :
Inscription : juillet 2010
Messages : 10
Points : 6
Points : 6
Par défaut rechargement image après upload (soucis cache)

rafraichir l'image après upload, solution

Bonjour,
je découvre ce topic pour partager, c'est cool

j'ai été confronté pendant longtemps à ce problème de rechargement de l'image fraîchement envoyée au serveur... par exemple :

j'ai une galerie d'images qui ont un nom fixe(les images) genre image1.jpg, image2.jpg etc..
je remplace une image par une autre, mais le nom ne change pas
le navigateur affiche alors l'image en cache, on est obligé de cliquer sur F5 pour rafraîchir la page....

il y a quelques bidouillages sur la toile qui marchent assez bien mais dans mon cas, il y avait toujours un soucis !

au lieu de charger l'image avec la date ou un nombre aléatoire, la solution est de récupérer la poids de l'image (en bytes, assez précis) et de le placer juste après le nom du fichier :

Code :
1
2
3
$la_photo='image.jpg';
$poids_foto='?'.filesize($la_photo);
echo '<img src='.$la_photo.$poids_foto.'>';
de cette façon, le moindre changement du poids force le rechargement
mais uniquement sur le fichier concerné, à l'inverse de rnd(1,9999) qui force toujours le rechargement...

si vous trouvez mieux, je suis preneur bien que cette bidouille soit très facile à mettre en place et ne nécessite pas énormément de modifs dans son code original...


voilà, c'est pas grand chose, mais ça marche

a+
gandahar1983 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 19/03/2011, 09h32   #87
Expert Confirmé
 
Avatar de Maxoo
 
Maxime Pasquier
Expert PHP
Inscription : novembre 2004
Messages : 2 126
Détails du profil
Informations personnelles :
Nom : Maxime Pasquier
Âge : 28
Localisation : France, Loire Atlantique (Pays de la Loire)

Informations professionnelles :
Activité : Expert PHP
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : novembre 2004
Messages : 2 126
Points : 2 602
Points : 2 602
Citation:
Envoyé par gandahar1983 Voir le message
[B][SIZE="6"]si vous trouvez mieux, je suis preneur bien que cette bidouille soit très facile à mettre en place et ne nécessite pas énormément de modifs dans son code original...
Envoyer des expires corrects, voir : http://julien-pauli.developpez.com/t...p/?page=page_8
__________________
Pour une bien meilleur lisibilité, utilisez la balise [code], c'est le [#] dans votre éditeur.
Mon espace Développez : mes Créations.


Rencontre & Carte des Membres de Developpez.com, version 3.0
Maxoo est déconnecté   Envoyer un message privé Réponse avec citation 10
Vieux 21/03/2011, 13h16   #88
Invité régulier
 
Inscription : juillet 2010
Messages : 10
Détails du profil
Informations forums :
Inscription : juillet 2010
Messages : 10
Points : 6
Points : 6
Citation:
Envoyé par Maxoo Voir le message
Envoyer des expires corrects, voir : http://julien-pauli.developpez.com/t...p/?page=page_8
Merci pour l'info, ça complète bien le sujet.
Maintenant, en sachant que les standards du web ne sont pas toujours respectés (Ex. ie) il faudrait procéder à de nombreux tests pour savoir si ça fonctionne sur tous les browsers..
gandahar1983 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/08/2011, 16h48   #89
Membre habitué
 
Homme Lucas GAUTHERON
Lycéen
Inscription : décembre 2008
Messages : 106
Détails du profil
Informations personnelles :
Nom : Homme Lucas GAUTHERON

Informations professionnelles :
Activité : Lycéen

Informations forums :
Inscription : décembre 2008
Messages : 106
Points : 145
Points : 145
Citation:
Envoyé par Passarinho44 Voir le message
Voici une petite fonction permettant de changer la valeur d'un attribut dans la barre d'adresse

Un code qui peut être pratique pour faire de la pagination ou des tris plus efficacement sans avoir à modifier le lien dès qu'on rajoute un attribut de tri.

Bien sur ce code peut surement être optimisé, n'hésitez pas à me le dire si vous trouvez des erreurs.
Effectivement
http://php.net/manual/fr/function.parse-url.php

Citation:
Envoyé par ThomasR Voir le message
Bonjour,

Je vous fait juste profiter d'un minuscule code qui permet de sécuriser les données envoyées par méthode GET / POST lorsqu'elle sont destinées à être utilisées dans une requête SQL.

La fonction nécessite d'être préalablement connecté à mysql :

Code :
1
2
3
4
5
 
function secureDatas(){
    $_POST = array_map('mysql_real_escape_string', $_POST);
    $_GET = array_map('mysql_real_escape_string', $_GET);
}
c'est grosso modo comme magic quotes (gpc)... obsolète et dont l'utilisation est déconseillée sur le site de PHP..
C'est comme désactiver register_globals et faire extract($_POST);
lucas74 est déconnecté   Envoyer un message privé Réponse avec citation 01
Vieux 10/08/2011, 11h12   #90
Membre habitué
 
Homme Lucas GAUTHERON
Lycéen
Inscription : décembre 2008
Messages : 106
Détails du profil
Informations personnelles :
Nom : Homme Lucas GAUTHERON

Informations professionnelles :
Activité : Lycéen

Informations forums :
Inscription : décembre 2008
Messages : 106
Points : 145
Points : 145
Une petite fonction pour définir plusieurs constantes d'un coup :
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
function enum()
{
    for($i = 0; $i < func_num_args(); $i++) define(func_get_arg($i), $i);
}
 
// exemple :
enum('ITEM_ARTICLE', 'ITEM_TAG', 'ITEM_CATEGORY', 'ITEM_AUTHOR');
 
// ITEM_ARTICLE = 0, ITEM_TAG = 1, ITEM_CATEGORY = 2, ITEM_AUTHOR = 3
 
// pareil avec puissances de 2
function enum2()
{
    for($i = 0; $i < func_num_args() && $i <= 32; $i++) define(func_get_arg($i), 1<<$i);
}
 
enum2('ITEM_ARTICLE', 'ITEM_TAG', 'ITEM_CATEGORY', 'ITEM_AUTHOR');
// ITEM_ARTICLE = 1, ITEM_TAG = 2, ITEM_CATEGORY = 4, ITEM_AUTHOR = 8
lucas74 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 11/08/2011, 15h46   #91
Rédacteur/Modérateur
 
Avatar de Thes32
 
Homme
Développeur Web
Inscription : décembre 2006
Messages : 2 335
Détails du profil
Informations personnelles :
Sexe : Homme

Informations professionnelles :
Activité : Développeur Web

Informations forums :
Inscription : décembre 2006
Messages : 2 335
Points : 3 774
Points : 3 774
Citation:
Envoyé par lucas74 Voir le message
Effectivement
c'est grosso modo comme magic quotes (gpc)... obsolète et dont l'utilisation est déconseillée sur le site de PHP..
C'est comme désactiver register_globals et faire extract($_POST);
Bah non, l'idée du script est de faire comprendre que dans certain cas, on peut sécuriser toutes les entrées utilisateurs. Et en plus, contrairement à magic quotes le contrôle se trouve dans l'espace utilisateur.
__________________
Développeur | Zend Certified Engineer

Étapes Pour mieux se servir du forum:
1. Commencez par lire les cours et tutoriels ;
2. Faites une recherche;
3. Faites un post si rien trouvé dans les deux étapes précédentes en respectant les règles;

Nix>_Rien n'est plus pratique que la théorie
Thes32 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 13/08/2011, 18h00   #92
Membre habitué
 
Homme Lucas GAUTHERON
Lycéen
Inscription : décembre 2008
Messages : 106
Détails du profil
Informations personnelles :
Nom : Homme Lucas GAUTHERON

Informations professionnelles :
Activité : Lycéen

Informations forums :
Inscription : décembre 2008
Messages : 106
Points : 145
Points : 145
Sauf qu'il vaut mieux laisser le soin de protéger les valeurs à la couche qui gère les accès à la base de données, ce qui est plus sur et moins contraignant pour le reste de l'application qui a besoin des valeurs d'entrée brutes.
lucas74 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 16/08/2011, 14h01   #93
Rédacteur/Modérateur
 
Avatar de Thes32
 
Homme
Développeur Web
Inscription : décembre 2006
Messages : 2 335
Détails du profil
Informations personnelles :
Sexe : Homme

Informations professionnelles :
Activité : Développeur Web

Informations forums :
Inscription : décembre 2006
Messages : 2 335
Points : 3 774
Points : 3 774
Citation:
Envoyé par lucas74 Voir le message
Sauf qu'il vaut mieux laisser le soin de protéger les valeurs à la couche qui gère les accès à la base de données,...
Qui te dit qu'on a toujours affaire à une base des données ?
__________________
Développeur | Zend Certified Engineer

Étapes Pour mieux se servir du forum:
1. Commencez par lire les cours et tutoriels ;
2. Faites une recherche;
3. Faites un post si rien trouvé dans les deux étapes précédentes en respectant les règles;

Nix>_Rien n'est plus pratique que la théorie
Thes32 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 16/08/2011, 14h09   #94
Membre Expert
 
Avatar de gene69
 
Inscription : janvier 2006
Messages : 951
Détails du profil
Informations personnelles :
Localisation : France

Informations professionnelles :
Secteur : High Tech - Produits et services télécom et Internet

Informations forums :
Inscription : janvier 2006
Messages : 951
Points : 1 063
Points : 1 063
permettre l'affichage du code qui s'execute sur le serveur. inutile sauf quand on ne se souvient plus comment on a implementé tel ou tel fonction.
Code php :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
<?php
/**
 * @package framework
 *
 * @author Pierre-Emmanuel Périllon
 * @license GPL2
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 **/
/**
 * @see __autoload()
 * */
require_once 'autoload.inc.php';
 
 
/**
 * @package framework
 * */
class SourceCode
{
    const patternRequireAndInclude = '#(?:include|require)(?>_once)?\s*\(?[ \t\n]*\'(.*)\'[ \t\n]*\)?#';
/*    const patternInclude = '#include(?>_once)?\s*\(?[ \t\n]*\'(.*)\'[ \t\n]*\)?#';
*/    const patternClass = '#(?>new\s+([A-Za-z0-9_]+)\s*\()|(?>([A-Za-z0-9_]+)::)|(?>extends\s+([A-Za-z0-9_]+)\s*)|(?>implements\s+([A-Za-z0-9_]+))|(?>catch\s*\(\s*([A-Za-z0-9_]+))#';
//    const patternFunction ='#(abstract|final|static|protected|public|private|)[ \t]*(abstract|final|static|protected|public|private|)[ \t]*(abstract|final|static|protected|public|private|)[ \t]*(abstract|final|static|protected|public|private|)[ \t]*function[ \t\n]+(&?[a-z0-9_]+)#i';
    const patternFunction ='#(?:(?>(static)|(protected)|(private)|(public)|(abstract)|(final))\s+){0,5}function\s+(&?\w+)\s*\(#i';
    const patternException = '#([A-Za-z0-9_]+)exception#i';
    static $ignore = array('self', 'parent', 'static');
 
    static $param = 'getSourceCode';
    static $dir = array('' => '', 'class' => 'include/','interface' => '.int.php' );
    static $ext = array('' => '', 'class' => '.class.php', 'interface' => '.int.php' ) ;
    static $docUrl = 'http://php.net/manual-lookup.php?pattern=';
    static $charset = 'UTF-8';
 
    /**
     * merci à Brice qui m'a aidé à écrire la premiere version de cette
     * fonction
     * @param sourceFileName c'est le nom du fichier
     * @uses SourceCode::convertirListeSymboleVersLien()
     * @uses SourceCode::patternRequireAndInclude
     * @uses SourceCode::patternClass
     * @static
     **/
    static protected function BriceA($source)
    {
        //detection des requires
        preg_match_all (self::patternRequireAndInclude, $source, $matches);
        $liste =self::convertirListeSymboleVersLien( $matches[1], '' );
 
        //detection des includes
//        preg_match_all (self::patternInclude, $source, $matches);
//        Debug::var_dump($matches);
//        $liste = array_merge( $liste , self::convertirListeSymboleVersLien($matches[1],'' ) ) ;
 
        //detection des classes
        preg_match_all (self::patternClass,$source,$matches);
        //new
        $liste = array_merge( $liste , self::convertirListeSymboleVersLien($matches[1], 'class') );
        //static
        $liste = array_merge( $liste , self::convertirListeSymboleVersLien($matches[2], 'class') );
        //extends
        $liste = array_merge( $liste , self::convertirListeSymboleVersLien($matches[3], 'class') );
        //interface
        $interface = array();
        foreach( $matches[4] as $int )
        {
            $tmp = explode(',',str_replace( array("\n\t\0 "), '', trim($int)));
            $interface = array_merge($interface, $tmp  );
        }
        $liste = array_merge( $liste , self::convertirListeSymboleVersLien( $interface, 'interface' ) );
        //catch
        $liste = array_merge( $liste , self::convertirListeSymboleVersLien($matches[5], 'class') );
//        print_r($matches);
 
        $liste = array_unique($liste );
 
        $suite = NULL;
 
        echo '
            <ul style="text-align:left;float:left">';
        foreach( $liste as $symbole => $filename)
        {
            if ($filename === null )
            {
                echo "\n",'<li>Citation: ', $symbole, '</li>';
            }
            else if ( strpos($filename,'http://') === 0 )
            {
                $suite[$symbole] = $filename;
            }
            else
            {
                echo "\n",'<li><a href="', self::uri2url($filename),'">', $symbole, '</a></li>';
            }
        }
        echo '</ul>';
        if ( $suite !== null )
        {
 
            echo '
                <ul style="text-align:left;float:left">';
            foreach( $suite as $symbole => $filename)
            {
                echo "\n",'<li><a href="', self::uri2url($filename),'">', $symbole, '</a></li>';
            }
            echo '</ul>';
        }
    }
 
 
 
        /***
     * replace un nom de fichier local en ce qu'il devrait être sur le web
     * pet'te que ça marche pas.
     * @param filename $file
     * @return string
     * */
    static protected function uri2url( $file )
    {
        $hide[] = $_SERVER['DOCUMENT_ROOT'];
        return str_replace($hide,'http://'.$_SERVER['SERVER_NAME'], $file);
    }
 
 
 
    /**
     * affiche le code source.
     * utilise un tableau pour sparer le code et les numros: plus simple.
     * on ne peut par couper la chaine obtenue par ligne avec par exemple un explode('<br />',$str)
     * parce que sinon on nique la coloration et avec la non fermeture des spans.
     * @param string $filename le nom du fichier (pathname  afficher)
     * @return void affiche a tous les coups et continue
     * @uses SourceCode::afficherNavigation()
     * @uses SourceCode::BriceA
     * @uses SourceCode::afficherCss()
     * @uses SourceCode::afficherCode()
     * @uses SourceCode::afficherListeFonction()
     * @uses SourceCode::$charset
     * @static
     */
    static protected function afficher($filename)
    {
        $file = basename($filename);
        $dir = dirname( $filename);
        $fileContent= file_get_contents($file);
 
        header('Content-type: text/html ; charset='.self::$charset.';');
 
        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="content-type" content=" content=; charset=',self::$charset,'" />
        <title>Code du script / serveur = ',$_SERVER['SERVER_NAME'],$dir,'/',$file,'</title>
        <style type="text/css">';
        self::afficherCss();
        echo '
        </style>
    </head>
    <body id="top">
        <div class="boite">
            <h1>',$filename,'</h1>
            <p>derniere modification: <span id="lastModified">',date('r',filemtime($file)),'</span>.</p>';
        self::afficherNavigation($filename);
        self::BriceA($fileContent);
        echo '
            <div style="clear:both"></div>
        </div>';
            /* on prépare le code. */
        self::afficherCode($file);
        echo '
            <hr />
            <div >licence: GPL 2+, author: Pierre-Emmanuel Périllon.</div>';
        self::afficherListeFonction($file);
 
        include 'traceursJavascript.inc.php' ;
 
        echo '
    </body>
</html>';
    }
 
    /**
     * @param filename $file
     * @static
     * */
    static protected function afficherCode($file)
    {
        $fileContent= file_get_contents($file);
        $max = substr_count ($fileContent,"\n")+1;
        $recherche =    array('<br />'/*,    '</font>',    '</span>'*/);
        $remplace =    array("<br />\n"/*,    "</font>\n",    "</span>\n"*/);
        $str = highlight_string($fileContent,true);
        $html= str_replace($recherche, $remplace, $str);
        echo '
        <table>
            <tr>
                <th> ? </th>
                <th> Code </th>
            </tr>
            <tr>
                <td title="Numéro de ligne" ><code>';
        /* afficher les numeros dans une cellule*/
        for ( $i=1; $i <= $max ; $i++)
        {
            echo '
    <a id="line',$i,'" href="#line',$i,'">',$i,'</a><br/>';
        }
        echo '
                    </code></td>
                    <td title="le code php" >',
            /* le reste dans une autre cellule */
            $html,'
                    </td>
                </tr>
            </table>';
    }
 
    /**
     * @static
     * */
    static protected function afficherCss()
    {
        echo '
/*<![CDATA[*/
body{font-size:10pt}
a{text-decoration:none}
a:hover{font-weight:bolder}
.boite{border:black 2px solid;text-align: center}
.boite a{text-decoration:underline}
code{font-size:10pt}
code a{color:gray;text-decoration:none}
code a:hover{text-decoration:underline}
h1{font-family:monospace}
.toolbox{position:fixed;bottom:0;right:0;width:30ex}
.toolbox>.resume{text-align:center;border:1px black solid;background:whitesmoke;margin:0;padding:2pt}
.liste{margin:0;padding:0;}
.liste>li{margin:0;padding:1px;}
.toolbox>.liste{list-style-type:none;height:300px;overflow:scroll;background-color:rgba(245,255,250,0.9);display:none;font-size:smaller;border-style:none;}
.toolbox:hover>.liste{display:block}
.abstract{text-decoration:line-through}
.private{color:red}
.protected{color:blue}
.public{color:green}
.final{background-color:yellow}
/*]]>*/
';
    }
 
    /**
     * @param filename $file
     * @static
     * @uses SourceCode::listerFonction()
     * @uses SourceCode::afficherPrototype()
     * */
    static protected function afficherListeFonction ($filename)
    {
        $t = self::listerFonction($filename);
        $c = count ($t);
            echo '
<div class="toolbox">';
        if ( $c > 0 )
        {
            echo '<ul class="liste" >';
            foreach( $t as $proto)
            {
                self::afficherPrototype($proto);
            }
            echo '</ul>';
        }
        echo '
        <div class="resume" ><a href="#top" title="top">',$c,' méthodes/fonctions</a></div>
</div>';
    }
 
    /**
     * @param filename $file
     * @static
     * @uses SourceCode::listerFichiers()
     * */
    static protected function afficherNavigation($filename)
    {
        $t = self::listerFichiers($filename);
        echo '<ul style="text-align:left;float:left;width:20em">
            <li><a href="',$t[0],'?',self::$param,'">fichier précédant</a></li>
            <li><a href="',$t[1],'?',self::$param,'">fichier suivant</a></li>';
        if ( file_exists('index.php') )
        {
            echo '<li><a href="?',self::$param,'">index</a>.</li>';
        }
        if ( file_exists('../index.php') )
        {
            echo '
            <li><a href="..?',self::$param,'">parent</a></li>';
        }
        if ( isset($_SERVER['HTTP_REFERER']) )
        {
            echo '
            <li><a href="',htmlspecialchars($_SERVER['HTTP_REFERER']),'" title="',htmlspecialchars($_SERVER['HTTP_REFERER']),'">referer</a></li>';
        }
        echo '
        </ul>';
    }
 
 
    /**
     * @static
     * @param array $p
     * */
    static protected function afficherPrototype($p)
    {
        echo  '<li>',(empty($p['static'])?'->':'::');
        echo '<a class="',$p['abstract'],' ',$p['visibility'],' ',$p['final'],
        '" href="#line',$p['line'],
        '" title="ligne ',
        $p['line'],': ',$p['abstract'],' ',$p['visibility'],'" >',$p['function'],'()</a></li>';
    }
 
    /**
     * liste les fichiers
     * @param filename $file
     * @static
     * @return array
     * */
    static function listerFichiers($filename)
    {
        $dir = dirname($filename);
        $ref = basename($filename);
 
        $tab = glob($_SERVER['DOCUMENT_ROOT'].$dir.'/*.php');
 
//        print_r($tab);
        $r[0] = $r[1] = $ref;
        foreach ( $tab as $file )
        {
            $script = basename($file);
            if ( $script ===  $ref)
            {
                $r[1] = basename( current ($tab) );
            }
            $r[0] = $script;
        }
        return $r;
    }
 
 
    /***
     * @param filename $filename
     * @static
     * @uses SourceCode::simplierPrototype()
     * @uses SourceCode::patternFunction
     * @return array
     * */
    static function listerFonction($filename)
    {
        $f = file ($filename);
        $r = array();
        foreach( $f as $n => $line )
        {
            if ( preg_match(self::patternFunction, $line, $matches ) )
            {
                $x =self::simplierPrototype($matches, $n+1);
                // on peut avoir deux fonctions du meme nom dans un meme fichier
                // mais tres difficilitement dans une meme ligne
                $r[$x['function'].'@'.$x['line']]=$x;
            }
        }
        ksort($r);
        return $r;
    }
 
 
    /**
     * afficher le code source d'une page au cas ou on en a besoin.
     * @return void affiche et termine ou ne fait rien
     * @uses SourceCode::afficher()
     * @static
     */
    static final function obtenir()
    {
        if( isset($_GET[self::$param]))
        {
            self::afficher($_SERVER['PHP_SELF']);
            exit;
        } // if( isset($_GET['getSourceCode']))
    }
 
    /**
     * @access private
     * @param array $m
     * @param integer $line
     * @return array
     * @static
     * */
    static private function simplierPrototype($m, $line)
    {
        $tmp= $m[2].$m[3].$m[4];
        if (empty($tmp))
        {
            $tmp = 'public';
        }
        $r['static'] = '';
        $r['abstract'] = '';
        $r['final'] = '';
        $key=array('static','abstract','final','function');
        unset($m[0]);
        unset($m[2]);
        unset($m[3]);
        unset($m[4]);
        $r=array_combine($key,$m);
        $r['visibility']=$tmp;
        $r['line'] = $line;
        return $r;
    }
 
    /**
     * @access protected
     * @static
     * @uses SourceCode::$dir
     * @uses SourceCode::$ext
     * @uses SourceCode::patternException
     * @uses SourceCode::$param
     * @uses SourceCode::chercherDocumentation()
     * */
    static protected function convertirSymboleVersLien($objet, $type)
    {
        if ( empty( $type ) and file_exists ($objet) )
        {
            return htmlspecialchars($objet).'?'.self::$param;
        }
        else if ( ($theFile = loadClassAndInterface($objet, false) ) !== False )
        {
            return htmlspecialchars($theFile).'?'.self::$param;
        }
        else
        {
            if ( preg_match(self::patternException,$objet,$matches) )
            {
                //si c'est une exception, on s'en contrefiche.
                return null;
            }
            else
            {
                return self::chercherDocumentation($objet);
            }
        }
    }
 
    /***
     * trouve l'url associée à une classe ou interface...
     * @access protected
     * @static
     * @param string $type
     * @param array $array
     * @return array
     * @uses SourceCode::convertirSymboleVersLien()
     * */
    static protected function convertirListeSymboleVersLien($array,$type)
    {
//        $array = array_unique($array);
        $l = array();
        foreach( $array as $objet )
        {
            $objet = trim($objet);
            if ( empty($objet) or in_array( $objet , self::$ignore ) )
            {
                continue;
            }
            $l[$type.' '.$objet]= self::convertirSymboleVersLien($objet, $type);
            //traiter les
        }
        return $l;
    }
 
    /***
     * @static
     * @uses SourceCode::$docUrl
     *
     * */
    static protected function chercherDocumentation($symbole)
    {
        return self::$docUrl.urlencode($symbole);
    }
 
 
}//class
__________________
PHP fait nativement la validation d'adresse électronique Vous êtes perdu en PHP? rassurez-vous ici (en)
Utilisez le bouton résolu!
gene69 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 16/08/2011, 14h22   #95
Rédacteur/Modérateur
 
Avatar de Thes32
 
Homme
Développeur Web
Inscription : décembre 2006
Messages : 2 335
Détails du profil
Informations personnelles :
Sexe : Homme

Informations professionnelles :
Activité : Développeur Web

Informations forums :
Inscription : décembre 2006
Messages : 2 335
Points : 3 774
Points : 3 774
salut,

peux tu le placez sur l'espace de téléchargements ?
__________________
Développeur | Zend Certified Engineer

Étapes Pour mieux se servir du forum:
1. Commencez par lire les cours et tutoriels ;
2. Faites une recherche;
3. Faites un post si rien trouvé dans les deux étapes précédentes en respectant les règles;

Nix>_Rien n'est plus pratique que la théorie
Thes32 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 16/08/2011, 20h39   #96
Membre habitué
 
Homme Lucas GAUTHERON
Lycéen
Inscription : décembre 2008
Messages : 106
Détails du profil
Informations personnelles :
Nom : Homme Lucas GAUTHERON

Informations professionnelles :
Activité : Lycéen

Informations forums :
Inscription : décembre 2008
Messages : 106
Points : 145
Points : 145
Citation:
Envoyé par Thes32 Voir le message
Qui te dit qu'on a toujours affaire à une base des données ?
pourquoi utiliser mysql_real_escape_string dans le cas contraire ?!
lucas74 est déconnecté   Envoyer un message privé Réponse avec citation 10
Vieux 19/08/2011, 09h48   #97
Rédacteur/Modérateur
 
Avatar de Thes32
 
Homme
Développeur Web
Inscription : décembre 2006
Messages : 2 335
Détails du profil
Informations personnelles :
Sexe : Homme

Informations professionnelles :
Activité : Développeur Web

Informations forums :
Inscription : décembre 2006
Messages : 2 335
Points : 3 774
Points : 3 774
Citation:
Envoyé par lucas74 Voir le message
pourquoi utiliser mysql_real_escape_string dans le cas contraire ?!
Euh oui, mais cette fonction pourrait bien faire partie de la couche métier...Bref l'idée du script est de faire comprendre qu'on nettoyer toutes les données des venant de l'exterieur en un seul coup (sans avoir magic quotes activer).
__________________
Développeur | Zend Certified Engineer

Étapes Pour mieux se servir du forum:
1. Commencez par lire les cours et tutoriels ;
2. Faites une recherche;
3. Faites un post si rien trouvé dans les deux étapes précédentes en respectant les règles;

Nix>_Rien n'est plus pratique que la théorie
Thes32 est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse Proposer ce sujet en actualité
Outils de la discussion



Fuseau horaire GMT +2. Il est actuellement 03h34.


 
 
 
 
Partenaires

Hébergement Web