Hướng dẫn php user profile page - trang hồ sơ người dùng php

Hello, xin chào tất cả các bạn, chào mừng các bạn đã quay trở lại với series hướng dẫn xây dựng trang web tin tức căn bản PHP. Ở bài hôm trước chúng ta đã xây dựng xong các chức năng tài khoản trong admin, hôm nay mình sẽ hướng dẫn các bạn viết các chức năng profile. Bây giờ chúng ta đi vào bài thôi!

Hướng dẫn php user profile page - trang hồ sơ người dùng php

Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.freetuts.net, không được copy dưới mọi hình thức.

1. Khái quát

Phần này có nhiệm vụ update các thông tin hồ sơ của tài khoản tác giả cũng như quản trị viên.

Các đặc điểm và chức năng trong phần này:

  • Cập nhật tên hiển thị
  • Cập nhật email
  • Đổi mật khẩu
  • Cập nhật url facebook, google, twitter
  • Cập nhật số điện thoại
  • Cập nhật giới thiệu
  • Upload ảnh đại diện

2. Table hồ sơ

Table này chúng ta đã tạo khi xây dựng chức năng đăng nhập ở bài 6, đó chính là table accounts. Các field chúng ta tương tác là:

Bài viết này được đăng tại [free tuts .net]

  • password: mật khẩu
  • display_name: tên hiển thị
  • email: tên email
  • facebook: url tài khoản Facebook
  • // Xem ảnh avatar trước
    function preUpAvt() {
        img_avt = $('#img_avt').val();
        $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
        $('#formUpAvt .box-pre-img').removeClass('hidden');
     
        // Nếu đã chọn ảnh
        if (img_avt != '')
        {
            $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
            $('#formUpAvt .box-pre-img').removeClass('hidden');
    		$('#formUpAvt .box-pre-img').append('<img src="' + URL.createObjectURL(event.target.files[0]) + '" style="border: 1px solid #ddd; width: 50px; height: 50px; margin-right: 5px; margin-bottom: 5px;"/>');
        } 
        // Ngược lại chưa chọn ảnh
        else
        {
            $('#formUpAvt .box-pre-img').html('');
            $('#formUpAvt .box-pre-img').addClass('hidden');
        }
    }
    0: url tài khoản Google Plus
  • // Xem ảnh avatar trước
    function preUpAvt() {
        img_avt = $('#img_avt').val();
        $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
        $('#formUpAvt .box-pre-img').removeClass('hidden');
     
        // Nếu đã chọn ảnh
        if (img_avt != '')
        {
            $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
            $('#formUpAvt .box-pre-img').removeClass('hidden');
    		$('#formUpAvt .box-pre-img').append('<img src="' + URL.createObjectURL(event.target.files[0]) + '" style="border: 1px solid #ddd; width: 50px; height: 50px; margin-right: 5px; margin-bottom: 5px;"/>');
        } 
        // Ngược lại chưa chọn ảnh
        else
        {
            $('#formUpAvt .box-pre-img').html('');
            $('#formUpAvt .box-pre-img').addClass('hidden');
        }
    }
    1: url tài khoản Twitter
  • // Xem ảnh avatar trước
    function preUpAvt() {
        img_avt = $('#img_avt').val();
        $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
        $('#formUpAvt .box-pre-img').removeClass('hidden');
     
        // Nếu đã chọn ảnh
        if (img_avt != '')
        {
            $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
            $('#formUpAvt .box-pre-img').removeClass('hidden');
    		$('#formUpAvt .box-pre-img').append('<img src="' + URL.createObjectURL(event.target.files[0]) + '" style="border: 1px solid #ddd; width: 50px; height: 50px; margin-right: 5px; margin-bottom: 5px;"/>');
        } 
        // Ngược lại chưa chọn ảnh
        else
        {
            $('#formUpAvt .box-pre-img').html('');
            $('#formUpAvt .box-pre-img').addClass('hidden');
        }
    }
    2: số điện thoại
  • // Xem ảnh avatar trước
    function preUpAvt() {
        img_avt = $('#img_avt').val();
        $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
        $('#formUpAvt .box-pre-img').removeClass('hidden');
     
        // Nếu đã chọn ảnh
        if (img_avt != '')
        {
            $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
            $('#formUpAvt .box-pre-img').removeClass('hidden');
    		$('#formUpAvt .box-pre-img').append('<img src="' + URL.createObjectURL(event.target.files[0]) + '" style="border: 1px solid #ddd; width: 50px; height: 50px; margin-right: 5px; margin-bottom: 5px;"/>');
        } 
        // Ngược lại chưa chọn ảnh
        else
        {
            $('#formUpAvt .box-pre-img').html('');
            $('#formUpAvt .box-pre-img').addClass('hidden');
        }
    }
    3: phần giới thiệu
  • // Xem ảnh avatar trước
    function preUpAvt() {
        img_avt = $('#img_avt').val();
        $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
        $('#formUpAvt .box-pre-img').removeClass('hidden');
     
        // Nếu đã chọn ảnh
        if (img_avt != '')
        {
            $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
            $('#formUpAvt .box-pre-img').removeClass('hidden');
    		$('#formUpAvt .box-pre-img').append('<img src="' + URL.createObjectURL(event.target.files[0]) + '" style="border: 1px solid #ddd; width: 50px; height: 50px; margin-right: 5px; margin-bottom: 5px;"/>');
        } 
        // Ngược lại chưa chọn ảnh
        else
        {
            $('#formUpAvt .box-pre-img').html('');
            $('#formUpAvt .box-pre-img').addClass('hidden');
        }
    }
    4: url ảnh đại diện  

