I am using following codes to prevent entry of duplicate username in the database but it always says "username already exists" through the particular username not exists in the database. I can not understand where I am doing wrong. Thanks in advance.
$ImageName = $ImageDir.$image_tempname;
$query = mysqli_query($conn, "SELECT * FROM usernames WHERE username='".$username."'");
$rows = mysqli_num_rows($query);
if (move_uploaded_file($_FILES['image']['tmp_name'],
$ImageName)) {
//get info about the image being uploaded
list($width, $height, $type, $attr) = getimagesize($ImageName);
//**insert these new lines
if ($type > 3) {
echo "Sorry, but the file you uploaded was not a GIF, JPG, or " .
"PNG file.<br>";
echo "Please hit your browser's 'back' button and try again.";
}
elseif ($rows > 0){
echo "email already exists";
}
else {
//image is acceptable; ok to proceed
//**end of inserted lines
//insert info into image table
$insert = "INSERT INTO xyz (.......)
VALUES (........)";
$insertresults = mysqli_query($insert); //order executes
if($insertresults)
{
header ("Location:https://www.getalifepartner.com/free-matrimonial-site/upload_success.php");
}
Here is one way
$query = mysqli_query($con, "SELECT * FROM usernames WHERE username='$username'");
$res = mysqli_fetch_array($query);
if ($res['username'] == $username)
{
echo 'Username already in use, please choose another one.';
}
else
{
// username not in use
}
Here is another way
$query = mysqli_query($con, "SELECT * FROM usernames WHERE username='$username'");
$rows = mysqli_num_rows($query);
if ($rows > 0)
{
echo 'Username already in use, please choose another one.';
}
else
{
// username not in use
}
UPDATE TO ORIGINAL QUESTION
$ImageName = $ImageDir.$image_tempname;
$query = mysqli_query($conn, "SELECT * FROM usernames WHERE username='$username'");
$rows = mysqli_num_rows($query);
if (move_uploaded_file($_FILES['image']['tmp_name'], $ImageName))
{
//get info about the image being uploaded
list($width, $height, $type, $attr) = getimagesize($ImageName);
//**insert these new lines
if ($type > 3)
{
echo "Sorry, but the file you uploaded was not a GIF, JPG, or PNG file.<br>";
echo "Please hit your browser's 'back' button and try again.";
}
}
elseif ($rows > 0)
{
echo "Email already exists.";
}
else
{
//image is acceptable; ok to proceed
//**end of inserted lines
//insert info into image table
}
Related
I want a logged in user to add a profile picture. No errors are shown, the picture is just not added to the folder where it should be.
I know I have to use prepared statements, I will. I just want to sort this problem out first.
When the user has not changed the profile pic, the default picture displays perfectly. The file profile pic just wont upload to the folder.
This is the page where you change the picture.
<?php
session_start();
include_once 'dbh.php';
<html>
<body>
<?php
$sql = "SELECT * FROM user";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$sqlImg = "SELECT * FROM profileimg WHERE userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div>";
if ($rowImg['status'] == 0) {
echo "<img src='uploads/profile".$id.".jpg'>";
}
else {
echo "<img src='uploads/male.jpg'>";
}
echo "<p>".$row['username']."</p>";
echo "</div>";
}
}
}
else {
echo "There are no users!";
}
if (isset($_SESSION['id'])) {
echo "You are logged in!";
echo '<form action="includes/upload.inc.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" name="submit">UPLOAD FILE</button>
</form>';
}
else {
echo "You are not logged in!";
}
?>
This is the php page for the upload
<?php
session_start();
include_once 'dbh.php';
$id = $_SESSION['id'];
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $file['name'];
$fileType = $file['type'];
$fileTempName = $file['tmp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png", "pdf");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 500000) {
//I now need to create a unique ID which we use to replace the name
of the uploaded file, before inserting it into our rootfolder
//If I don't do this, we might end up overwriting the file if we
upload a file later with the same name
//Here I use the user ID of the user to create the first part of the
image name
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
$result = mysqli_query($conn, $sql);
header("Location: index.php?uploadsuccess");
}
else {
echo "Your file is too big!";
}
}
else {
echo "There was an error uploading your file, try again!";
}
}
else {
echo "You cannot upload files of this type!";
}
}
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
I suspect logical issue near your below update query:
$sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
Your logic will run fine for only those users who already having corresponding record in profileimg table. But UPDATE query will do nothing for new user.
So, you will have to first check whether there is a record in profileimg for particular user. If no record then run INSERT query, if record exists then run UPDATE query..
Hello how to check whether the user has uploaded profile pic or not...I have tried this code but only displays the default pic and not the else part..please help...this is my code
$check_pic = mysqli_query($conn,"SELECT image FROM users WHERE id='$id'");
$get_pic_row = mysqli_fetch_assoc($check_pic);
$profile_pic_db = $get_pic_row['image'];
$pro_num = mysqli_num_rows($profile_pic_db);
if ($pro_num == 0) {
$profile_pic = "http://localhost/Ramdhenu/images/default_propic.png";
} else {
$profile_pic = "http://localhost/Ramdhenu/userdata/Author_images/".$profile_pic_db ;
}
You need to be checking the value of the column, not if any rows were returned. You should also be using a prepared statement instead.
$stmt = $conn->prepare("SELECT image FROM users WHERE id=?");
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($image);
if ($stmt->fetch()) {
if (empty($image)) {
$profile_pic = "/Ramdhenu/images/default_propic.png";
} else {
$profile_pic = "/Ramdhenu/userdata/Author_images/".$image;
}
} else {
// No user by that ID
}
$stmt->close();
You will always get $pro_num !=0 , you will need to check the default value if you image column ,
lets say the default value is NULL ,
$check_pic = mysqli_query($conn,"SELECT image FROM users WHERE id='$id'");
$get_pic_row = mysqli_fetch_assoc($check_pic);
$profile_pic_db = $get_pic_row['image'];
$pro_num = mysqli_num_rows($profile_pic_db);
if($pro_num == 1){
if ($profile_pic_db == null) {
$profile_pic = "http://localhost/Ramdhenu/images/default_propic.png";
} else {
$profile_pic = "http://localhost/Ramdhenu/userdata/Author_images/".$profile_pic_db ;
}
}else{
//user not found
}
i am storing image in uploads folder an then in a random directory but it is not being shown in my website this is my code
<?php
$query = "SELECT * FROM users WHERE email='$email' or username = '$email'or mobile='$email'";
$fire = mysqli_query($con,$query) or die("can not fetch data from database ".mysqli_error($con));
if (mysqli_num_rows($fire)>0) {
$users = mysqli_fetch_assoc($fire);
}
?>
<img src="<?php echo $users['avatar_path']?>" width='100' height='100' class='avatar'>
and this is my upload code
if (isset($_POST['uploadimg'])) {
$avatar = $_FILES['avatar'];
$avatar_name = $_FILES['avatar']['name'];
$avatar_tmpname = $_FILES['avatar']['tmp_name'];
$avatar_size = $_FILES['avatar']['size'];
$avatar_type = $_FILES['avatar']['type'];
$avatar_ext = pathinfo($avatar_name, PATHINFO_EXTENSION);
if (!empty($avatar_name)) {
if ($avatar_size <= 25000000) {
if ($avatar_ext == "jpg" || $avatar_ext == "jpeg" ||$avatar_ext == "png" ) {
$chars= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rand_dir_name=substr(str_shuffle($chars),0,15);
mkdir("uploads/$rand_dir_name");
$final_file= "uploads/$rand_dir_name/$avatar_name";
$upload = move_uploaded_file($avatar_tmpname, $final_file);
if ($upload) {
unlink("$avatar_path");
$msg = "file uploaded successfully ";
$query = "UPDATE users SET avatar_path='$final_file' WHERE id='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
$query = "UPDATE likes SET avatar_path='$final_file' WHERE user_id='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
$query = "UPDATE photos SET avatar_path='$final_file' WHERE uid='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
if ($fire) {
$msg .=" and also inserted into database";
}
# code...
}else{ echo "only jpg,jpeg,png, type format allowed";}
}else{echo "file size is too large";}
}else{echo "please select an image to upload";}
}
}
}
?>
this code used to work on localhost and my upload code is still working and when i inspect my page the avatar path is correct but still the pic is not being shown a broken image is shown i dont know what is being wrong this is the avatar path that is coming
uploads/Un7sL9TwyNzOhco/bhai.jpg
Try adding slash at first like below:
$final_file= "/uploads/$rand_dir_name/$avatar_name";
I have been having an issue with my code, specifically with the move_uploaded_file. I changed the folder I keep the images in's permissions to 777 to make sure it wasn't a problem with the permissions. I also read a php manual on how to use move_uploaded_file of w3schools.com. I have run out of ideas on how to upload my image to a folder using php. Please help.
Here is the portion of the code with the move_uploeaded_file:
<?php
if (#$_GET['action'] == "ci"){
echo "<form action='account.php?action=ci' method='POST' enctype='multipart/form-data'><br />
Available file extention: <stong>.PNG .JPG .JPEG</stong><br /><br />
<input type='file' name='image' /><br />
<input type='submit' name='change_pic' value='Change' /><br />
</form>";
if (isset($_POST['change_pic'])) {
$errors = array();
$allowed_e = array('png', 'jpg', 'jpeg');
$file_name = $_FILES['image']['name'];
$file_e = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$file_s = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
if(in_array($file_e, $allowed_e) === false) {
$errors[] = 'This file extension is not allowed.';
}
if ($file_s > 2097152) {
$errors[] = 'File size must be under 2MB';
}
if (empty($errors)) {
move_uploaded_file($file_tmp, '../images/'.$file_name);
$image_up = '../images/'.$file_name;
$check = mysqli_query($connect, "SELECT * FROM users WHERE usename='".#$_SESSION['username']."'");
$rows = mysqli_num_rows($check);
while($row = mysqli_fetch_assoc($check)) {
$db_image = $row['profile_pic'];
}
if($query = mysqli_query($connect, "UPDATE users SET profile_pic = '".$image_up."' WHERE username='".$_SESSION['username']."'"))
echo "You have successfuly changed your profile picture!";
} else {
foreach($errors as $error) {
echo $error, '<br />';
}
}
}
}
?>
Here's the last chunk of the code, slightly rewritten. move_uploaded_file returns a boolean, so we can test if it's true or false by setting up a variable $result:
if (empty($errors)) {
$image_up = 'images/'.$file_name;
$result = move_uploaded_file($file_tmp, $image_up);
if($result){
//this line had a typo usename -> username
//Also, you should change this over to using parameters and binding values ASAP. This leaves you open to hacking.
$check = mysqli_query($connect, "SELECT * FROM users WHERE username='".#$_SESSION['username']."'");
$rows = mysqli_num_rows($check);
while($row = mysqli_fetch_assoc($check)) {
$db_image = $row['profile_pic'];
}
$q = "UPDATE users SET profile_pic = '".$image_up."' WHERE username='".$_SESSION['username']."'";
if($query = mysqli_query($connect, $q)){
echo "You have successfuly changed your profile picture!";
}
} else {
echo "Upload failed.";
}
} else {
foreach($errors as $error) {
echo $error, '<br />';
}
}
}
}
Thanks for the support really appreciated.
I am newbie in PHP, and i heard that i can find my solution from those PHP expert who are here in Stackoverflow.
I have bought this script a while ago and now the producer stopped offering support.
Avatar upload form
http://i.stack.imgur.com/YO7PD.jpg
My Question
The script have ability to upload profile for every user but it doesn't resize the image.
If a user upload a 2 mb image so the script use 2 mb image in all over the website which makes my website to run slower.
I want that the script should resize the image to
([width=100px and height=auto] and
[width=19px and height=auto])
so i use a lighter image in size (like ~150 kb and ~55kb) and let my site run faster.
This is the avatar.php file that process the uploading
<?php
// declare variables
$msg = '';
$f_avatar_image = '';
// ------------------------------------------------------------
// UPLOAD AVATAR
// ------------------------------------------------------------
if(isset($_POST['btnUploadAvatar']) && !empty($_FILES['fileUpload']['name']))
{
// create variables
$avatar_directory = AVATAR_FILE_DIRECTORY;
$file_name = $_FILES['fileUpload']['name'];
$file_type = $_FILES['fileUpload']['type'];
$file_size = $_FILES['fileUpload']['size'];
$file_size_limit = AVATAR_FILE_SIZE;
$calc_kilobites = 1024;
$file_size_kb = round($file_size / $calc_kilobites, 2);
$temp_file_name = $_FILES['fileUpload']['tmp_name'];
$upload_error = $_FILES['fileUpload']['error'];
// create unique file name
$unique_file_name = $user_name.'-'.$file_name;
$avatar_img_url = AVATAR_IMAGE_URL.$user_name.'-'.$file_name;
// if upload error display error message
if($upload_error > 0)
{
echo 'ERROR:' . $upload_error;
}
// if no upload error - check for file types
if($upload_error == 0 &&
$file_type == 'image/gif' ||
$file_type == 'image/jpeg' ||
$file_type == 'image/png' )
{
// if file size is within limits
if($file_size <= $file_size_limit)
{
// move uploaded file to assigned directory
if(move_uploaded_file($temp_file_name, $avatar_directory . $unique_file_name))
{
// get user id
$get_user_id = mysqli_query($conn, "SELECT UserId FROM users WHERE UserName = '$user_name' Limit 1") or die($dataaccess_error);
// if user id exist
if(mysqli_num_rows($get_user_id) == 1 )
{
$row = mysqli_fetch_array($get_user_id);
$user_id = $row['UserId'];
// check if user profile already exist
$check_user_profile = mysqli_query($conn, "SELECT UserId FROM profiles WHERE UserName = '$user_name' Limit 1") or die($dataaccess_error);
// if user profile exist - update
if(mysqli_num_rows($check_user_profile) == 1 )
{
// update profiles
$update_profile = mysqli_query($conn, "UPDATE profiles SET AvatarImage = '$avatar_img_url' WHERE UserName = '$user_name'") or die($dataaccess_error);
if(mysqli_affected_rows($conn) > 0)
{
echo 'Upload Success! <br/>';
echo 'File Name: '.$file_name.'<br/>';
echo 'File Type: '.$file_type.'<br/>';
echo 'File Size: '.$file_size_kb.' Kb <br/>';
$msg = $profile_update_success;
}
else
{
$msg = $profile_update_failed;
}
}
else
{
// create profile
$insert_profile = mysqli_query($conn, "INSERT INTO profiles(UserId,UserName,AvatarImage) VALUES($user_id,'$user_name','$avatar_img_url')") or die($dataaccess_error);
if(mysqli_affected_rows($conn) > 0)
{
echo 'Upload Success! <br/>';
echo 'File Name: '.$file_name.'<br/>';
echo 'File Type: '.$file_type.'<br/>';
echo 'File Size: '.$file_size_kb.' Kb <br/>';
$msg = $profile_update_success;
}
else
{
$msg = $profile_create_failed;
}
}
}
else
{
// user id not found
$msg = $profile_update_failed2;
}
}
else
{
$msg = $avatar_upload_failed;
}
}
else
{
$msg = $avatar_file_too_large;
}
}
else
{
$msg = $avatar_wrong_file_type;
}
}
elseif(isset($_POST['btnUploadAvatar']) && empty($_FILES['fileUpload']['name']))
{
$msg = $avatar_empty;
}
// ------------------------------------------------------------
// DISPLAY AVATAR ON PAGE LOAD
// ------------------------------------------------------------
if($user_name)
{
// get user id
$get_avatar_image = mysqli_query($conn, "SELECT AvatarImage FROM profiles WHERE UserName = '$user_name' Limit 1") or die($dataaccess_error);
if(mysqli_num_rows($get_avatar_image) == 1)
{
$row = mysqli_fetch_array($get_avatar_image);
if($row['AvatarImage'] != 'NULL' && $row['AvatarImage'] != '')
{
$f_avatar_image = $row['AvatarImage'];
}
else
{
$f_avatar_image = AVATAR_IMAGE_URL.DEFAULT_AVATAR_IMAGE;
}
}
else
{
$f_avatar_image = AVATAR_IMAGE_URL.DEFAULT_AVATAR_IMAGE;
}
}
?>
This is the avatar.html.php file form
<?php require_once(ROOT_PATH.'user/modules/accordion/avatar.php'); ?>
<div class="profileWrap">
<form name="frmAvatar" method="post" action="" enctype="multipart/form-data" class="htmlForm">
<div class="infoBanner2">
<p>REQUIREMENTS: File Size: <?php echo AVATAR_FILE_SIZE / 1024 ?> kb max. File Type: gif, jpg, png</p>
</div>
<!-- error msgs -->
<ul>
<?php echo $msg; ?>
</ul>
<p><input name="selectFile" type="image" src="<?php echo $f_avatar_image; ?>" class="img"></p>
<p><label for="fileUpload">Avatar Image:</label><input name="fileUpload" type="file" id="fileUpload" maxlength="255" ></p>
<input name="btnUploadAvatar" type="submit" value="Upload" class="gvbtn btn" onclick="return confirm('Are You READY to UPLOAD?');"/>
</form>
</div>
The avatar.php file is linked to a configuration file (web.config.php) file
// ------------------------------------------------------------
// 16. AVATAR IMAGE FILE
// ------------------------------------------------------------
define('AVATAR_FILE_SIZE', 2097152); // 50 Kb max. -> 1 kilobyte = 1024 bytes
define('AVATAR_FILE_DIRECTORY', ROOT_PATH.'user/upload/avatars/'); // upload directory
define('AVATAR_IMAGE_URL', SITE_URL.'user/upload/avatars/'); // default avatar url
define('DEFAULT_AVATAR_IMAGE', 'default-avatar.png'); // default avatar image
If you needed to ask anything i am ready to answer.
Let me thank the one who answer it.
Take a look at this lib and doc
https://github.com/Nimrod007/PHP_image_resize