4 / 4 / 2
Регистрация: 28.10.2010
Сообщений: 180
1

При авторизации пользователя, форма входа не меняется на личный кабинет

10.04.2014, 21:21. Показов 1736. Ответов 2
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Здравствуйте. Проблема заключается в следующем.

Пользователь заходит на сайт, и если куки отсутствуют(если он до этого авторизовывался), то подставляется форма входа, если же все же куки есть, то за место этой формы выходит div с описанием, например здравствуйте "пользователь".
Кликните здесь для просмотра всего текста
HTML5
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
<?PHP
require ('lib/connections/db.php');
include('lib/functions/functions.php');
 
$getuser = getUserRecords($_SESSION['user_id']);
?>
<!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" xml:lang="en-GB">
<head>
    <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <meta name="robots" content="index, follow" />
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />   
    <script type="text/javascript" src="js/jquery-1.6.2.js"></script>
    <script type="text/javascript" src="js/script.js"></script>
<!-- JavaScript -->
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
                    //Контейнер форм (включает все формы)
                var $form_wrapper   = $('#form_wrapper'),
                    //Текущая форма - имеет класс active
                    $currentForm    = $form_wrapper.children('form.active'),
                    //Ссылка на изменение формы
                    $linkform       = $form_wrapper.find('.linkform');
                        
                //Получаем высоту и ширину каждой формы и сохраняем их
                $form_wrapper.children('form').each(function(i){
                    var $theForm    = $(this);
                    //Решение проблемы с выводом при использовании fadeIn fadeOut
                    if(!$theForm.hasClass('active'))
                        $theForm.hide();
                    $theForm.data({
                        width   : $theForm.width(),
                        height  : $theForm.height()
                    });
                });
                
                //Устанавливаем высоту и ширину контейнера (такие же как и у текущей формы)
                setWrapperWidth();
                
                /*
                Нажатие на ссылке (событие смены форм) в форме приводит к скрытию текущей формы.
                Контейнер анимирует изменение ширины и высоты к новым значениям.
                После завершения анимации выводится новая форма
                */
                $linkform.bind('click',function(e){
                    var $link   = $(this);
                    var target  = $link.attr('rel');
                    $currentForm.fadeOut(400,function(){
                        //Удаляем класс active с текущей формы
                        $currentForm.removeClass('active');
                        //Новая текущая форма
                        $currentForm= $form_wrapper.children('form.'+target);
                        //Анимируем изменения контейнера
                        $form_wrapper.stop()
                                     .animate({
                                        width   : $currentForm.data('width') + 'px',
                                        height  : $currentForm.data('height') + 'px'
                                     },500,function(){
                                        //Новая форма получает класс active
                                        $currentForm.addClass('active');
                                        //Выводим новую форму
                                        $currentForm.fadeIn(400);
                                     });
                    });
                    e.preventDefault();
                });
                
                function setWrapperWidth(){
                    $form_wrapper.css({
                        width   : $currentForm.data('width') + 'px',
                        height  : $currentForm.data('height') + 'px'
                    });
                }
                
                /*
                Для демонстрации кнопки отключены.
                Если отправлять форму, нужно проверить, какая форма отправляется 
                и присвоить класс active той форме, которая будет выводиться после отправки.
                */
                /*$form_wrapper.find('input[type="submit"]')
                             .click(function(e){
                                e.preventDefault();
                             });*/
               $(document).ready(function(){
    
            $('#loginForm').submit(function(e) {
                login();
                e.preventDefault();
            }); 
        }); 
 
 
                $(document).ready(function(){
    
            $('#regForm').submit(function(e) {
                register();
                e.preventDefault();
            }); 
        });
        
     
                $(document).ready(function(){
    
            $('#passreset').submit(function(e) {
                passreset();
                e.preventDefault(); 
            }); 
        });
 
            
    });
</script>
    </head>