Mình sẽ chia các field này thành 3 phần để xây dựng

  • Upload ảnh đại diện
  • 2. Table hồ sơ
  • Đổi mật khẩu

Cập nhật url facebook, google, twitter

Cập nhật số điện thoại

Cập nhật giới thiệu

Upload ảnh đại diện

<?php

// Nếu đăng nhập
if ($user) 
{
	// URL ảnh đại diện tài khoản
	if ($data_user['url_avatar'] == '')
	{
		$data_user['url_avatar'] = $_DOMAIN.'images/profile.png';
	}
	else
	{
		$data_user['url_avatar'] = str_replace('admin/', '', $_DOMAIN).$data_user['url_avatar'];
	}

	// Form Upload ảnh đại diện
	echo 
	'
		<h3>Hồ sơ cá nhân</h3>
		<div class="panel panel-default">
			<div class="panel-heading">Upload ảnh đại diện</div>
			<div class="panel-body">
				<form action="' . $_DOMAIN . 'profile.php" method="POST" onsubmit="return false;" id="formUpAvt" enctype="multipart/form-data">
					<div class="form-group box-current-img">
                        <p><strong>Ảnh hiện tại</strong></p>
                        <img src="' . $data_user['url_avatar'] . '" alt="Ảnh đại diện của ' . $data_user['display_name'] . '" width="80" height="80">
                    </div>
					<div class="alert alert-info">Vui lòng chọn file ảnh có đuôi .jpg, .png, .gif và có dung lượng dưới 5MB.</div>
					<div class="form-group">
						<label>Chọn hình ảnh</label>
						<input type="file" class="form-control" id="img_avt" name="img_avt" onchange="preUpAvt();">
					</div>
					<div class="form-group box-pre-img hidden">
                        <p><strong>Ảnh xem trước</strong></p>
                    </div>            
                    <div class="form-group hidden box-progress-bar">
                        <div class="progress">
                            <div class="progress-bar" role="progressbar"></div>
                        </div>
                    </div>
					<div class="form-group">
						<button class="btn btn-primary pull-left" type="submit">Upload</button>
						<a class="btn btn-danger pull-right" id="del_avt"><span class="glyphicon glyphicon-trash"></span> Xoá</a>
					</div>
					<div class="clearfix"></div><br>
					<div class="alert alert-danger hidden"></div>
				</form>
			</div>
		</div>
	';

	// Form Cập nhật các thông tin còn lại
}
// Ngược lại chưa đăng nhập
else
{
    new Redirect($_DOMAIN); // Trở về trang index
}

