Trying for users to add profile picture php - php

I want a logged in user to add a profile picture. if the user havent added a picture, the default image should display.
here is the code I tried. The default image is not showing and it is displaying the amount of users in the database. I know I should use prepared statements, but dont know how to with adding a file.
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'pt');
if(isset($_POST['upload_submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmp = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$filesError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.',$_FILES['file']['name']);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png','pdf');
if(in_array($fileActualExt,$allowed)){
if($_FILES['file']['error'] === 0){
if($_FILES['file']['size'] < 1000000){
$fileNameNew =
"profile".$_SESSION['username'].".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($_FILES['file']
['tmp_name'],$fileDestination);
$sql = "UPDATE users SET status = 0 WHERE
username='$_SESSION[username]';";
$result = mysqli_query($db, $sql);
header("Location: pic.php");
}else{
echo "Your file is too big!";
}
}else{
echo "You have an error uploading your file!";
}
}else{
echo "You cannot upload files of this type!";
}
}
?>
<?php
$sql = "SELECT * from users";
$result = mysqli_query($db, $sql);
if(mysqli_num_rows($result)> 0){
while ($row = mysqli_fetch_assoc($result)){
$sqlimg = "SELECT * FROM users WHERE
username='$_SESSION[username]'";
$resultimg=mysqli_query($db,$sqlimg);
while($rowimg = mysqli_fetch_assoc($resultimg)){
echo "<div class=container>";
if($rowimg['status'] == 0){
echo "<img src=
'uploads/profile".$_SESSION['username'].".jpg'>";
}else{
echo "<img src='uploads/male.jpg'>";
}
echo "<p>".$_SESSION['username']."</p>";
echo "</div>";
}
}
}else{
echo "There are no users yet!";
}
if(isset($_SESSION['username'])){
echo "<form action='pic.php'
method='POST'enctype='mutlipart/form-
data'>
<input type='file' name='file'>
<button type='submit' name='upload_submit'>Upload</button>
</form>";
}else {
echo "You are not logged in!";
}
?>

Related

delete image from server folder

Here is code of uploading image in my localhost/file/img folder and also inserting image path and name in my table.
<?php
if (isset($_POST['submit']))
{
$file_id = $_POST['file_id'];
if (count($_FILES['upload']['name']) > 0)
{
for ($i = 0; $i < count($_FILES['upload']['name']); $i++)
{
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != "")
{
$shortname = $_FILES['upload']['name'][$i];
$filePath = "img/" . $_FILES['upload']['name'][$i];
if (move_uploaded_file($tmpFilePath, $filePath))
{
$files[] = $shortname;
$query = "insert into images(id,img_name) values('$file_id',' $filePath')";
mysqli_query($con, $query);
}
}
}
}
echo "<h1>Uploaded:</h1>";
if (is_array($files))
{
echo "<ul>";
foreach($files as $file)
{
echo "<li>$file</li>";
}
echo "</ul>";
}
}
?>
Table Images with attribute img_name type is LONGBLOB
now its totally working fine but when i am deleting image from database its getting error that image name is not found. here is code of sending image id and image name using a href
<ul>
<a href="index.php?img_id=<?php echo urlencode($id); ?>&img=<?php echo urlencode($img); ?>"
style="color:red; margin-left:18px;" onclick="return confirm('Are you sure you want to delete this?')" >Delete
</a>
</ul>
now here is code of want i want to delete from my database and also from my localhost folder named img .
<?php
if (isset($_GET['img_id'], $_GET['img']))
{
$id = $_GET['img_id'];
$img = $_GET['img'];
$query = "delete from images where id='$id' and image='$img'";
if (mysqli_query($con, $query))
{
unlink($img);
echo '<script language="javascript">';
echo 'alert("Image Deleted successfully")';
echo '</script>';
}
else
{
echo '<script language="javascript">';
echo 'alert("image does not exist")';
echo '</script>';
}
}
?>
now showing warning that img/image_name.jpg not found.Help me please .
I think your delete query is wrong
if(isset($_GET['img_id'] , $_GET['img'])){
$id=$_GET['img_id'];
$img=$_GET['img'];
$query="delete from images where id='$id' and image='$id'";
}
$query="delete from images where id='$id' and image='$img'";
In this query you check Id and Image field with same $id variable
try this :
<?php
if (isset($_FILES['image']['name'])) {
$name = $_FILES['image']['name'];
$tmpname1 = $_FILES['image']['tmp_name'];
$exten = explode(".", $_FILES['image']['name']);
$exten = $exten[1];
if ($exten != '') {
$image_name = "img" . time() . "." . $exten;
}
move_uploaded_file($tmpname1, FCPATH . 'assets/admin/uploads/' . $image_name);
$query = "insert into images(id,img_name) values('your_id',' $image_name')";
mysqli_query($con, $query);
//see your code
/*
$id=$_GET['img_id'];
$img=$_GET['img'];
$query="delete from images where id='$id' and image='$id'";
*/
you pass the same id value for image. you should try this-
$query="delete from images where id='$id' and image='$img'";
}

Passing array using AJAX