<body>
<? if(!empty($error)){echo "<div class='error'>".$error."</div>";}?>
<div id="sidebar">
 
    <div class="done"><p>Регистрация прошла успешно! На ваш e-mail было отправлено письмо с активацией вашей учетной записи.</p></div>
          <?php if (!isset($_SESSION['user_id']))
    {
    ?>
           <div id="form_wrapper" class="form_wrapper">
                    
                    <form id="regForm" class="register" action="reg_submit.php" method="post">
                    
                    <h3><center>Регистрация<center></h3>
 
                    <div class="column">
 
                    <div>
 
                                <label>Логин:</label>
                                
                                <input onclick="this.value='';" name="username" type="text" size="25" maxlength="14" value="<?php if(isset($_POST['username'])){echo $_POST['username'];}?>"/>
                                
                                <span class="error">Ошибка</span>
                            
                    </div>
                            <div>
                                <label>Пароль:</label>
                            
                                <input name="password" type="password" size="25" maxlength="15" />
 
                                <span class="error">Ошибка</span>
                            
                            </div>
                            
                            
                            <div>
                                <label>Email:</label>
                                <input onclick="this.value='';" name="email" type="text" size="25" maxlength="50" value="<?php if(isset($_POST['email'])){echo $_POST['email'];}?>"/>
                                <span class="error">Ошибка</span>
                            </div>
                            </div>
                          <div class="bottom">
                            <div class="remember">
                                <input type="checkbox" />
                                <span>Отправлять мне обновления</span>
                            </div>
                            <input type="submit" name="register" value="Зарегистрироваться" /><img id="loading" src="img/loading.gif" alt="working.." />
                            <a href="index.html" rel="login" class="linkform">Вы уже зарегистрировались? Войдите здесь</a>
                            <div id="error">&nbsp;</div>
                            <div class="clear"></div>
                        </div>
                    </form>
                    <form id="loginForm" class="login active"  action="login_submit.php" method="post">
                        <h3><center>Вход на сайт</center></h3>
                        <div>
                            <label>Имя пользователя:</label>
                            <input onclick="this.value='';" name="username" type="text" size="25" maxlength="14" value="<?php if(isset($_POST['username'])){echo $_POST['username'];}?>"/>
                            <span class="error">Ошибка</span>
                        </div>
                        <div>
                            <label>Пароль: <a href="forgot_password.html" rel="forgot_password" class="forgot linkform">Забыли пароль?</a></label>
                            <input name="password" type="password" size="25" maxlength="15" />
                            <span class="error">Ошибка</span>
                        </div>
                        <div class="bottom">
                            <div class="remember"><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" type="checkbox" /><span>Оставаться в системе</span></div>
                            <input type="submit" name="submit" value="Войти" />
                            <a href="register.html" rel="register" class="linkform">Вы еще не зарегистрировались? Присоединяйтесь</a>
                            <div class="clear"></div>
                        </div>
                    </form>
                    <form id="passreset" class="forgot_password" action="pass_reset_submit.php" method="post">
                        <h3><center>Восстановление пароля</center></h3>
                        <div>
                            <label>Введите Email:</label>
                            <input onclick="this.value='';" name="email" type="text" size="25" maxlength="30" value="<?php if(isset($_POST['email'])){echo $_POST['email'];}?>" />
                            <span class="error">Ошибка</span>
                        </div>
                        <div class="bottom">
                            <input type="submit"  name="submit" value="Отправить пароль"></input>
                            <a href="index.html" rel="login" class="linkform">Вдруг вспомнили пароль? Войдите здесь</a>
                            <a href="register.html" rel="register" class="linkform">Вы еще не зарегистрировались? Присоединяйтесь</a>
                            <div class="clear"></div>
                        </div>
                    </form>
                        </div>
                <div class="clear"></div>
            <?php 
            }
            else 
            {?>
            
    <p>Добро пожаловать <?php if(empty($getuser[0]['first_name']) || empty($getuser[0]['last_name'])){echo $getuser[0]['username'];} else {echo $getuser[0]['first_name']." ".$getuser[0]['last_name'];} }?></p>
            
 
        
<div class = "container" style = "">
         <ul class = "nice-menu">
           <li class = "orange"><a href = "">Главная</a></li>
           <li class = "red"><a href = "">О нас</a></li>
           <li class = "green"><a href = "">Контакты</a></li>
           <li class = "blue"><a href = "">Профиль</a></li>
           <li class = "bright"><a href = "">Портфолио</a></li>
           <li class = "red"><a href = "">Материалы</a></li>
         </ul>
       </div>
      </div>
      </body>
страница функции
HTML5
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
<?php
//----------Check if magic qoutes is on then stripslashes if needed----------
function secureInput($var)
{
    $output = '';
    if (is_array($var)){
        foreach($var as $key=>$val){
            $output[$key] = secureInput($val);
        }
    } else {
        $var = strip_tags(trim($var));
        if (function_exists("get_magic_quotes_gpc")) {
            $output = mysql_real_escape_string(get_magic_quotes_gpc() ? stripslashes($var) : $var);
        } else {
            $output = mysql_real_escape_string($var);
        }
    }
    if (!empty($output))
    return $output;
}
 
//----------Функция для входа пользователей----------
function login($user,$pass)
{
    $user = secureInput($user);
    $pass = secureInput($pass);
    
    $salt = 's+(_a*';
    $pass = md5($pass.$salt);
    $lastLogin = date("l, M j, Y, g:i a");
    
        //Прверяем имя и пароль пользователя
        $query = mysql_query('SELECT id, username, password, active, level_access FROM users WHERE username = "'.secureInput($user).'" AND password = "'.secureInput($pass).'" AND level_access != 9') or die (mysql_error());
        
        if(mysql_num_rows($query) == 1)
        {
            $row = mysql_fetch_assoc($query);
            $update = mysql_query('UPDATE users SET last_login = "'.$lastLogin.'" WHERE id = "'.$row['id'].'"');
            if ($row['active'] == 1 ) {
                set_login_sessions ( $row['id'], $row['password'] ? TRUE : FALSE );
                    if ($row['level_access'] == 2) {                                    
                        return 99;
                        }
            }
            if ($row['active'] == 2) {return 2;}
            if ($row['active'] == 0) {return 3;}            
        } else return 1;
}
 
//----------Function for logging off users----------
function logoff()
{
  //сессия должны быть запущена, прежде чем ее уничтожать
        session_start ();
    
        //если сессия активна
        if ( $_SESSION['logged_in'] == TRUE )
        {   
            //задана сессия
            unset ( $_SESSION ); 
            //уничтожаем сессию
            session_destroy (); 
        }
        
        //It is safest to set the cookies with a date that has already expired.
        if ( isset ( $_COOKIE['cookie_id'] ) && isset ( $_COOKIE['authenticate'] ) ) {
            /**
             * uncomment the following line if you wish to remove all cookies 
             * (don't forget to comment ore delete the following 2 lines if you decide to use clear_cookies)
             */
            //clear_cookies ();
            setcookie ( "cookie_id", '', time() - 3600);
            setcookie ( "authenticate", '', time() - 3600 );
        }
        
        //redirect the user to the default "logout" page
  header("Location: log_off.php");
}
 
//*******************************site access**************************
//----------Set Login Sessions----------
 