?>

2. Table hồ sơ

Table này chúng ta đã tạo khi xây dựng chức năng đăng nhập ở bài 6, đó chính là table accounts. Các field chúng ta tương tác là:

Bài viết này được đăng tại [free tuts .net]

  • password: mật khẩu
  • Upload ảnh đại diện
  • 2. Table hồ sơ

Table này chúng ta đã tạo khi xây dựng chức năng đăng nhập ở bài 6, đó chính là table accounts. Các field chúng ta tương tác là:

password: mật khẩu

// Xem ảnh avatar trước
function preUpAvt() {
    img_avt = $('#img_avt').val();
    $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
    $('#formUpAvt .box-pre-img').removeClass('hidden');
 
    // Nếu đã chọn ảnh
    if (img_avt != '')
    {
        $('#formUpAvt .box-pre-img').html('<p><strong>Ảnh xem trước</strong></p>');
        $('#formUpAvt .box-pre-img').removeClass('hidden');
		$('#formUpAvt .box-pre-img').append('<img src="' + URL.createObjectURL(event.target.files[0]) + '" style="border: 1px solid #ddd; width: 50px; height: 50px; margin-right: 5px; margin-bottom: 5px;"/>');
    } 
    // Ngược lại chưa chọn ảnh
    else
    {
        $('#formUpAvt .box-pre-img').html('');
        $('#formUpAvt .box-pre-img').addClass('hidden');
    }
}

Upload ảnh đại diện

// Upload ảnh đại diện
$('#formUpAvt').submit(function(e) {
    img_avt = $('#img_avt').val();
    $('#formUpAvt button[type=submit]').html('Đang tải ...');
 
    // Nếu có chọn ảnh
    if (img_avt) {
    	size_img_avt = $('#img_avt')[0].files[0].size;
    	type_img_avt = $('#img_avt')[0].files[0].type;

        e.preventDefault();
        // Nếu lỗi về size ảnh
        if (size_img_avt > 5242880) { // 5242880 byte = 5MB 
            $('#formUpAvt button[type=submit]').html('Upload');
            $('#formUpAvt .alert-danger').removeClass('hidden');
            $('#formUpAvt .alert-danger').html('Tệp đã chọn có dung lượng lớn hơn mức cho phép.');
        // Nếu lỗi về định dạng ảnh
        } else if (type_img_avt != 'image/jpeg' && type_img_avt != 'image/png' && type_img_avt != 'image/gif') {
            $('#formUpAvt button[type=submit]').html('Upload');
            $('#formUpAvt .alert-danger').removeClass('hidden');
            $('#formUpAvt .alert-danger').html('File ảnh không đúng định dạng cho phép.');
        } else {
            $(this).ajaxSubmit({ 
                beforeSubmit: function() {
                    target:   '#formUpAvt .alert-danger', 
                    $("#formUpAvt .box-progress-bar").removeClass('hidden');
                    $("#formUpAvt .progress-bar").width('0%');
                },
                uploadProgress: function (event, position, total, percentComplete){ 
                    $("#formUpAvt .progress-bar").animate({width: percentComplete + '%'});
                    $("#formUpAvt .progress-bar").html(percentComplete + '%');
                },
                success: function (data) {     
                    $('#formUpAvt button[type=submit]').html('Upload');
                    $('#formUpAvt .alert-danger').attr('class', 'alert alert-success'); 
                    $('#formUpAvt .alert-success').html(data);
                },
                error: function() {
                    $('#formUpAvt button[type=submit]').html('Upload');
                    $('#formUpAvt .alert-danger').removeClass('hidden');  
                    $('#formUpAvt .alert-danger').html('Không thể upload hình ảnh vào lúc này, hãy thử lại sau.');
                },
                resetForm: true
            }); 
            return false;
        }
    // Ngược lại không chọn ảnh
    } else {
        $('#formUpAvt button[type=submit]').html('Upload');
        $('#formUpAvt .alert-danger').removeClass('hidden');
        $('#formUpAvt .alert-danger').html('Vui lòng chọn tệp hình ảnh.');
    }
});