I am used to writing AJAX using the following structure, where I would end up sending variables to PHP
function requestToggle(type, user, elem) {
_(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "request_system.php");
ajax.onreadystatechange = function () {
if (ajaxReturn(ajax) == true) {
if (ajax.responseText == "request_sent") {
_(elem).innerHTML = 'OK Request Sent';
} else if (ajax.responseText == "unrequest_ok") {
_(elem).innerHTML = '<button onclick="requestToggle(\'request\',\'<?php echo $u; ?>\',\'requestBtn\')">Request Number</button>';
} else {
alert(ajax.responseText);
_(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type=" + type + "&user=" + user);
}
The example that I want to work on is for a photo upload form and the PHP script is using the $_FILES array but I am unsure how I would go about passing this array to the PHP using AJAX.
Here is the PHP
<?php
$result = "";
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
$result = "That image has no dimensions";
echo $result;
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
$result = "Your image file was larger than 1mb";
echo $result;
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
$result = "Please only JPG, GIF or PNG images";
echo $result;
exit();
} else if ($fileErrorMsg == 1) {
$result = "An unknown error occurred";
echo $result;
exit();
}
$sql = "SELECT profilePicture FROM User WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
//delete old pic if set
if($avatar != ""){
$picurl = "users/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
//move file from temp folder to users folder
$moveResult = move_uploaded_file($fileTmpLoc, "users/$log_username/$db_file_name");
if ($moveResult != true) {
$result = "File upload failed";
echo $result;
exit();
}
include_once("image_resize.php");
//replace original file with resized version
$target_file = "users/$log_username/$db_file_name";
$resized_file = "users/$log_username/$db_file_name";
$wmax = 400;
$hmax = 600;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE User SET profilePicture='$db_file_name' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
//header("location: user.php?u=$log_username");
$result = "upload_success";
echo $result;
exit();
}
?>
UPLOAD FORM
$avatar_form = '<div class="bhoechie-tab-content" id="uploadphoto">';
$avatar_form .= '<center>';
$avatar_form .= '<form id="avatar_form"" method="post" enctype="multipart/form-data">';
$avatar_form .= '<h1>Change avatar</h1>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '<p id="status"></p>';
$avatar_form .= '</form>';
$avatar_form .= '</center></div>';
You can easily enough pass an array eg ajax.send("type=" + type + "&user=" + user + "&files=" + files);
Having not seen the rest of your code I can't provide a full answer, but I'm assuming you're somehow creating a files array in js and want to pass that to the php? If so, the variable 'files' would then be using in PHP like:
$files= $_REQUEST['files'];

Old picture is missing

So I have "staff" table in database i.e. StaffName, StaffAddress and StaffProfilePicture etc. Updating works fine on name, address but not the picure. The old picture seems to be missing from the database eventhough I don't upload a new one.
if(isset($_POST['submit'])){
$target_dir = "images/staff/";
$target_dir = $target_dir . basename($_FILES["new_profilepicture"]["name"]);
$uploadOk=1;
if (file_exists($target_dir . $_FILES["new_profilepicture"]["name"])) {
//echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($uploadOk==0) {
//echo "Sorry, your file was not uploaded.";
}
else {
if (move_uploaded_file($_FILES["new_profilepicture"]["tmp_name"], $target_dir)) {
$imageup = $target_dir;
//echo "<img src='" . $imageup . "' />";
} else {
//echo "Sorry, there was an error uploading your file.";
}
}
$_var1 = $_POST['new_name'];
$_var2 = $_POST['new_email'];
$_var3 = $_POST['new_password'];
$_var4 = $_POST['new_contactno'];
$_var5 = $_POST['new_icno'];
$_var6 = $_POST['new_address'];
$_var7 = $_POST['new_status'];
$_var8 = $imageup;
$query1 = $mysqli->query("UPDATE staff
SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7', StaffProfilePicture='$_var8'
WHERE StaffID='$staffID'");
$success = mysql_query($query1);//is mysql query working?
if($success){
//$oldprofilepicture = $staff['StaffProfilePicture'];
//if(file_exists($oldprofilepicture)){
//unlink($oldprofilepicture);//delete now
echo "success";
header('location:staff_profile.php');
die;
}else{
echo "failed";
}
}
Below is the HTML form for the picture
<tr>
<td width="170">Old Profile Picture:</td>
<td><img src="<?php echo $profilepicture ?>" width="100" height="80" /><br><br>
<input type="file" name="new_profilepicture" />
</tr>
How can I make the old/existed picture stay?
On your query you have:
StaffProfilePicture='$_var8'
so it still updates the database and since $imageup is empty/undefined so is $_var8 and it will update the database with empty value.
So add an if condition:
$_var8 = $imageup;
if($_var8 != '') {
$query1 = $mysqli->query("UPDATE staff SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7', StaffProfilePicture='$_var8' WHERE StaffID='$staffID'");
} else {
$query1 = $mysqli->query("UPDATE staff SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7' WHERE StaffID='$staffID'");
}
or you can do it other ways but that's where your problem is that you're losing your old image. Hope it helps.
Cheers.

Display all images from database (php)

I use this code to upload images in the database:
<?php
//Store the upload form
$UploadForm = " <form id='idForm' action='upload.php' method='post' enctype='multipart/form-data'>
<input type='file' name='image'/><br/><br/>
<input id='BTN' type='submit' value='Upload'/><br/><br/>
</form>";
//if logged in show the upload form
if($userid && $username){
echo $UploadForm;
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//file properties
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
//if image selected
if(isset($file) && $file != ""){
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "That's not an image!";
header( "refresh:2;url=upload.php" );
}
else{
$qry = mysqli_query($con,"SELECT * FROM store WHERE name='$image_name'");
$Nrows = $qry->num_rows;
if( $Nrows == 0){
if(!$insert = mysqli_query($con,"INSERT INTO store VALUES ('','$image_name','$username','$image')")){
echo "We had problems uploading your file!";
header( "refresh:2;url=upload.php" );
}
else{
echo "Image $image_name uploaded!";
header( "refresh:2;url=upload.php" );
}
}
else{
echo "There is already an image uploaded with the name $image_name<br/>";
}
}
}
else{
echo "Please select an image";
}
mysqli_close($con);
}
else{
echo "You have to be logged in to upload!";
}
?>
And this code to display all images from the database:
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$res = mysqli_query($con,'SELECT * FROM store');
while($row = $res->fetch_array()){
$image = $rows['image'];
echo "<img src='".$image."' />";
}
And I get something like tons of random symbols like diamonds with question marks in them and letters instead of my image. The scripts are not made by me. I just watched some tutorials and combined them and it seems that I didn't "combined" them properly. What am I doing wrong?
LATER EDIT:
HTML:
<img src="getImage.php?id=26"/>
PHP (getImage.php):
$con = mysqli_connect('***', '***', '***', '***_dbimage');
if(isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM store WHERE id=$id");
while($row = mysql_fetch_assoc($query))
{
$imageData = $row['image'];
}
header("content-type:image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
?>
Still can't get it to work! Help please!
I finaly did it!
This is the upload script:
<?php
//Store the upload form
$UploadForm = " <form id='idForm' action='upload.php' method='post' enctype='multipart/form-data'>
<input type='file' name='image'/><br/><br/>
<input id='BTN' type='submit' value='Upload'/><br/><br/>
</form>";
//if logged in show the upload form
if($userid && $username){
echo $UploadForm;
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//file properties
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
//if image selected
if(isset($file) && $file != ""){
$image = mysqli_real_escape_string($con,file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "That's not an image!";
header( "refresh:2;url=upload.php" );
}
else{
$qry = mysqli_query($con,"SELECT * FROM store WHERE name='$image_name'");
$Nrows = $qry->num_rows;
if( $Nrows == 0){
if(!$insert = mysqli_query($con,"INSERT INTO store VALUES ('','$image_name','$username','$image')")){
echo "We had problems uploading your file!";
header( "refresh:2;url=upload.php" );
}
else{
echo "Image $image_name uploaded!";
header( "refresh:2;url=upload.php" );
}
}
else{
echo "There is already an image uploaded with the name $image_name<br/>";
}
}
}
else{
echo "Please select an image";
}
mysqli_close($con);
}
else{
echo "You have to be logged in to upload!";
}
?>
Here is the diplay script:
$con = mysqli_connect('***', '***', '***', '***_dbimage');
$query = mysqli_query($con,"SELECT id FROM store");
while($row = mysqli_fetch_assoc($query))
{
$IDstore = $row['id'];
echo "<img src='getImage.php?id=".$IDstore."'/>";
}
And the "getImage.php":
<?php
$con = mysqli_connect('***', '***', '***', '***_dbimage');
if(isset($_GET['id']))
{
$id = mysqli_real_escape_string($con,$_GET['id']);
$query = mysqli_query($con,"SELECT * FROM store WHERE id=$id");
while($row = mysqli_fetch_assoc($query))
{
$imageData = $row['image'];
}
header("content-type:image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
?>
I hope it will help someone cause it's ready to use now. :)

File upload profile avatar

I'm trying to create a social network site and I've been watching tutorials where the users can upload their profile picture and change their avatar. However, whenever I try to upload a picture it gives me an error 'File upload failed' I'm not very sure how to fix it or what exactly to do. Where exactly do I need to dump all the pictures the users have uploaded?
photo_system.php
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
$sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file($fileTmpLoc, "../user/$log_username/$db_file_name");
if ($moveResult != true) {
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
user.php
$profile_pic = "";
$profile_pic_btn = "";
$avatar_form = "";
// Check to see if the viewer is the account owner
$isOwner = "no";
if($u == $log_username && $user_ok == true){
$isOwner = "yes";
$profile_pic_btn = 'Toggle Avatar Form';
$avatar_form = '<form id="avatar_form" enctype="multipart/form-data" method="post" action="php_parsers/photo_system.php">';
$avatar_form .= '<h4>Change your avatar</h4>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '</form>';
}
Create directory first if not exist
if($avatar != ""){
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
if(!file_exists($picurl)){
mkdir($picurl, 0777,true);
}
}

Categories