function set_login_sessions ( $user_id, $password )
{
        
        //устанавливаем время жизни куки 2 недели
        session_set_cookie_params(2*7*24*60*60);
        //start the session
        session_start();
                
        //set the sessions
        $_SESSION['user_id'] = $user_id;
        $_SESSION['logged_in'] = TRUE;      
}
 
//----------checks the level access of users----------
function checkLogin ( $levels )
{
        session_start ();
        $kt = explode ( ' ', $levels );
        
        if ( ! $_SESSION['logged_in'] ) {
        
            $access = FALSE;
            
            if ( isset ( $_COOKIE['cookie_id'] ) ) {//if we have a cookie
            
            $query = mysql_query('SELECT * FROM users WHERE id = "'.mysql_real_escape_string($_COOKIE['cookie_id']).'"');
            
            if(mysql_num_rows($query) == 1)
            $row = mysql_fetch_assoc($query);
            
            if ( $_COOKIE['authenticate'] == md5 ( getIP () . $row['password'] . $_SERVER['USER_AGENT'] ) ) {
                        //we set the sessions so we don't repeat this step over and over again
                        $_SESSION['user_id'] = $row['id'];          
                        $_SESSION['logged_in'] = TRUE;
                        
                        //now we check the level access, we might not have the permission
                        if ( in_array ( get_level_access ( $_SESSION['user_id'] ), $kt ) ) {
                            //we do?! horray!
                            $access = TRUE;
                        }
                    }
                }
            }
        else {          
            $access = FALSE;
            
            if ( in_array ( get_level_access ( $_SESSION['user_id'] ), $kt ) ) {
                $access = TRUE;
            }
        }
        
        if ( $access == FALSE ) {
            header("Location: login.php");
        }       
}
    
//----------Get Level Access----------
    
function get_level_access ( $user_id )
{
        $query = mysql_query("SELECT `level_access` FROM `users` WHERE `id` = '" .  mysql_real_escape_string ( $user_id ) . "'");
        if ( mysql_num_rows ( $query ) == 1 )
        {
            $row = mysql_fetch_array ( $query );
        }
        return $row['level_access'];
}
    
//----------IP functions----------
function ip_first ( $ips ) 
{
        if ( ( $pos = strpos ( $ips, ',' ) ) != false ) {
            return substr ( $ips, 0, $pos );
        } 
        else {
            return $ips;
        }
}
    
//----------ip_valid - will try to determine if a given ip is valid or not-----------
 
function ip_valid ( $ips )
{
    if ( isset( $ips ) ) {
        $ip    = ip_first ( $ips );
        $ipnum = ip2long ( $ip );
        if ( $ipnum !== -1 && $ipnum !== false && ( long2ip ( $ipnum ) === $ip ) ) {
            if ( ( $ipnum < 167772160   || $ipnum > 184549375 ) && // Not in 10.0.0.0/8
            ( $ipnum < - 1408237568 || $ipnum > - 1407188993 ) && // Not in 172.16.0.0/12
            ( $ipnum < - 1062731776 || $ipnum > - 1062666241 ) )   // Not in 192.168.0.0/16
            return true;
        }
    }
    return false;
}
    
//----------getIP - returns the IP of the visitor----------
function getIP () 
{
    $check = array(
            'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED', 'HTTP_VIA', 'HTTP_X_COMING_FROM', 'HTTP_COMING_FROM',
            'HTTP_CLIENT_IP'
            );
 
    foreach ( $check as $c ) {
        if ( ip_valid ( &$_SERVER [ $c ] ) ) {
            return ip_first ( $_SERVER [ $c ] );
        }
    }
 
    return $_SERVER['REMOTE_ADDR'];
}
    
//----------Random string generation function----------
 
function random_string($type = 'alnum', $len = 5)
{                   
    switch($type)
    {
        case 'alnum'    :
        case 'numeric'  :
        case 'nozero'   :
        
                switch ($type)
                {
                    case 'alnum'    :   $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        break;
                    case 'numeric'  :   $pool = '0123456789';
                        break;
                    case 'nozero'   :   $pool = '123456789';
                        break;
                }
 
                $str = '';
                for ($i=0; $i < $len; $i++)
                {
                    $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
                }
                return $str;
          break;
        case 'unique' : return md5(uniqid(mt_rand()));
          break;
    }
}
 
//*******************************unique**************************
//---------checks if record stored in db already exists or not--------
 
function uniqueUser($user)
{
    $user=secureInput($user);
    $sql = "SELECT username FROM users WHERE username = '" . $user ."' ";
    $res = mysql_query($sql);
    $num = mysql_num_rows($res);
 
    if ($num > 0)
        return true;
    return false;   
}
 
function uniqueEmail($email)
{
    $email=secureInput($email);
    $sql = "SELECT COUNT(*) as NUMBER FROM users WHERE email = '" . $email ."' ";
    $res = mysql_query($sql);
    $num = mysql_result($res,0,"NUMBER");
    
    if ($num > 0)
        return true;
    return false;   
}
 
//----------Function for checking existence of users----------
function checkUserInfo($id)
{
    $id = secureInput($id);
    
    $sql = "SELECT id FROM users WHERE id='".$id."'";
    $res = mysql_query($sql);
    $rows = mysql_num_rows($res);
    
    if($rows == 0) return TRUE;
        return FALSE;
}
 
//*******************************Function for validating an email address**************************
 
function validateEmail($email)
{
    $email=secureInput($email);
   return ( ! preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $email)) ? TRUE : FALSE;
}
 
 
//-----Function for Validating a given string against numeric characters----------
 
function validateNumeric($str)
{
    $str=secureInput($str);
    return ( ! preg_match("/^[0-9\.]+$/", $str)) ? FALSE : TRUE;
}
 