2. Table hồ sơ

// Xoá ảnh đại diện
$('#del_avt').on('click', function() {
	$confirm = confirm('Bạn có chắc chắn muốn xoá ảnh đại diện này không?');
	if ($confirm == true)
	{
		$.ajax({
			url : $_DOMAIN + 'profile.php',
			type : 'POST',
			data : {
				action : 'delete_avt'
			}, success : function() {
				location.reload();
			}, error : function() {
				alert('Đã có lỗi xảy ra, vui lòng thử lại.');
			}
		});
	}
	else {
		return false;
	}
});

Table này chúng ta đã tạo khi xây dựng chức năng đăng nhập ở bài 6, đó chính là table accounts. Các field chúng ta tương tác là:

Bài viết này được đăng tại [free tuts .net]

password: mật khẩu

  • Upload ảnh đại diện
  • 2. Table hồ sơ

Table này chúng ta đã tạo khi xây dựng chức năng đăng nhập ở bài 6, đó chính là table accounts. Các field chúng ta tương tác là:

<?php

// Kết nối database và thông tin chung
require_once 'core/init.php';

// Nếu đăng nhập
if ($user) 
{
	// Nếu có file upload
	if (isset($_FILES['img_avt'])) 
	{
		$dir = "../upload/"; 
		$name_img = stripslashes($_FILES['img_avt']['name']);
		$source_img = $_FILES['img_avt']['tmp_name'];

		// Lấy ngày, tháng, năm hiện tại
		$day_current = substr($date_current, 8, 2);
		$month_current = substr($date_current, 5, 2);
		$year_current = substr($date_current, 0, 4);

		// Tạo folder năm hiện tại
		if (!is_dir($dir.$year_current))
		{
    		mkdir($dir.$year_current.'/');
		} 

		// Tạo folder tháng hiện tại
		if (!is_dir($dir.$year_current.'/'.$month_current))
    	{
    		mkdir($dir.$year_current.'/'.$month_current.'/');
    	}	

    	// Tạo folder ngày hiện tại
    	if (!is_dir($dir.$year_current.'/'.$month_current.'/'.$day_current))
	    {
	    	mkdir($dir.$year_current.'/'.$month_current.'/'.$day_current.'/');
	    }

		$path_img = $dir.$year_current.'/'.$month_current.'/'.$day_current.'/'.$name_img; // Đường dẫn thư mục chứa file
		move_uploaded_file($source_img, $path_img); // Upload file
		$url_img = substr($path_img, 3); // Đường dẫn file

		$sql_up_avt = "UPDATE accounts SET url_avatar = '$url_img' WHERE id_acc = '$data_user[id_acc]'";
		$db->query($sql_up_avt);
		echo 'Upload thành công.';
		$db->close();
		new Redirect($_DOMAIN.'profile');
	} 
	// Nếu tồn tại POST action
	else if (isset($_POST['action']))
	{
		$action = trim(addslashes(htmlspecialchars($_POST['action'])));

		// Xoá ảnh đại diện
		if ($action == 'delete_avt')
		{		
			if (file_exists('../'.$data_user['url_avatar']))
			{
				unlink('../'.$data_user['url_avatar']);
			}

			$sql_delete_avt = "UPDATE accounts SET url_avatar = '' WHERE id_acc = '$data_user[id_acc]'";
			$db->query($sql_delete_avt);
			$db->close();	
		}
	}
	else
	{
		new Redirect($_DOMAIN); 
	}
}
// Ngược lại chưa đăng nhập
else
{
    new Redirect($_DOMAIN); // Trở về trang index
}
 
?>

Bài viết này được đăng tại [free tuts .net]

password: mật khẩu

// URL ảnh đại diện tài khoản
if ($data_user['url_avatar'] == '')
{
	echo $_DOMAIN.'images/profile.png';
}
else
{
	echo str_replace('admin/', '', $_DOMAIN).$data_user['url_avatar'];
}

display_name: tên hiển thị

email: tên email

facebook: url tài khoản Facebook