php session tutorial with dynamic image

Hello, Friends! In the previous tutorial, we have seen all about the php session and successfully built the login and registration portal using php and MySQL database. Now, we’re going to make the image change according to the user.i.e. dynamic image.
Note: Please make sure that you’ve gone through the previous session tutorial in order to understand this tutorial. If not, then please find it here.

php session tutorial

We are using the same files as in previous session tutorial. so I will not mention all of them here. We have to modify the file home.php to support the dynamic showing of the image. Just add one field ‘picpath’ in the database having varchar type and value as ’50’. Now, open the previously coded file home.php and add the below code in it.

<?php
	require_once("session.php");
	require_once("class.user.php");
	$auth_user = new USER();
	$user_id = $_SESSION['user_session'];
	$stmt = $auth_user->runQuery("SELECT * FROM users WHERE user_id=:user_id");
	$stmt->execute(array(":user_id"=>$user_id));
	//Image
	$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
	//unlink("user_images/".$userRow['userPic']);
	///////////////////////////////////////////////////////////////////////
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "technopoints";
  
  try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}
  catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }
	///////////////////////////////////////////////////////////////////////

?>
<!--<html>
<title>Technopoints Profile:<?php print($userRow['user_name']); ?></title>
<body>
<h1>Welcome, <?php print($userRow['user_name']); ?>!</h1>
<a href="logout.php?logout=true"><input type="submit" value="Logout"></a>-->

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Welcome, <?php print($userRow['user_name'])?></title>
<link href="https://fonts.googleapis.com/css?family=Merienda+One" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="bootstrap/css/font-awesome.min.css">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="bootstrap/css/style.css">
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>

</head> 
<body>
<nav class="navbar navbar-default navbar-expand-xl navbar-light">
	<div class="navbar-header d-flex col">
		<a class="navbar-brand" href="#">Technopoints</a>  		
		<button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle navbar-toggler ml-auto">
			<span class="navbar-toggler-icon"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
		</button>
	</div>
	<!-- Collection of nav links, forms, and other content for toggling -->
	<div id="navbarCollapse" class="collapse navbar-collapse justify-content-start">
		<ul class="nav navbar-nav">
			<li class="nav-item active"><a href="#" class="nav-link">Home</a></li>
			<li class="nav-item"><a href="https://www.technopoints.co.in/about" class="nav-link">About</a></li>
			<li class="nav-item dropdown">
				<a data-toggle="dropdown" class="nav-link dropdown-toggle" href="#">Services <b class="caret"></b></a>
				<ul class="dropdown-menu">					
					<li><a href="#" class="dropdown-item">Web Design</a></li>
					<li><a href="#" class="dropdown-item">Web Development</a></li>
					<li><a href="#" class="dropdown-item">Graphic Design</a></li>
					<li><a href="#" class="dropdown-item">Digital Marketing</a></li>
				</ul>
			</li>
			<li class="nav-item"><a href="https://www.technopoints.co.in" class="nav-link">Blog</a></li>
			<li class="nav-item"><a href="https://www.technopoints.co.in/contact" class="nav-link">Contact</a></li>
		</ul>
		<form class="navbar-form form-inline">
			<div class="input-group search-box">								
				<input type="text" id="search" class="form-control" placeholder="Search by Name">
				<span class="input-group-addon"><i class="material-icons">&#xE8B6;</i></span>
			</div>
		</form>
		<ul class="nav navbar-nav navbar-right ml-auto">
			<li class="nav-item dropdown">
				<a href="#" data-toggle="dropdown" class="nav-link dropdown-toggle user-action"><img src="<?php print($userRow['picpath'])?>" class="avatar" alt="Avatar"> <?php print($userRow['user_name']); ?> <b class="caret"></b></a>
				<ul class="dropdown-menu">
					<li><a href="logout.php?logout=true" class="dropdown-item"><i class="material-icons">&#xE8AC;</i> Logout</a></li>
				</ul>
			</li>
		</ul>
	</div>
</nav>
<center>
<h1>Welcome, <?php print($userRow['user_name']) ?></h1>
<br/><br/>
		<img src="<?php echo $userRow['picpath']; ?>" class="img-rounded" width="250px" height="250px" />
		<br/><br/><form action="home.php" method="post" enctype="multipart/form-data">
		<table>
		<tr><td>
		  <input type="file" class="button button1" name="fileToUpload" id="fileToUpload" required="required"/>
		  </td><td>
		  <input type="submit" class="button button1" class="new" name="upld-img"/>
		  </td>
		  </table>
        </form>
<!--php code for uploading file-->
<?php
if(isset($_POST["upld-img"]))
{
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "";
        $uploadOk = 1;
    } else {
        echo "<center>File is not an image.</center>";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "<center>Sorry, file already exists. Try renaming your file.</center>";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "<center>Sorry, your file is too large.</center>";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "<center>Sorry, only JPG, JPEG, PNG & GIF files are allowed.</center>";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "<center>Sorry, your file was not uploaded.</center>";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "<center><i><h4>The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded!</h4></i></center>";
    } else {
        echo "<center>Sorry, there was an error uploading your file.</font></center>";
    }
}
$imgmail=($userRow['user_email']);
$stmt=$conn->prepare("UPDATE users SET picpath=:target_file WHERE user_email=:imgmail");
		
		$stmt->bindparam(":target_file",$target_file);
		$stmt->bindparam(":imgmail",$imgmail);
        $result=$stmt->execute();
}
?>
<h3>Name:<?php print($userRow['user_name']) ?></h3>
<h3>Email: <?php print($userRow['user_email']) ?></h3>
<h3>User ID: <?php print($userRow['user_id']) ?></h3>
<button class="button button1" onclick="window.location.href='logout.php?logout=true'">Logout</button>
</center>
</body>
</html>

We are here using a session variables to manage the image upload, retrieval and display it. We here put variables in image tag and the as the session variable value changes, the image path also changes. So in this way, the value updates and makes different images appear in the place.

You can see the modified content shown by a comment in the above code. We have included the variable containing the value of session in the image ‘img’ tag so that the value will be updated by fetching it in database and it prints the new value containing the path of new image. This results into changing the image dynamically for each user.

Dynamic image

This code will check if the file exceeds the certain limit 5 Mb, then again checks if the file is an image or not, again checks the file is already exists and if all these conditions are false, then the file is successfully uploaded on the server in our specified folder.

To achieve this, we will create a folder to store the uploaded images and also we have to create one additional field in the database to save the image path.

So, create folder ‘images‘ in the same root directory and create the additional field in database structure named ‘picpath‘.  For better understanding, do not remove the comments form the code above.

That’s it! The whole tutorial will work now with the dynamic image of a user in which user can upload and update his profile image. See the screenshot below.
php full session tutorial

As usual, the source code is always freely available for download from below link.

Download Source Code


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.