//----------Function for adding user's profile----------
function addUser($user,$pass,$email,$site_url)
{
    $user = secureInput($user);
    $pass = secureInput($pass);
    $email = secureInput($email);
    $site_url = secureInput($site_url);
 
    //Encrypt password for database
    $salt = 's+(_a*';
    $pass = md5($pass.$salt);
 
    $rand_str = random_string('alnum', 8);
    $activation_key = md5($rand_str.$salt);
 
    $reg_date = date("l, M j, Y, g:i a");
 
    $sql = "INSERT INTO users (username,password,email,active,level_access,act_key,reg_date) VALUES ('".$user."','".$pass."','".$email."',0,2,'".$activation_key."','".$reg_date."')";
    $res = mysql_query($sql) or die(mysql_error());
    if($res){
        //build email to be sent
        $to = $email;
        $subject = $site_url;
        $subject .= ": Activate Your Account";
 
        $message = "
        <html>
        <head>
        <title>Account Activation</title>
        </head>
        <body>
        <h3>Account Activation</h3>
        <p>Dear ".$user.", thank you for registering at ".$site_url.".</p>
        <p>Please click on the link below to activate your account:</p>
        <a href='".$site_url."/confirm_user_reg.php?activation_key=".$activation_key."'>.".$site_url."</a>.
        <p>If the above link does not work, copy and paste the below URL to your browser's address bar:</p>
        <p><i>http://www.".$site_url."/confirm_user_reg.php?activation_key=".$activation_key."</i></p><br/>
        <p>If you did not initiate this request, simply disregard this email, and we're sorry for bothering you.</p>
        <br/><br/>
        <p>Sincerely,</p>
        <p>The ".$site_url." Team.</p>
        </body>
        </html>
        ";
 
        // To send HTML mail, the Content-type header must be set
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
 
        if($mail_send = mail($email, $subject, $message, $headers)) {
        } return 99;
            return 1;
    }
        else return 2;
 
}
 
 
//----------Function for editing user's and admin's profile by admin----------
function editUser($id,$email,$firstname,$lastname,$dialing_code,$phone,$city,$country)
{
            $id = secureInput($id);
         $email = secureInput($email);
    $first_name = secureInput($firstname);
     $last_name = secureInput($lastname);
  $dialing_code = secureInput($dialing_code);
         $phone = secureInput($phone);
          $city = secureInput($city);
       $country = secureInput($country);
                
           
    if (!empty($email)){
            $sql = "UPDATE users SET email = '" . $email . "', first_name = '" . $first_name . "', last_name = '" . $last_name . "', dialing_code = '" . $dialing_code . "', phone = '" . $phone . "', city = '" . $city . "', country = '" . $country . "' WHERE id = '" . $id . "' AND id != 2 AND id != 35";     
            $res = mysql_query($sql) or die(mysql_error());
                if(!$res) return 4;
                return 99;
            } 
    if(empty($email)){
            $sql = "UPDATE users SET first_name = '" . $first_name . "', last_name = '" . $last_name . "', dialing_code = '" . $dialing_code . "', phone = '" . $phone . "', city = '" . $city . "', country = '" . $country . "' WHERE id = '" . $id . "' AND id != 2 AND id != 35";       
            $res = mysql_query($sql) or die(mysql_error());
                if(!$res) return 4;
                return 99;
            }
}
 
//----------Function for changing password----------//
function updatePass($id,$opass,$pass)
{
    $id = secureInput($id);
    $opass = secureInput($opass);
    $pass = secureInput($pass);
    
    $salt = 's+(_a*';
    $opasssalt = md5($opass.$salt);
    
    $query = mysql_query('SELECT `password` FROM `users` WHERE `id` = "'.$id.'"');
    $row = mysql_fetch_assoc($query);
    
    if ($opasssalt != $row['password']){
        return 2;
    }else{
    
    //Encrypt password for database
    $salt = 's+(_a*';
    $new_password = md5($pass.$salt);
 
    $sql = "UPDATE users SET password = '" . $new_password . "' WHERE id = '" . $id . "' AND id != 2 AND id != 35";
    $res = mysql_query($sql);
        if(!$res) return 3;
        return 99;
    }
}
 
//----------Function for admin change user passwords----------
function adminUpdatePass($uid,$pass)
{
    $uid = secureInput($uid);
    $pass = secureInput($pass);
    
    //Encrypt password for database
    $salt = 's+(_a*';
    $new_password = md5($pass.$salt);
 
    $sql = "UPDATE users SET password = '" . $new_password . "' WHERE id = '" . $uid . "' AND id != 2 AND id != 35";
    $res = mysql_query($sql);
    if($res) return 99;
        return 1;
}
 
//----------Function for deleting users by admin----------
function deleteUser($id)
{
    $sql = "SELECT * FROM users WHERE id = '".$id."'";
    $res = mysql_query($sql);
    if ($res){
        $del = "DELETE FROM users WHERE id = '".$id."' AND id != 35"; 
        $result = mysql_query($del);
            if($result)
                return 99;
                    return 1;
    } else return 2;    
}
 
//----------Function for suspending users by admin----------
function suspendUser($id)
{
    $sql = "SELECT id,active FROM users WHERE id = '".$id."'"; 
    $res = mysql_query($sql);
    if ($res){
        $update = "UPDATE users SET active = 2 WHERE id = '".$id."' AND id != 35";
        $result = mysql_query($update);
            if ($result)
                return 99;
                    return 1;
    } else return 2;
}
 
//----------Function for reactivating users by admin----------
function unsuspendUser($id)
{
    $sql = "SELECT id,active FROM users WHERE id = '".$id."'"; 
    $res = mysql_query($sql);
    if ($res){
        $update = "UPDATE users SET active = 1 WHERE id = '".$id."' AND id != 35";
        $result = mysql_query($update);
            if ($result)
                return 99;
                    return 1;
    } else return 2;
}
 
//----------Function for getting user records----------
function getUserRecords($id)
{
    global $getuser;
    $sql = "SELECT * FROM users WHERE id = '". $id . "'"; 
    $res = mysql_query($sql);
 
    $c=0;
    while ($a_row = mysql_fetch_array($res)) {
        $getuser[$c]["id"] = $a_row["id"];
        $getuser[$c]["username"] = $a_row["username"];
        $getuser[$c]["first_name"] = $a_row["first_name"];
        $getuser[$c]["last_name"] = $a_row["last_name"];
        $getuser[$c]["email"] = $a_row["email"];
        $getuser[$c]["dialing_code"] = $a_row["dialing_code"];
        $getuser[$c]["phone"] = $a_row["phone"];
        $getuser[$c]["city"] = $a_row["city"];
        $getuser[$c]["country"] = $a_row["country"];
        $getuser[$c]["thumb_path"] = $a_row["thumb_path"];
        $getuser[$c]["img_path"] = $a_row["img_path"];
        $getuser[$c]["active"] = $a_row["active"];
        $getuser[$c]["reg_date"] = $a_row["reg_date"];
        $getuser[$c]["last_active"] = $a_row["last_active"];
        
    $c++;
    }
    return $getuser;
}
 
//*******************************insert form data **************************
//----------Function for Logging in admin----------
function adminLogin($user,$pass)
{
    $user = secureInput($user);
    $pass = secureInput($pass);
    
    $salt = 's+(_a*';
    $pass = md5($pass.$salt);
    $lastLogin = date("l, M j, Y, g:i a");
    
        //Use the input username and password and check against 'users' table
        $query = mysql_query('SELECT id, username, password, active, level_access FROM users WHERE username = "'.secureInput($user).'" AND password = "'.secureInput($pass).'" AND level_access = 1') or die (mysql_error());
        
        if(mysql_num_rows($query) == 1)
        {
            $row = mysql_fetch_assoc($query);
            $update = mysql_query('UPDATE users SET last_login = "'.$lastLogin.'" WHERE id = "'.$row['id'].'"');
            if ($row['active'] == 1 ) {
                set_login_sessions ( $row['id'], $row['password'] ? TRUE : FALSE );
                    if ($row['level_access'] == 1) {                                    
                        return 99;
                        }
            } else return 1;
        } else return 2;
}
 
//----------Function for password recovery----------
function pass_recovery($email,$site_url)
{
    $email = secureInput($email);
    $site_url = secureInput($site_url);
    
    $sql = "SELECT id,username,password,email FROM users WHERE email = '".$email."'";
    $res = mysql_query($sql) or die(mysql_error());
    $num = mysql_num_rows($res);
    $row = mysql_fetch_assoc($res);
    
    if($num == 1)
        {
        $temp_password = random_string('alnum', 8);
        $salt = 's+(_a*';
        $temp_pass = md5($temp_password.$salt);
        
        $update = mysql_query("UPDATE users SET password='".$temp_pass."',temp_pass='".$temp_password."',temp_pass_active=1 WHERE email='".$email."'") or die(mysql_error());   
                        
        if($update){
            //build email to be sent
            $to = $row['email'];
            $subject = "Password Reset Request";
            
            $message = "
                <html>
                  <head>
                    <title>Восстановление пароля</title>
                  </head>
                  <body>
                    <h3>Ваш новый пароль</h3>
                    <p>Дорогой ".$row['username'].", кто-то(предположительно вы) запросили сброс пароля</p>
                    <p>Ваш новый временный пароль ".$temp_password.".</p>
                    <p>To confirm this change and activate your new password, please follow this link to our website:</p> 
                    <a href=\"".$site_url."/confirm_pass.php?id=".$row['id']."&new=".$temp_password."\">".$site_url."</a>.
                    <b><i>".$site_url."/confirm_pass.php?id=".$row['id']."&new=".$temp_password."</b></i>
                    <p>Don't forget to update your profile as well after confirming this change and create a new password.</p><br/> 
                    <p>If you did not initiate this request, simply disregard this email, and we're sorry for bothering you.</p>
                    <br/><br/>
                    <p>Sincerely,</p>
                    <p>SiteName Team.</p>
                  </body>
                </html>
                ";
 
                // To send HTML mail, the Content-type header must be set
                $headers = "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
 
            if($mail_send = mail($row['email'], $subject, $message, $headers)) {
            } return 99;
             return 1;
        } else return 2;
    }
    else return 3;
}
 
//----------Function for confirming password----------
function confirm_pass($id,$new)
{
     $id = secureInput($id);
    $new = secureInput($new);
    
    $query = mysql_query("SELECT password,temp_pass,temp_pass_active FROM users WHERE id = '".$id."'");
 
    if(mysql_num_rows($query)==1)
    {
        $row = mysql_fetch_assoc($query);
        if($row['temp_pass']==$_GET['new'] && $row['temp_pass_active']==1)
        {
            $update = mysql_query("UPDATE users SET temp_pass_active=0 WHERE id = '".mysql_real_escape_string($_GET['id'])."'");
            if($update){
                return 99;
            } else return 1;
        }
        else
        {
            return 2;
        }
    }
    else {
        return 3;
    }
}
 
//----------Function for confirming user through email submitted----------
function confirm_user_reg($activation_key)
{
     $activation_key = mysql_real_escape_string($activation_key);
        
    $query = mysql_query("SELECT id,active,act_key FROM users WHERE act_key = '".$activation_key."'");
 
    if(mysql_num_rows($query)==1)
    {
        $row = mysql_fetch_assoc($query);
        $id = $row['id'];
        if($row['active']==0)
        {
            $update = mysql_query("UPDATE users SET active=1,act_key='' WHERE id = '".$id."'");
            if($update){
                return 99;
            } else return 1;
        }
        if($row['active']==1)
        {
            return 2;
        }
    }
    else {
        return 3;
    }
}
 
//----------Function for inserting info to contact us----------
function contactUs($name,$email,$message,$site_email)
{
       $name = secureInput($name);
      $email = secureInput($email);
    $message = secureInput($message);
 $site_email = secureInput($site_email);
            
        //build email to be sent
        $to = $site_email;
        $subject = "New message from ".$email;
        
        $message = "
            <html>
              <head>
                <title>New message from".$name."</title>
              </head>
              <body>
                <h3>Query / Comment</h3>
                <p>Site Admin, ".$name." has sent a query/comment. It is as below:</p>
                <p>".$message."</p>
              </body>
            </html>
            ";
 
            // To send HTML mail, the Content-type header must be set
            $headers = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
 
            $mail_send = mail($to, $subject, $message, $headers );
            if ($mail_send)
                return 99;
             return 1;
}
 
//----------get Site Settings ----------
function getSiteSettings()
{
    global $sitesettings;
    
    $sql = "SELECT id,site_url,site_email FROM site_settings";
    $res = mysql_query($sql);
    
        $c=0;
        while ($row = mysql_fetch_array($res)) {
            $sitesettings[$c]["id"] = $row["id"];
            $sitesettings[$c]["site_url"] = $row["site_url"];
            $sitesettings[$c]["site_email"] = $row["site_email"];
            
        $c++;
        }
        return $sitesettings;
}
 
//----------Function for updating site settings----------
function updateSiteSet($site_url,$site_email)
{       
           $site_url = secureInput($site_url);
         $site_email = secureInput($site_email);
         
        $sql = "SELECT * FROM site_settings";
        $res = mysql_query($sql);
        $numRows = mysql_num_rows($res);
        
        if ($numRows == 0){
            $sql = "INSERT INTO site_settings (site_url,site_email) VALUES('".$site_url."','".$site_email."')";
            $res = mysql_query($sql);
                if(!$res) return 1;
            return 99;
            }
        if ($numRows > 0){
            $sql = "UPDATE site_settings SET site_url = '" . $site_url . "', site_email = '" . $site_email . "' ";      
            $res = mysql_query($sql);
                if(!$res) return 1;
            return 99;
            }
}
 
//----------get country via select option----------
function get_country()
{
    
    $sql = "SELECT id,country FROM countries ORDER BY id ASC";
    $res = mysql_query($sql);
        
    echo "<select id=\"country\" class=\"searchbox\" name=\"country\">";
        echo "<option value=\"\">Select One</option>";
        while ($row = mysql_fetch_assoc($res)){
            echo "<option value=\"".$row['country']."\">".$row['country']."</option>";
            }
    echo "</select>";
}
 
//----------get countries via select option from users----------
function get_select_countries($id)
{
    $id = secureInput($id);
    
    $sql = "SELECT country FROM countries ORDER BY country ASC";
    $res = mysql_query($sql);
        
    $sql1 = "SELECT country FROM users WHERE id='".$id."'";
    $res1 = mysql_query($sql1);
    $row1 = mysql_fetch_assoc($res1);
    
    if($row1){
        echo "<select name=\"country\">";
        echo "<option selected=".$row1['country']." value=\"".$row1['country']."\">".$row1['country']."</option>";
        while ($row = mysql_fetch_assoc($res)){
            echo "<option value=\"".$row['country']."\">".$row['country']."</option>";
            }
        echo "</select>";
        } else {
            echo "<select name=\"country\">";
            while ($row = mysql_fetch_assoc($res)){
                echo "<option value=\"".$row['country']."\">".$row['country']."</option>";
            }
            echo "</select>";
    }
}
 
//----------get dialing code via select option----------
function get_dialing_code($id)
{
    $id = secureInput($id);
    
    $sql = "SELECT dialing_code FROM dialing_code ORDER BY name ASC";
    $res = mysql_query($sql);
        
    $sql1 = "SELECT dialing_code FROM users WHERE id='".$id."'";
    $res1 = mysql_query($sql1);
    $row1 = mysql_fetch_assoc($res1);
    
    if($row1){
        echo "<select name=\"dialing_code\">";
        echo "<option selected=".$row1['dialing_code']." value=\"".$row1['dialing_code']."\">".$row1['dialing_code']."</option>";
        while ($row = mysql_fetch_assoc($res)){
            echo "<option value=\"".$row['dialing_code']."\">".$row['dialing_code']."</option>";
            }
        echo "</select>";
        } else {
            echo "<select name=\"dialing_code\">";
            while ($row = mysql_fetch_assoc($res)){
                echo "<option value=\"".$row['dialing_code']."\">".$row['dialing_code']."</option>";
            }
            echo "</select>";
    }
}
 
//////////////////////////////////////////User Image Functions//////////////////////////////////
//----------Check image size----------
function checkImageSize($tmpfile, $max)
{
    //check the tmpimage file size and see if it is to big returns true if to large
    $size = filesize($tmpfile);
    if ($size > $max)
        return true;
    return false;
}
 
//----------Check allowed extension----------
function checkAllowedExt($file)
{
    $temp = strtolower($file);
    $ext = pathinfo($temp, PATHINFO_EXTENSION);
    $allowed = array('gif', 'jpg', 'jpeg', 'png');
    if (!in_array($ext, $allowed))
        return true;
    return false;
}
 
//----------Open image file----------
function openImage($file)
{
    // Get extension and return it
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    switch(strtolower($ext)) {
        case 'jpg':
        case 'jpeg':
            $im = @imagecreatefromjpeg($file);
            break;
        case 'gif':
            $im = @imagecreatefromgif($file);
            break;
        case 'png':
            $im = @imagecreatefrompng($file);
            break;
        default:
            $im = false;
            break;
    }
    return $im;
}
 
//----------Create thumbnail image for user----------
function createThumb($file, $ext, $width)
{
    $im = '';
    $im = openImage($file);
 
    if (empty($im)) {
        return false;
    }
 
    $old_x = imagesx($im);
    $old_y = imagesy($im);
 
    $new_w = (int)$width;
 
    if (($new_w <= 0) or ($new_w > $old_x)) {
        $new_w = $old_x;
    }
 
    $new_h = ($old_x * ($new_w / $old_x));
 
    if ($old_x > $old_y) {
        $thumb_w = $new_w;
        $thumb_h = $old_y * ($new_h / $old_x);
    }
    if ($old_x < $old_y) {
        $thumb_w = $old_x * ($new_w / $old_y);
        $thumb_h = $new_h;
    }
    if ($old_x == $old_y) {
        $thumb_w = $new_w;
        $thumb_h = $new_h;
    }
 
    $thumb = imagecreatetruecolor($thumb_w,$thumb_h);
 
    if ($ext == 'png') {
        imagealphablending($thumb, false);
        $colorTransparent = imagecolorallocatealpha($thumb, 0, 0, 0, 127);
        imagefill($thumb, 0, 0, $colorTransparent);
        imagesavealpha($thumb, true);
    } elseif ($ext == 'gif') {
        $trnprt_indx = imagecolortransparent($im);
        if ($trnprt_indx >= 0) {
            //its transparent
            $trnprt_color = imagecolorsforindex($im, $trnprt_indx);
            $trnprt_indx = imagecolorallocate($thumb, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
            imagefill($thumb, 0, 0, $trnprt_indx);
            imagecolortransparent($thumb, $trnprt_indx);
        }
    }
 
    imagecopyresampled($thumb,$im,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
 
    //choose which image program to use
    switch(strtolower($ext)) {
        case 'jpg':
        case 'jpeg':
            imagejpeg($thumb,$file);
            break;
        case 'gif':
            imagegif($thumb,$file);
            break;
        case 'png':
            imagepng($thumb,$file);
            break;
        default:
            return false;
            break;
    }
 
    imagedestroy($im);
    imagedestroy($thumb);
}
 
//----------Move uploaded image file ----------
function moveUploadImage($path, $file, $tmpfile, $max)
{
    //upload your image and give it a random name so no conflicts occur
    $rand = rand(1000,9000);
    $save_path = $path . $rand . $file;
    
    //prep file for db and gd manipulation
    $bad_char_arr = array(' ', '&', '(', ')', '*', '[', ']', '<', '>', '{', '}');
    $replace_char_arr = array('-', '_', '', '', '', '', '', '', '', '', '');
    $save_path = str_replace($bad_char_arr, $replace_char_arr, $save_path);
 
    //move the temp file to the proper place
    if (move_uploaded_file($tmpfile, $save_path)) {
        $ext = pathinfo($save_path, PATHINFO_EXTENSION);
        $base = pathinfo($save_path, PATHINFO_FILENAME);
        $dir = pathinfo($save_path, PATHINFO_DIRNAME);
        $base_path = "$dir/$base";
 
        copy($save_path, "$base_path" . "_thumb" . "." . "$ext");
        createThumb("$base_path" . "_thumb" . "." . "$ext", $ext, 150);
        createThumb("$base_path" . "." . "$ext", $ext, 640);
        
        //chmod("$base_path" . "_thumb" . "." . "$ext", 0644);
        //chmod("$base_path" . "." . "$ext", 0644);
 
        return $save_path;
    }
    unlink($tmpfile);
    return false;
}
//----------upload user image----------
function uploadUserImage($path, $file, $tmpfile, $max, $id)
{
       $id = secureInput($id);
       
       if (empty($file))
          return 1;
       if (!getimagesize($tmpfile))
          return false;
       if (checkImageSize($tmpfile, $max))
          return 2;
       if (checkAllowedExt($file))
          return 3;
          
    $save_path = moveUploadImage($path, $file, $tmpfile, $max);
    if (!empty($save_path)) {
        $ext = pathinfo($save_path, PATHINFO_EXTENSION);
        $base = pathinfo($save_path, PATHINFO_FILENAME);
        $dir = pathinfo($save_path, PATHINFO_DIRNAME);
        $base_path = "$dir/$base";
 
        $save_thumb_path = "$base_path" . "_thumb" . "." . "$ext";
        
        $sql = "UPDATE users SET thumb_path = '" . $save_thumb_path . "', img_path = '" . $save_path . "' WHERE id = '".$id."'";
        $res = mysql_query($sql);
            if($res){return 99;} else {return 4;}
    } else {return 5;}
}
 
//----------Update user image----------
function updateUserImage($path, $file, $tmpfile, $max, $id)
{
       $id = secureInput($id);
            
       if (empty($file))
          return 1;
       if (!getimagesize($tmpfile))
          return false;
       if (checkImageSize($tmpfile, $max))
          return 2;
       if (checkAllowedExt($file))
          return 3;
 
    //look up old image path then remove the file before preceding with the new image upload
    $sql = "SELECT thumb_path,img_path FROM users WHERE id = '" . $id . "'";
    $res = mysql_query($sql);
    $row = mysql_fetch_assoc($res);
    $del = $row["thumb_path"];
    $delg = $row["img_path"];
        
    if (!empty($del)) {
        $dir = pathinfo($del, PATHINFO_DIRNAME);
        $ext = pathinfo($del, PATHINFO_EXTENSION);
        $base = pathinfo($del, PATHINFO_FILENAME);
        $base_path = "$dir/$base";
 
        unlink("$del");
        unlink("$base_path" . "_thumb" . "." . "$ext");
    }
    if (!empty($delg)) {
        $dirg = pathinfo($delg, PATHINFO_DIRNAME);
        $extg = pathinfo($delg, PATHINFO_EXTENSION);
        $baseg = pathinfo($delg, PATHINFO_FILENAME);
        $gbase_path = "$dirg/$baseg";
 
        unlink("$delg");
        unlink("$gbase_path" . "." . "$extg");
    }
    
    $save_path = moveUploadImage($path, $file, $tmpfile, $max, $id);
    if (!empty($save_path)) {
        $ext = pathinfo($save_path, PATHINFO_EXTENSION);
        $base = pathinfo($save_path, PATHINFO_FILENAME);
        $dir = pathinfo($save_path, PATHINFO_DIRNAME);
        $base_path = "$dir/$base";
 
        $save_thumb_path = "$base_path" . "_thumb" . "." . "$ext"; 
        $sql = "UPDATE users SET thumb_path = '" . $save_thumb_path . "', img_path = '" . $save_path . "' WHERE id = '" . $id . "'";
        $res = mysql_query($sql) or die(mysql_error());
        }
        if ($res)
            return 99;
                return 4;
}
 
//----------Delete user image----------
function deleteImage($id)
{
    $id = secureInput($id);
            
    //look up old image path and remove image from image folder
    $sql = "SELECT thumb_path,img_path FROM users WHERE id = '" . $id . "'";
    $res = mysql_query($sql);
    $row = mysql_fetch_assoc($res);
    $del = $row["thumb_path"];
    $delg = $row["img_path"];
        
    if (!empty($del)) {
        $dir = pathinfo($del, PATHINFO_DIRNAME);
        $ext = pathinfo($del, PATHINFO_EXTENSION);
        $base = pathinfo($del, PATHINFO_FILENAME);
        $base_path = "$dir/$base";
 
        unlink("$base_path" . "." . "$ext");
    }
    
    if (!empty($delg)) {
        $dirg = pathinfo($delg, PATHINFO_DIRNAME);
        $extg = pathinfo($delg, PATHINFO_EXTENSION);
        $baseg = pathinfo($delg, PATHINFO_FILENAME);
        $gbase_path = "$dirg/$baseg";
 
        unlink("$gbase_path" . "." . "$extg");
    }
    
    $sql = "UPDATE users SET thumb_path = '', img_path = '' WHERE id = '" . $id . "'";
    $res = mysql_query($sql);
    if ($res){return 99;} else {return 1;}
}
 
//----------Function for displaying user image on home page and admin user management page----------
function displayUserImg($id)
{
    $sql = "SELECT thumb_path FROM users WHERE id = '".$id."'";
    $res = mysql_query($sql);
    $row = mysql_fetch_assoc($res);
    
    if (!empty($row['thumb_path'])){
        echo "<img src='".$row['thumb_path']."' width='150' height='100' border='0' alt='' hspace='2' />";
    } else {
        //display a default image if user image does not exist
        echo "<img src='pics/no_image.gif' width='150' height='100' border='0' alt='' hspace='2' />";
    }
}
 
?>


Добавлено через 23 часа 2 минуты
не получается реализовать.
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
10.04.2014, 21:21
Ответы с готовыми решениями:

Форма авторизации и форма Регистрации(Личный кабинет)
Здравствуйте! Подскажите мне пожалуйста, как мне сделать личный кабинет после авторизации, чтобы я...

Реализовать личный кабинет по данной авторизации
Здравствуйте! Помогите пожалуйста, создать личный кабинет пользователя для данной авторизации: &lt;?...

Подскажите, как организовать профиль пользователя или личный кабинет пользователя
Я изучаю jango и не могу разобраться как организовать личный кабинет пользователя, чтобы после...

Личный кабинет пользователя
Всем привет, ребят подскажите как создать на сайте личный кабинет пользователя?

2
289 / 34 / 6
Регистрация: 20.09.2011
Сообщений: 464
11.04.2014, 16:54 2
NONEMOX, проверь, заносится ли что-нибудь в куки после авторизации (это можно проверить в обычном браузере). А вообще, зачем копировать весь исходный код? Лучше скопируй ту часть, в которой у тебя проблема. Так будет намного легче разобраться с проблемой.
0
4 / 4 / 2
Регистрация: 28.10.2010
Сообщений: 180
11.04.2014, 23:26  [ТС] 3
Какие то данные все таки заносятся
0
11.04.2014, 23:26
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
11.04.2014, 23:26
Помогаю со студенческими работами здесь

Личный кабинет пользователя
Всем привет, собственно сабж, подскажите плз как сделать такую штуку. Пользователь регается,...

Личный кабинет пользователя
Здравствуйте, не могли бы вы мне помочь разобраться со следующей проблемой. Когда пользователь...

Форма регистрации и личный кабинет
Добрый день. Подскажите хороший модуль регистрации с простым личным кабинетом, где реализованы...

Личный кабинет пользователя + оплата
здравствуйте подскажите, пожалуйста, как реализовать на вордпресс личный кабинет пользователя? ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru